]> Pileus Git - ~andy/linux/blob - drivers/staging/octeon-usb/octeon-hcd.c
Merge remote-tracking branches 'spi/fix/ath79', 'spi/fix/atmel', 'spi/fix/coldfire...
[~andy/linux] / drivers / staging / octeon-usb / octeon-hcd.c
1 /*
2  * This file is subject to the terms and conditions of the GNU General Public
3  * License.  See the file "COPYING" in the main directory of this archive
4  * for more details.
5  *
6  * Copyright (C) 2008 Cavium Networks
7  *
8  * Some parts of the code were originally released under BSD license:
9  *
10  * Copyright (c) 2003-2010 Cavium Networks (support@cavium.com). All rights
11  * reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions are
15  * met:
16  *
17  *   * Redistributions of source code must retain the above copyright
18  *     notice, this list of conditions and the following disclaimer.
19  *
20  *   * Redistributions in binary form must reproduce the above
21  *     copyright notice, this list of conditions and the following
22  *     disclaimer in the documentation and/or other materials provided
23  *     with the distribution.
24  *
25  *   * Neither the name of Cavium Networks nor the names of
26  *     its contributors may be used to endorse or promote products
27  *     derived from this software without specific prior written
28  *     permission.
29  *
30  * This Software, including technical data, may be subject to U.S. export
31  * control laws, including the U.S. Export Administration Act and its associated
32  * regulations, and may be subject to export or import regulations in other
33  * countries.
34  *
35  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED "AS IS"
36  * AND WITH ALL FAULTS AND CAVIUM NETWORKS MAKES NO PROMISES, REPRESENTATIONS OR
37  * WARRANTIES, EITHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, WITH RESPECT TO
38  * THE SOFTWARE, INCLUDING ITS CONDITION, ITS CONFORMITY TO ANY REPRESENTATION
39  * OR DESCRIPTION, OR THE EXISTENCE OF ANY LATENT OR PATENT DEFECTS, AND CAVIUM
40  * SPECIFICALLY DISCLAIMS ALL IMPLIED (IF ANY) WARRANTIES OF TITLE,
41  * MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, LACK OF
42  * VIRUSES, ACCURACY OR COMPLETENESS, QUIET ENJOYMENT, QUIET POSSESSION OR
43  * CORRESPONDENCE TO DESCRIPTION. THE ENTIRE RISK ARISING OUT OF USE OR
44  * PERFORMANCE OF THE SOFTWARE LIES WITH YOU.
45  */
46 #include <linux/kernel.h>
47 #include <linux/module.h>
48 #include <linux/init.h>
49 #include <linux/pci.h>
50 #include <linux/interrupt.h>
51 #include <linux/platform_device.h>
52 #include <linux/usb.h>
53
54 #include <linux/time.h>
55 #include <linux/delay.h>
56
57 #include <asm/octeon/cvmx.h>
58 #include <asm/octeon/cvmx-iob-defs.h>
59
60 #include <linux/usb/hcd.h>
61
62 #include <linux/err.h>
63
64 #include <asm/octeon/octeon.h>
65 #include <asm/octeon/cvmx-helper.h>
66 #include <asm/octeon/cvmx-sysinfo.h>
67 #include <asm/octeon/cvmx-helper-board.h>
68
69 #include "octeon-hcd.h"
70
71 /**
72  * enum cvmx_usb_speed - the possible USB device speeds
73  *
74  * @CVMX_USB_SPEED_HIGH: Device is operation at 480Mbps
75  * @CVMX_USB_SPEED_FULL: Device is operation at 12Mbps
76  * @CVMX_USB_SPEED_LOW:  Device is operation at 1.5Mbps
77  */
78 enum cvmx_usb_speed {
79         CVMX_USB_SPEED_HIGH = 0,
80         CVMX_USB_SPEED_FULL = 1,
81         CVMX_USB_SPEED_LOW = 2,
82 };
83
84 /**
85  * enum cvmx_usb_transfer - the possible USB transfer types
86  *
87  * @CVMX_USB_TRANSFER_CONTROL:     USB transfer type control for hub and status
88  *                                 transfers
89  * @CVMX_USB_TRANSFER_ISOCHRONOUS: USB transfer type isochronous for low
90  *                                 priority periodic transfers
91  * @CVMX_USB_TRANSFER_BULK:        USB transfer type bulk for large low priority
92  *                                 transfers
93  * @CVMX_USB_TRANSFER_INTERRUPT:   USB transfer type interrupt for high priority
94  *                                 periodic transfers
95  */
96 enum cvmx_usb_transfer {
97         CVMX_USB_TRANSFER_CONTROL = 0,
98         CVMX_USB_TRANSFER_ISOCHRONOUS = 1,
99         CVMX_USB_TRANSFER_BULK = 2,
100         CVMX_USB_TRANSFER_INTERRUPT = 3,
101 };
102
103 /**
104  * enum cvmx_usb_direction - the transfer directions
105  *
106  * @CVMX_USB_DIRECTION_OUT: Data is transferring from Octeon to the device/host
107  * @CVMX_USB_DIRECTION_IN:  Data is transferring from the device/host to Octeon
108  */
109 enum cvmx_usb_direction {
110         CVMX_USB_DIRECTION_OUT,
111         CVMX_USB_DIRECTION_IN,
112 };
113
114 /**
115  * enum cvmx_usb_complete - possible callback function status codes
116  *
117  * @CVMX_USB_COMPLETE_SUCCESS:    The transaction / operation finished without
118  *                                any errors
119  * @CVMX_USB_COMPLETE_SHORT:      FIXME: This is currently not implemented
120  * @CVMX_USB_COMPLETE_CANCEL:     The transaction was canceled while in flight
121  *                                by a user call to cvmx_usb_cancel
122  * @CVMX_USB_COMPLETE_ERROR:      The transaction aborted with an unexpected
123  *                                error status
124  * @CVMX_USB_COMPLETE_STALL:      The transaction received a USB STALL response
125  *                                from the device
126  * @CVMX_USB_COMPLETE_XACTERR:    The transaction failed with an error from the
127  *                                device even after a number of retries
128  * @CVMX_USB_COMPLETE_DATATGLERR: The transaction failed with a data toggle
129  *                                error even after a number of retries
130  * @CVMX_USB_COMPLETE_BABBLEERR:  The transaction failed with a babble error
131  * @CVMX_USB_COMPLETE_FRAMEERR:   The transaction failed with a frame error
132  *                                even after a number of retries
133  */
134 enum cvmx_usb_complete {
135         CVMX_USB_COMPLETE_SUCCESS,
136         CVMX_USB_COMPLETE_SHORT,
137         CVMX_USB_COMPLETE_CANCEL,
138         CVMX_USB_COMPLETE_ERROR,
139         CVMX_USB_COMPLETE_STALL,
140         CVMX_USB_COMPLETE_XACTERR,
141         CVMX_USB_COMPLETE_DATATGLERR,
142         CVMX_USB_COMPLETE_BABBLEERR,
143         CVMX_USB_COMPLETE_FRAMEERR,
144 };
145
146 /**
147  * struct cvmx_usb_port_status - the USB port status information
148  *
149  * @port_enabled:       1 = Usb port is enabled, 0 = disabled
150  * @port_over_current:  1 = Over current detected, 0 = Over current not
151  *                      detected. Octeon doesn't support over current detection.
152  * @port_powered:       1 = Port power is being supplied to the device, 0 =
153  *                      power is off. Octeon doesn't support turning port power
154  *                      off.
155  * @port_speed:         Current port speed.
156  * @connected:          1 = A device is connected to the port, 0 = No device is
157  *                      connected.
158  * @connect_change:     1 = Device connected state changed since the last set
159  *                      status call.
160  */
161 struct cvmx_usb_port_status {
162         uint32_t reserved               : 25;
163         uint32_t port_enabled           : 1;
164         uint32_t port_over_current      : 1;
165         uint32_t port_powered           : 1;
166         enum cvmx_usb_speed port_speed  : 2;
167         uint32_t connected              : 1;
168         uint32_t connect_change         : 1;
169 };
170
171 /**
172  * union cvmx_usb_control_header - the structure of a Control packet header
173  *
174  * @s.request_type:     Bit 7 tells the direction: 1=IN, 0=OUT
175  * @s.request           The standard usb request to make
176  * @s.value             Value parameter for the request in little endian format
177  * @s.index             Index for the request in little endian format
178  * @s.length            Length of the data associated with this request in
179  *                      little endian format
180  */
181 union cvmx_usb_control_header {
182         uint64_t u64;
183         struct {
184                 uint64_t request_type   : 8;
185                 uint64_t request        : 8;
186                 uint64_t value          : 16;
187                 uint64_t index          : 16;
188                 uint64_t length         : 16;
189         } s;
190 };
191
192 /**
193  * struct cvmx_usb_iso_packet - descriptor for Isochronous packets
194  *
195  * @offset:     This is the offset in bytes into the main buffer where this data
196  *              is stored.
197  * @length:     This is the length in bytes of the data.
198  * @status:     This is the status of this individual packet transfer.
199  */
200 struct cvmx_usb_iso_packet {
201         int offset;
202         int length;
203         enum cvmx_usb_complete status;
204 };
205
206 /**
207  * enum cvmx_usb_initialize_flags - flags used by the initialization function
208  *
209  * @CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_XI:    The USB port uses a 12MHz crystal
210  *                                            as clock source at USB_XO and
211  *                                            USB_XI.
212  * @CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_GND:   The USB port uses 12/24/48MHz 2.5V
213  *                                            board clock source at USB_XO.
214  *                                            USB_XI should be tied to GND.
215  * @CVMX_USB_INITIALIZE_FLAGS_CLOCK_MHZ_MASK: Mask for clock speed field
216  * @CVMX_USB_INITIALIZE_FLAGS_CLOCK_12MHZ:    Speed of reference clock or
217  *                                            crystal
218  * @CVMX_USB_INITIALIZE_FLAGS_CLOCK_24MHZ:    Speed of reference clock
219  * @CVMX_USB_INITIALIZE_FLAGS_CLOCK_48MHZ:    Speed of reference clock
220  * @CVMX_USB_INITIALIZE_FLAGS_NO_DMA:         Disable DMA and used polled IO for
221  *                                            data transfer use for the USB
222  */
223 enum cvmx_usb_initialize_flags {
224         CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_XI           = 1 << 0,
225         CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_GND          = 1 << 1,
226         CVMX_USB_INITIALIZE_FLAGS_CLOCK_MHZ_MASK        = 3 << 3,
227         CVMX_USB_INITIALIZE_FLAGS_CLOCK_12MHZ           = 1 << 3,
228         CVMX_USB_INITIALIZE_FLAGS_CLOCK_24MHZ           = 2 << 3,
229         CVMX_USB_INITIALIZE_FLAGS_CLOCK_48MHZ           = 3 << 3,
230         /* Bits 3-4 used to encode the clock frequency */
231         CVMX_USB_INITIALIZE_FLAGS_NO_DMA                = 1 << 5,
232 };
233
234 /**
235  * enum cvmx_usb_pipe_flags - internal flags for a pipe.
236  *
237  * @__CVMX_USB_PIPE_FLAGS_SCHEDULED: Used internally to determine if a pipe is
238  *                                   actively using hardware. Do not use.
239  * @__CVMX_USB_PIPE_FLAGS_NEED_PING: Used internally to determine if a high
240  *                                   speed pipe is in the ping state. Do not
241  *                                   use.
242  */
243 enum cvmx_usb_pipe_flags {
244         __CVMX_USB_PIPE_FLAGS_SCHEDULED = 1 << 17,
245         __CVMX_USB_PIPE_FLAGS_NEED_PING = 1 << 18,
246 };
247
248 /* Normal prefetch that use the pref instruction. */
249 #define CVMX_PREFETCH(address, offset) asm volatile ("pref %[type], %[off](%[rbase])" : : [rbase] "d" (address), [off] "I" (offset), [type] "n" (0))
250
251 /* Maximum number of times to retry failed transactions */
252 #define MAX_RETRIES             3
253
254 /* Maximum number of hardware channels supported by the USB block */
255 #define MAX_CHANNELS            8
256
257 /* The highest valid USB device address */
258 #define MAX_USB_ADDRESS         127
259
260 /* The highest valid USB endpoint number */
261 #define MAX_USB_ENDPOINT        15
262
263 /* The highest valid port number on a hub */
264 #define MAX_USB_HUB_PORT        15
265
266 /*
267  * The low level hardware can transfer a maximum of this number of bytes in each
268  * transfer. The field is 19 bits wide
269  */
270 #define MAX_TRANSFER_BYTES      ((1<<19)-1)
271
272 /*
273  * The low level hardware can transfer a maximum of this number of packets in
274  * each transfer. The field is 10 bits wide
275  */
276 #define MAX_TRANSFER_PACKETS    ((1<<10)-1)
277
278 /**
279  * Logical transactions may take numerous low level
280  * transactions, especially when splits are concerned. This
281  * enum represents all of the possible stages a transaction can
282  * be in. Note that split completes are always even. This is so
283  * the NAK handler can backup to the previous low level
284  * transaction with a simple clearing of bit 0.
285  */
286 enum cvmx_usb_stage {
287         CVMX_USB_STAGE_NON_CONTROL,
288         CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE,
289         CVMX_USB_STAGE_SETUP,
290         CVMX_USB_STAGE_SETUP_SPLIT_COMPLETE,
291         CVMX_USB_STAGE_DATA,
292         CVMX_USB_STAGE_DATA_SPLIT_COMPLETE,
293         CVMX_USB_STAGE_STATUS,
294         CVMX_USB_STAGE_STATUS_SPLIT_COMPLETE,
295 };
296
297 /**
298  * struct cvmx_usb_transaction - describes each pending USB transaction
299  *                               regardless of type. These are linked together
300  *                               to form a list of pending requests for a pipe.
301  *
302  * @node:               List node for transactions in the pipe.
303  * @type:               Type of transaction, duplicated of the pipe.
304  * @flags:              State flags for this transaction.
305  * @buffer:             User's physical buffer address to read/write.
306  * @buffer_length:      Size of the user's buffer in bytes.
307  * @control_header:     For control transactions, physical address of the 8
308  *                      byte standard header.
309  * @iso_start_frame:    For ISO transactions, the starting frame number.
310  * @iso_number_packets: For ISO transactions, the number of packets in the
311  *                      request.
312  * @iso_packets:        For ISO transactions, the sub packets in the request.
313  * @actual_bytes:       Actual bytes transfer for this transaction.
314  * @stage:              For control transactions, the current stage.
315  * @urb:                URB.
316  */
317 struct cvmx_usb_transaction {
318         struct list_head node;
319         enum cvmx_usb_transfer type;
320         uint64_t buffer;
321         int buffer_length;
322         uint64_t control_header;
323         int iso_start_frame;
324         int iso_number_packets;
325         struct cvmx_usb_iso_packet *iso_packets;
326         int xfersize;
327         int pktcnt;
328         int retries;
329         int actual_bytes;
330         enum cvmx_usb_stage stage;
331         struct urb *urb;
332 };
333
334 /**
335  * struct cvmx_usb_pipe - a pipe represents a virtual connection between Octeon
336  *                        and some USB device. It contains a list of pending
337  *                        request to the device.
338  *
339  * @node:               List node for pipe list
340  * @next:               Pipe after this one in the list
341  * @transactions:       List of pending transactions
342  * @interval:           For periodic pipes, the interval between packets in
343  *                      frames
344  * @next_tx_frame:      The next frame this pipe is allowed to transmit on
345  * @flags:              State flags for this pipe
346  * @device_speed:       Speed of device connected to this pipe
347  * @transfer_type:      Type of transaction supported by this pipe
348  * @transfer_dir:       IN or OUT. Ignored for Control
349  * @multi_count:        Max packet in a row for the device
350  * @max_packet:         The device's maximum packet size in bytes
351  * @device_addr:        USB device address at other end of pipe
352  * @endpoint_num:       USB endpoint number at other end of pipe
353  * @hub_device_addr:    Hub address this device is connected to
354  * @hub_port:           Hub port this device is connected to
355  * @pid_toggle:         This toggles between 0/1 on every packet send to track
356  *                      the data pid needed
357  * @channel:            Hardware DMA channel for this pipe
358  * @split_sc_frame:     The low order bits of the frame number the split
359  *                      complete should be sent on
360  */
361 struct cvmx_usb_pipe {
362         struct list_head node;
363         struct list_head transactions;
364         uint64_t interval;
365         uint64_t next_tx_frame;
366         enum cvmx_usb_pipe_flags flags;
367         enum cvmx_usb_speed device_speed;
368         enum cvmx_usb_transfer transfer_type;
369         enum cvmx_usb_direction transfer_dir;
370         int multi_count;
371         uint16_t max_packet;
372         uint8_t device_addr;
373         uint8_t endpoint_num;
374         uint8_t hub_device_addr;
375         uint8_t hub_port;
376         uint8_t pid_toggle;
377         uint8_t channel;
378         int8_t split_sc_frame;
379 };
380
381 struct cvmx_usb_tx_fifo {
382         struct {
383                 int channel;
384                 int size;
385                 uint64_t address;
386         } entry[MAX_CHANNELS+1];
387         int head;
388         int tail;
389 };
390
391 /**
392  * struct cvmx_usb_state - the state of the USB block
393  *
394  * init_flags:             Flags passed to initialize.
395  * index:                  Which USB block this is for.
396  * idle_hardware_channels: Bit set for every idle hardware channel.
397  * usbcx_hprt:             Stored port status so we don't need to read a CSR to
398  *                         determine splits.
399  * pipe_for_channel:       Map channels to pipes.
400  * pipe:                   Storage for pipes.
401  * indent:                 Used by debug output to indent functions.
402  * port_status:            Last port status used for change notification.
403  * idle_pipes:             List of open pipes that have no transactions.
404  * active_pipes:           Active pipes indexed by transfer type.
405  * frame_number:           Increments every SOF interrupt for time keeping.
406  * active_split:           Points to the current active split, or NULL.
407  */
408 struct cvmx_usb_state {
409         int init_flags;
410         int index;
411         int idle_hardware_channels;
412         union cvmx_usbcx_hprt usbcx_hprt;
413         struct cvmx_usb_pipe *pipe_for_channel[MAX_CHANNELS];
414         int indent;
415         struct cvmx_usb_port_status port_status;
416         struct list_head idle_pipes;
417         struct list_head active_pipes[4];
418         uint64_t frame_number;
419         struct cvmx_usb_transaction *active_split;
420         struct cvmx_usb_tx_fifo periodic;
421         struct cvmx_usb_tx_fifo nonperiodic;
422 };
423
424 struct octeon_hcd {
425         spinlock_t lock;
426         struct cvmx_usb_state usb;
427         struct tasklet_struct dequeue_tasklet;
428         struct list_head dequeue_list;
429 };
430
431 /* This macro spins on a field waiting for it to reach a value */
432 #define CVMX_WAIT_FOR_FIELD32(address, type, field, op, value, timeout_usec)\
433         ({int result;                                                       \
434         do {                                                                \
435                 uint64_t done = cvmx_get_cycle() + (uint64_t)timeout_usec * \
436                         octeon_get_clock_rate() / 1000000;                  \
437                 type c;                                                     \
438                 while (1) {                                                 \
439                         c.u32 = __cvmx_usb_read_csr32(usb, address);        \
440                         if (c.s.field op (value)) {                         \
441                                 result = 0;                                 \
442                                 break;                                      \
443                         } else if (cvmx_get_cycle() > done) {               \
444                                 result = -1;                                \
445                                 break;                                      \
446                         } else                                              \
447                                 cvmx_wait(100);                             \
448                 }                                                           \
449         } while (0);                                                        \
450         result; })
451
452 /*
453  * This macro logically sets a single field in a CSR. It does the sequence
454  * read, modify, and write
455  */
456 #define USB_SET_FIELD32(address, type, field, value)            \
457         do {                                                    \
458                 type c;                                         \
459                 c.u32 = __cvmx_usb_read_csr32(usb, address);    \
460                 c.s.field = value;                              \
461                 __cvmx_usb_write_csr32(usb, address, c.u32);    \
462         } while (0)
463
464 /* Returns the IO address to push/pop stuff data from the FIFOs */
465 #define USB_FIFO_ADDRESS(channel, usb_index) (CVMX_USBCX_GOTGCTL(usb_index) + ((channel)+1)*0x1000)
466
467 /**
468  * Read a USB 32bit CSR. It performs the necessary address swizzle
469  * for 32bit CSRs and logs the value in a readable format if
470  * debugging is on.
471  *
472  * @usb:     USB block this access is for
473  * @address: 64bit address to read
474  *
475  * Returns: Result of the read
476  */
477 static inline uint32_t __cvmx_usb_read_csr32(struct cvmx_usb_state *usb,
478                                              uint64_t address)
479 {
480         uint32_t result = cvmx_read64_uint32(address ^ 4);
481         return result;
482 }
483
484
485 /**
486  * Write a USB 32bit CSR. It performs the necessary address
487  * swizzle for 32bit CSRs and logs the value in a readable format
488  * if debugging is on.
489  *
490  * @usb:     USB block this access is for
491  * @address: 64bit address to write
492  * @value:   Value to write
493  */
494 static inline void __cvmx_usb_write_csr32(struct cvmx_usb_state *usb,
495                                           uint64_t address, uint32_t value)
496 {
497         cvmx_write64_uint32(address ^ 4, value);
498         cvmx_read64_uint64(CVMX_USBNX_DMA0_INB_CHN0(usb->index));
499 }
500
501
502 /**
503  * Read a USB 64bit CSR. It logs the value in a readable format if
504  * debugging is on.
505  *
506  * @usb:     USB block this access is for
507  * @address: 64bit address to read
508  *
509  * Returns: Result of the read
510  */
511 static inline uint64_t __cvmx_usb_read_csr64(struct cvmx_usb_state *usb,
512                                              uint64_t address)
513 {
514         uint64_t result = cvmx_read64_uint64(address);
515         return result;
516 }
517
518
519 /**
520  * Write a USB 64bit CSR. It logs the value in a readable format
521  * if debugging is on.
522  *
523  * @usb:     USB block this access is for
524  * @address: 64bit address to write
525  * @value:   Value to write
526  */
527 static inline void __cvmx_usb_write_csr64(struct cvmx_usb_state *usb,
528                                           uint64_t address, uint64_t value)
529 {
530         cvmx_write64_uint64(address, value);
531 }
532
533 /**
534  * Return non zero if this pipe connects to a non HIGH speed
535  * device through a high speed hub.
536  *
537  * @usb:    USB block this access is for
538  * @pipe:   Pipe to check
539  *
540  * Returns: Non zero if we need to do split transactions
541  */
542 static inline int __cvmx_usb_pipe_needs_split(struct cvmx_usb_state *usb,
543                                               struct cvmx_usb_pipe *pipe)
544 {
545         return pipe->device_speed != CVMX_USB_SPEED_HIGH &&
546                usb->usbcx_hprt.s.prtspd == CVMX_USB_SPEED_HIGH;
547 }
548
549
550 /**
551  * Trivial utility function to return the correct PID for a pipe
552  *
553  * @pipe:   pipe to check
554  *
555  * Returns: PID for pipe
556  */
557 static inline int __cvmx_usb_get_data_pid(struct cvmx_usb_pipe *pipe)
558 {
559         if (pipe->pid_toggle)
560                 return 2; /* Data1 */
561         else
562                 return 0; /* Data0 */
563 }
564
565 /**
566  * Initialize a USB port for use. This must be called before any
567  * other access to the Octeon USB port is made. The port starts
568  * off in the disabled state.
569  *
570  * @usb:         Pointer to an empty struct cvmx_usb_state
571  *               that will be populated by the initialize call.
572  *               This structure is then passed to all other USB
573  *               functions.
574  * @usb_port_number:
575  *               Which Octeon USB port to initialize.
576  *
577  * Returns: 0 or a negative error code.
578  */
579 static int cvmx_usb_initialize(struct cvmx_usb_state *usb,
580                                int usb_port_number,
581                                enum cvmx_usb_initialize_flags flags)
582 {
583         union cvmx_usbnx_clk_ctl usbn_clk_ctl;
584         union cvmx_usbnx_usbp_ctl_status usbn_usbp_ctl_status;
585         int i;
586
587         /* At first allow 0-1 for the usb port number */
588         if ((usb_port_number < 0) || (usb_port_number > 1))
589                 return -EINVAL;
590
591         memset(usb, 0, sizeof(*usb));
592         usb->init_flags = flags;
593
594         /* Initialize the USB state structure */
595         usb->index = usb_port_number;
596         INIT_LIST_HEAD(&usb->idle_pipes);
597         for (i = 0; i < ARRAY_SIZE(usb->active_pipes); i++)
598                 INIT_LIST_HEAD(&usb->active_pipes[i]);
599
600         /*
601          * Power On Reset and PHY Initialization
602          *
603          * 1. Wait for DCOK to assert (nothing to do)
604          *
605          * 2a. Write USBN0/1_CLK_CTL[POR] = 1 and
606          *     USBN0/1_CLK_CTL[HRST,PRST,HCLK_RST] = 0
607          */
608         usbn_clk_ctl.u64 = __cvmx_usb_read_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index));
609         usbn_clk_ctl.s.por = 1;
610         usbn_clk_ctl.s.hrst = 0;
611         usbn_clk_ctl.s.prst = 0;
612         usbn_clk_ctl.s.hclk_rst = 0;
613         usbn_clk_ctl.s.enable = 0;
614         /*
615          * 2b. Select the USB reference clock/crystal parameters by writing
616          *     appropriate values to USBN0/1_CLK_CTL[P_C_SEL, P_RTYPE, P_COM_ON]
617          */
618         if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_GND) {
619                 /*
620                  * The USB port uses 12/24/48MHz 2.5V board clock
621                  * source at USB_XO. USB_XI should be tied to GND.
622                  * Most Octeon evaluation boards require this setting
623                  */
624                 if (OCTEON_IS_MODEL(OCTEON_CN3XXX) ||
625                     OCTEON_IS_MODEL(OCTEON_CN56XX) ||
626                     OCTEON_IS_MODEL(OCTEON_CN50XX))
627                         /* From CN56XX,CN50XX,CN31XX,CN30XX manuals */
628                         usbn_clk_ctl.s.p_rtype = 2; /* p_rclk=1 & p_xenbn=0 */
629                 else
630                         /* From CN52XX manual */
631                         usbn_clk_ctl.s.p_rtype = 1;
632
633                 switch (flags & CVMX_USB_INITIALIZE_FLAGS_CLOCK_MHZ_MASK) {
634                 case CVMX_USB_INITIALIZE_FLAGS_CLOCK_12MHZ:
635                         usbn_clk_ctl.s.p_c_sel = 0;
636                         break;
637                 case CVMX_USB_INITIALIZE_FLAGS_CLOCK_24MHZ:
638                         usbn_clk_ctl.s.p_c_sel = 1;
639                         break;
640                 case CVMX_USB_INITIALIZE_FLAGS_CLOCK_48MHZ:
641                         usbn_clk_ctl.s.p_c_sel = 2;
642                         break;
643                 }
644         } else {
645                 /*
646                  * The USB port uses a 12MHz crystal as clock source
647                  * at USB_XO and USB_XI
648                  */
649                 if (OCTEON_IS_MODEL(OCTEON_CN3XXX))
650                         /* From CN31XX,CN30XX manual */
651                         usbn_clk_ctl.s.p_rtype = 3; /* p_rclk=1 & p_xenbn=1 */
652                 else
653                         /* From CN56XX,CN52XX,CN50XX manuals. */
654                         usbn_clk_ctl.s.p_rtype = 0;
655
656                 usbn_clk_ctl.s.p_c_sel = 0;
657         }
658         /*
659          * 2c. Select the HCLK via writing USBN0/1_CLK_CTL[DIVIDE, DIVIDE2] and
660          *     setting USBN0/1_CLK_CTL[ENABLE] = 1. Divide the core clock down
661          *     such that USB is as close as possible to 125Mhz
662          */
663         {
664                 int divisor = (octeon_get_clock_rate()+125000000-1)/125000000;
665                 /* Lower than 4 doesn't seem to work properly */
666                 if (divisor < 4)
667                         divisor = 4;
668                 usbn_clk_ctl.s.divide = divisor;
669                 usbn_clk_ctl.s.divide2 = 0;
670         }
671         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
672                                usbn_clk_ctl.u64);
673         /* 2d. Write USBN0/1_CLK_CTL[HCLK_RST] = 1 */
674         usbn_clk_ctl.s.hclk_rst = 1;
675         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
676                                usbn_clk_ctl.u64);
677         /* 2e.  Wait 64 core-clock cycles for HCLK to stabilize */
678         cvmx_wait(64);
679         /*
680          * 3. Program the power-on reset field in the USBN clock-control
681          *    register:
682          *    USBN_CLK_CTL[POR] = 0
683          */
684         usbn_clk_ctl.s.por = 0;
685         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
686                                usbn_clk_ctl.u64);
687         /* 4. Wait 1 ms for PHY clock to start */
688         mdelay(1);
689         /*
690          * 5. Program the Reset input from automatic test equipment field in the
691          *    USBP control and status register:
692          *    USBN_USBP_CTL_STATUS[ATE_RESET] = 1
693          */
694         usbn_usbp_ctl_status.u64 = __cvmx_usb_read_csr64(usb, CVMX_USBNX_USBP_CTL_STATUS(usb->index));
695         usbn_usbp_ctl_status.s.ate_reset = 1;
696         __cvmx_usb_write_csr64(usb, CVMX_USBNX_USBP_CTL_STATUS(usb->index),
697                                usbn_usbp_ctl_status.u64);
698         /* 6. Wait 10 cycles */
699         cvmx_wait(10);
700         /*
701          * 7. Clear ATE_RESET field in the USBN clock-control register:
702          *    USBN_USBP_CTL_STATUS[ATE_RESET] = 0
703          */
704         usbn_usbp_ctl_status.s.ate_reset = 0;
705         __cvmx_usb_write_csr64(usb, CVMX_USBNX_USBP_CTL_STATUS(usb->index),
706                                usbn_usbp_ctl_status.u64);
707         /*
708          * 8. Program the PHY reset field in the USBN clock-control register:
709          *    USBN_CLK_CTL[PRST] = 1
710          */
711         usbn_clk_ctl.s.prst = 1;
712         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
713                                usbn_clk_ctl.u64);
714         /*
715          * 9. Program the USBP control and status register to select host or
716          *    device mode. USBN_USBP_CTL_STATUS[HST_MODE] = 0 for host, = 1 for
717          *    device
718          */
719         usbn_usbp_ctl_status.s.hst_mode = 0;
720         __cvmx_usb_write_csr64(usb, CVMX_USBNX_USBP_CTL_STATUS(usb->index),
721                                usbn_usbp_ctl_status.u64);
722         /* 10. Wait 1 us */
723         udelay(1);
724         /*
725          * 11. Program the hreset_n field in the USBN clock-control register:
726          *     USBN_CLK_CTL[HRST] = 1
727          */
728         usbn_clk_ctl.s.hrst = 1;
729         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
730                                usbn_clk_ctl.u64);
731         /* 12. Proceed to USB core initialization */
732         usbn_clk_ctl.s.enable = 1;
733         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
734                                usbn_clk_ctl.u64);
735         udelay(1);
736
737         /*
738          * USB Core Initialization
739          *
740          * 1. Read USBC_GHWCFG1, USBC_GHWCFG2, USBC_GHWCFG3, USBC_GHWCFG4 to
741          *    determine USB core configuration parameters.
742          *
743          *    Nothing needed
744          *
745          * 2. Program the following fields in the global AHB configuration
746          *    register (USBC_GAHBCFG)
747          *    DMA mode, USBC_GAHBCFG[DMAEn]: 1 = DMA mode, 0 = slave mode
748          *    Burst length, USBC_GAHBCFG[HBSTLEN] = 0
749          *    Nonperiodic TxFIFO empty level (slave mode only),
750          *    USBC_GAHBCFG[NPTXFEMPLVL]
751          *    Periodic TxFIFO empty level (slave mode only),
752          *    USBC_GAHBCFG[PTXFEMPLVL]
753          *    Global interrupt mask, USBC_GAHBCFG[GLBLINTRMSK] = 1
754          */
755         {
756                 union cvmx_usbcx_gahbcfg usbcx_gahbcfg;
757                 /* Due to an errata, CN31XX doesn't support DMA */
758                 if (OCTEON_IS_MODEL(OCTEON_CN31XX))
759                         usb->init_flags |= CVMX_USB_INITIALIZE_FLAGS_NO_DMA;
760                 usbcx_gahbcfg.u32 = 0;
761                 usbcx_gahbcfg.s.dmaen = !(usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA);
762                 if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)
763                         /* Only use one channel with non DMA */
764                         usb->idle_hardware_channels = 0x1;
765                 else if (OCTEON_IS_MODEL(OCTEON_CN5XXX))
766                         /* CN5XXX have an errata with channel 3 */
767                         usb->idle_hardware_channels = 0xf7;
768                 else
769                         usb->idle_hardware_channels = 0xff;
770                 usbcx_gahbcfg.s.hbstlen = 0;
771                 usbcx_gahbcfg.s.nptxfemplvl = 1;
772                 usbcx_gahbcfg.s.ptxfemplvl = 1;
773                 usbcx_gahbcfg.s.glblintrmsk = 1;
774                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_GAHBCFG(usb->index),
775                                        usbcx_gahbcfg.u32);
776         }
777         /*
778          * 3. Program the following fields in USBC_GUSBCFG register.
779          *    HS/FS timeout calibration, USBC_GUSBCFG[TOUTCAL] = 0
780          *    ULPI DDR select, USBC_GUSBCFG[DDRSEL] = 0
781          *    USB turnaround time, USBC_GUSBCFG[USBTRDTIM] = 0x5
782          *    PHY low-power clock select, USBC_GUSBCFG[PHYLPWRCLKSEL] = 0
783          */
784         {
785                 union cvmx_usbcx_gusbcfg usbcx_gusbcfg;
786                 usbcx_gusbcfg.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GUSBCFG(usb->index));
787                 usbcx_gusbcfg.s.toutcal = 0;
788                 usbcx_gusbcfg.s.ddrsel = 0;
789                 usbcx_gusbcfg.s.usbtrdtim = 0x5;
790                 usbcx_gusbcfg.s.phylpwrclksel = 0;
791                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_GUSBCFG(usb->index),
792                                        usbcx_gusbcfg.u32);
793         }
794         /*
795          * 4. The software must unmask the following bits in the USBC_GINTMSK
796          *    register.
797          *    OTG interrupt mask, USBC_GINTMSK[OTGINTMSK] = 1
798          *    Mode mismatch interrupt mask, USBC_GINTMSK[MODEMISMSK] = 1
799          */
800         {
801                 union cvmx_usbcx_gintmsk usbcx_gintmsk;
802                 int channel;
803
804                 usbcx_gintmsk.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GINTMSK(usb->index));
805                 usbcx_gintmsk.s.otgintmsk = 1;
806                 usbcx_gintmsk.s.modemismsk = 1;
807                 usbcx_gintmsk.s.hchintmsk = 1;
808                 usbcx_gintmsk.s.sofmsk = 0;
809                 /* We need RX FIFO interrupts if we don't have DMA */
810                 if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)
811                         usbcx_gintmsk.s.rxflvlmsk = 1;
812                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_GINTMSK(usb->index),
813                                        usbcx_gintmsk.u32);
814
815                 /*
816                  * Disable all channel interrupts. We'll enable them per channel
817                  * later.
818                  */
819                 for (channel = 0; channel < 8; channel++)
820                         __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCINTMSKX(channel, usb->index), 0);
821         }
822
823         {
824                 /*
825                  * Host Port Initialization
826                  *
827                  * 1. Program the host-port interrupt-mask field to unmask,
828                  *    USBC_GINTMSK[PRTINT] = 1
829                  */
830                 USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk,
831                                 prtintmsk, 1);
832                 USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk,
833                                 disconnintmsk, 1);
834                 /*
835                  * 2. Program the USBC_HCFG register to select full-speed host
836                  *    or high-speed host.
837                  */
838                 {
839                         union cvmx_usbcx_hcfg usbcx_hcfg;
840                         usbcx_hcfg.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCFG(usb->index));
841                         usbcx_hcfg.s.fslssupp = 0;
842                         usbcx_hcfg.s.fslspclksel = 0;
843                         __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCFG(usb->index), usbcx_hcfg.u32);
844                 }
845                 /*
846                  * 3. Program the port power bit to drive VBUS on the USB,
847                  *    USBC_HPRT[PRTPWR] = 1
848                  */
849                 USB_SET_FIELD32(CVMX_USBCX_HPRT(usb->index), union cvmx_usbcx_hprt, prtpwr, 1);
850
851                 /*
852                  * Steps 4-15 from the manual are done later in the port enable
853                  */
854         }
855
856         return 0;
857 }
858
859
860 /**
861  * Shutdown a USB port after a call to cvmx_usb_initialize().
862  * The port should be disabled with all pipes closed when this
863  * function is called.
864  *
865  * @usb: USB device state populated by cvmx_usb_initialize().
866  *
867  * Returns: 0 or a negative error code.
868  */
869 static int cvmx_usb_shutdown(struct cvmx_usb_state *usb)
870 {
871         union cvmx_usbnx_clk_ctl usbn_clk_ctl;
872
873         /* Make sure all pipes are closed */
874         if (!list_empty(&usb->idle_pipes) ||
875             !list_empty(&usb->active_pipes[CVMX_USB_TRANSFER_ISOCHRONOUS]) ||
876             !list_empty(&usb->active_pipes[CVMX_USB_TRANSFER_INTERRUPT]) ||
877             !list_empty(&usb->active_pipes[CVMX_USB_TRANSFER_CONTROL]) ||
878             !list_empty(&usb->active_pipes[CVMX_USB_TRANSFER_BULK]))
879                 return -EBUSY;
880
881         /* Disable the clocks and put them in power on reset */
882         usbn_clk_ctl.u64 = __cvmx_usb_read_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index));
883         usbn_clk_ctl.s.enable = 1;
884         usbn_clk_ctl.s.por = 1;
885         usbn_clk_ctl.s.hclk_rst = 1;
886         usbn_clk_ctl.s.prst = 0;
887         usbn_clk_ctl.s.hrst = 0;
888         __cvmx_usb_write_csr64(usb, CVMX_USBNX_CLK_CTL(usb->index),
889                                usbn_clk_ctl.u64);
890         return 0;
891 }
892
893
894 /**
895  * Enable a USB port. After this call succeeds, the USB port is
896  * online and servicing requests.
897  *
898  * @usb: USB device state populated by cvmx_usb_initialize().
899  *
900  * Returns: 0 or a negative error code.
901  */
902 static int cvmx_usb_enable(struct cvmx_usb_state *usb)
903 {
904         union cvmx_usbcx_ghwcfg3 usbcx_ghwcfg3;
905
906         usb->usbcx_hprt.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HPRT(usb->index));
907
908         /*
909          * If the port is already enabled the just return. We don't need to do
910          * anything
911          */
912         if (usb->usbcx_hprt.s.prtena)
913                 return 0;
914
915         /* If there is nothing plugged into the port then fail immediately */
916         if (!usb->usbcx_hprt.s.prtconnsts) {
917                 return -ETIMEDOUT;
918         }
919
920         /* Program the port reset bit to start the reset process */
921         USB_SET_FIELD32(CVMX_USBCX_HPRT(usb->index), union cvmx_usbcx_hprt, prtrst, 1);
922
923         /*
924          * Wait at least 50ms (high speed), or 10ms (full speed) for the reset
925          * process to complete.
926          */
927         mdelay(50);
928
929         /* Program the port reset bit to 0, USBC_HPRT[PRTRST] = 0 */
930         USB_SET_FIELD32(CVMX_USBCX_HPRT(usb->index), union cvmx_usbcx_hprt, prtrst, 0);
931
932         /* Wait for the USBC_HPRT[PRTENA]. */
933         if (CVMX_WAIT_FOR_FIELD32(CVMX_USBCX_HPRT(usb->index), union cvmx_usbcx_hprt,
934                                   prtena, ==, 1, 100000))
935                 return -ETIMEDOUT;
936
937         /*
938          * Read the port speed field to get the enumerated speed,
939          * USBC_HPRT[PRTSPD].
940          */
941         usb->usbcx_hprt.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HPRT(usb->index));
942         usbcx_ghwcfg3.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GHWCFG3(usb->index));
943
944         /*
945          * 13. Program the USBC_GRXFSIZ register to select the size of the
946          *     receive FIFO (25%).
947          */
948         USB_SET_FIELD32(CVMX_USBCX_GRXFSIZ(usb->index), union cvmx_usbcx_grxfsiz,
949                         rxfdep, usbcx_ghwcfg3.s.dfifodepth / 4);
950         /*
951          * 14. Program the USBC_GNPTXFSIZ register to select the size and the
952          *     start address of the non- periodic transmit FIFO for nonperiodic
953          *     transactions (50%).
954          */
955         {
956                 union cvmx_usbcx_gnptxfsiz siz;
957                 siz.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GNPTXFSIZ(usb->index));
958                 siz.s.nptxfdep = usbcx_ghwcfg3.s.dfifodepth / 2;
959                 siz.s.nptxfstaddr = usbcx_ghwcfg3.s.dfifodepth / 4;
960                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_GNPTXFSIZ(usb->index), siz.u32);
961         }
962         /*
963          * 15. Program the USBC_HPTXFSIZ register to select the size and start
964          *     address of the periodic transmit FIFO for periodic transactions
965          *     (25%).
966          */
967         {
968                 union cvmx_usbcx_hptxfsiz siz;
969                 siz.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HPTXFSIZ(usb->index));
970                 siz.s.ptxfsize = usbcx_ghwcfg3.s.dfifodepth / 4;
971                 siz.s.ptxfstaddr = 3 * usbcx_ghwcfg3.s.dfifodepth / 4;
972                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HPTXFSIZ(usb->index), siz.u32);
973         }
974         /* Flush all FIFOs */
975         USB_SET_FIELD32(CVMX_USBCX_GRSTCTL(usb->index), union cvmx_usbcx_grstctl, txfnum, 0x10);
976         USB_SET_FIELD32(CVMX_USBCX_GRSTCTL(usb->index), union cvmx_usbcx_grstctl, txfflsh, 1);
977         CVMX_WAIT_FOR_FIELD32(CVMX_USBCX_GRSTCTL(usb->index), union cvmx_usbcx_grstctl,
978                               txfflsh, ==, 0, 100);
979         USB_SET_FIELD32(CVMX_USBCX_GRSTCTL(usb->index), union cvmx_usbcx_grstctl, rxfflsh, 1);
980         CVMX_WAIT_FOR_FIELD32(CVMX_USBCX_GRSTCTL(usb->index), union cvmx_usbcx_grstctl,
981                               rxfflsh, ==, 0, 100);
982
983         return 0;
984 }
985
986
987 /**
988  * Disable a USB port. After this call the USB port will not
989  * generate data transfers and will not generate events.
990  * Transactions in process will fail and call their
991  * associated callbacks.
992  *
993  * @usb: USB device state populated by cvmx_usb_initialize().
994  *
995  * Returns: 0 or a negative error code.
996  */
997 static int cvmx_usb_disable(struct cvmx_usb_state *usb)
998 {
999         /* Disable the port */
1000         USB_SET_FIELD32(CVMX_USBCX_HPRT(usb->index), union cvmx_usbcx_hprt, prtena, 1);
1001         return 0;
1002 }
1003
1004
1005 /**
1006  * Get the current state of the USB port. Use this call to
1007  * determine if the usb port has anything connected, is enabled,
1008  * or has some sort of error condition. The return value of this
1009  * call has "changed" bits to signal of the value of some fields
1010  * have changed between calls.
1011  *
1012  * @usb: USB device state populated by cvmx_usb_initialize().
1013  *
1014  * Returns: Port status information
1015  */
1016 static struct cvmx_usb_port_status cvmx_usb_get_status(struct cvmx_usb_state *usb)
1017 {
1018         union cvmx_usbcx_hprt usbc_hprt;
1019         struct cvmx_usb_port_status result;
1020
1021         memset(&result, 0, sizeof(result));
1022
1023         usbc_hprt.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HPRT(usb->index));
1024         result.port_enabled = usbc_hprt.s.prtena;
1025         result.port_over_current = usbc_hprt.s.prtovrcurract;
1026         result.port_powered = usbc_hprt.s.prtpwr;
1027         result.port_speed = usbc_hprt.s.prtspd;
1028         result.connected = usbc_hprt.s.prtconnsts;
1029         result.connect_change = (result.connected != usb->port_status.connected);
1030
1031         return result;
1032 }
1033
1034 /**
1035  * Open a virtual pipe between the host and a USB device. A pipe
1036  * must be opened before data can be transferred between a device
1037  * and Octeon.
1038  *
1039  * @usb:             USB device state populated by cvmx_usb_initialize().
1040  * @device_addr:
1041  *                   USB device address to open the pipe to
1042  *                   (0-127).
1043  * @endpoint_num:
1044  *                   USB endpoint number to open the pipe to
1045  *                   (0-15).
1046  * @device_speed:
1047  *                   The speed of the device the pipe is going
1048  *                   to. This must match the device's speed,
1049  *                   which may be different than the port speed.
1050  * @max_packet:      The maximum packet length the device can
1051  *                   transmit/receive (low speed=0-8, full
1052  *                   speed=0-1023, high speed=0-1024). This value
1053  *                   comes from the standard endpoint descriptor
1054  *                   field wMaxPacketSize bits <10:0>.
1055  * @transfer_type:
1056  *                   The type of transfer this pipe is for.
1057  * @transfer_dir:
1058  *                   The direction the pipe is in. This is not
1059  *                   used for control pipes.
1060  * @interval:        For ISOCHRONOUS and INTERRUPT transfers,
1061  *                   this is how often the transfer is scheduled
1062  *                   for. All other transfers should specify
1063  *                   zero. The units are in frames (8000/sec at
1064  *                   high speed, 1000/sec for full speed).
1065  * @multi_count:
1066  *                   For high speed devices, this is the maximum
1067  *                   allowed number of packet per microframe.
1068  *                   Specify zero for non high speed devices. This
1069  *                   value comes from the standard endpoint descriptor
1070  *                   field wMaxPacketSize bits <12:11>.
1071  * @hub_device_addr:
1072  *                   Hub device address this device is connected
1073  *                   to. Devices connected directly to Octeon
1074  *                   use zero. This is only used when the device
1075  *                   is full/low speed behind a high speed hub.
1076  *                   The address will be of the high speed hub,
1077  *                   not and full speed hubs after it.
1078  * @hub_port:        Which port on the hub the device is
1079  *                   connected. Use zero for devices connected
1080  *                   directly to Octeon. Like hub_device_addr,
1081  *                   this is only used for full/low speed
1082  *                   devices behind a high speed hub.
1083  *
1084  * Returns: A non-NULL value is a pipe. NULL means an error.
1085  */
1086 static struct cvmx_usb_pipe *cvmx_usb_open_pipe(struct cvmx_usb_state *usb,
1087                                                 int device_addr, int
1088                                                 endpoint_num,
1089                                                 enum cvmx_usb_speed
1090                                                         device_speed,
1091                                                 int max_packet,
1092                                                 enum cvmx_usb_transfer
1093                                                         transfer_type,
1094                                                 enum cvmx_usb_direction
1095                                                         transfer_dir,
1096                                                 int interval, int multi_count,
1097                                                 int hub_device_addr,
1098                                                 int hub_port)
1099 {
1100         struct cvmx_usb_pipe *pipe;
1101
1102         if (unlikely((device_addr < 0) || (device_addr > MAX_USB_ADDRESS)))
1103                 return NULL;
1104         if (unlikely((endpoint_num < 0) || (endpoint_num > MAX_USB_ENDPOINT)))
1105                 return NULL;
1106         if (unlikely(device_speed > CVMX_USB_SPEED_LOW))
1107                 return NULL;
1108         if (unlikely((max_packet <= 0) || (max_packet > 1024)))
1109                 return NULL;
1110         if (unlikely(transfer_type > CVMX_USB_TRANSFER_INTERRUPT))
1111                 return NULL;
1112         if (unlikely((transfer_dir != CVMX_USB_DIRECTION_OUT) &&
1113                 (transfer_dir != CVMX_USB_DIRECTION_IN)))
1114                 return NULL;
1115         if (unlikely(interval < 0))
1116                 return NULL;
1117         if (unlikely((transfer_type == CVMX_USB_TRANSFER_CONTROL) && interval))
1118                 return NULL;
1119         if (unlikely(multi_count < 0))
1120                 return NULL;
1121         if (unlikely((device_speed != CVMX_USB_SPEED_HIGH) &&
1122                 (multi_count != 0)))
1123                 return NULL;
1124         if (unlikely((hub_device_addr < 0) || (hub_device_addr > MAX_USB_ADDRESS)))
1125                 return NULL;
1126         if (unlikely((hub_port < 0) || (hub_port > MAX_USB_HUB_PORT)))
1127                 return NULL;
1128
1129         pipe = kzalloc(sizeof(*pipe), GFP_ATOMIC);
1130         if (!pipe)
1131                 return NULL;
1132         if ((device_speed == CVMX_USB_SPEED_HIGH) &&
1133                 (transfer_dir == CVMX_USB_DIRECTION_OUT) &&
1134                 (transfer_type == CVMX_USB_TRANSFER_BULK))
1135                 pipe->flags |= __CVMX_USB_PIPE_FLAGS_NEED_PING;
1136         pipe->device_addr = device_addr;
1137         pipe->endpoint_num = endpoint_num;
1138         pipe->device_speed = device_speed;
1139         pipe->max_packet = max_packet;
1140         pipe->transfer_type = transfer_type;
1141         pipe->transfer_dir = transfer_dir;
1142         INIT_LIST_HEAD(&pipe->transactions);
1143
1144         /*
1145          * All pipes use interval to rate limit NAK processing. Force an
1146          * interval if one wasn't supplied
1147          */
1148         if (!interval)
1149                 interval = 1;
1150         if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
1151                 pipe->interval = interval*8;
1152                 /* Force start splits to be schedule on uFrame 0 */
1153                 pipe->next_tx_frame = ((usb->frame_number+7)&~7) + pipe->interval;
1154         } else {
1155                 pipe->interval = interval;
1156                 pipe->next_tx_frame = usb->frame_number + pipe->interval;
1157         }
1158         pipe->multi_count = multi_count;
1159         pipe->hub_device_addr = hub_device_addr;
1160         pipe->hub_port = hub_port;
1161         pipe->pid_toggle = 0;
1162         pipe->split_sc_frame = -1;
1163         list_add_tail(&pipe->node, &usb->idle_pipes);
1164
1165         /*
1166          * We don't need to tell the hardware about this pipe yet since
1167          * it doesn't have any submitted requests
1168          */
1169
1170         return pipe;
1171 }
1172
1173
1174 /**
1175  * Poll the RX FIFOs and remove data as needed. This function is only used
1176  * in non DMA mode. It is very important that this function be called quickly
1177  * enough to prevent FIFO overflow.
1178  *
1179  * @usb:        USB device state populated by cvmx_usb_initialize().
1180  */
1181 static void __cvmx_usb_poll_rx_fifo(struct cvmx_usb_state *usb)
1182 {
1183         union cvmx_usbcx_grxstsph rx_status;
1184         int channel;
1185         int bytes;
1186         uint64_t address;
1187         uint32_t *ptr;
1188
1189         rx_status.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GRXSTSPH(usb->index));
1190         /* Only read data if IN data is there */
1191         if (rx_status.s.pktsts != 2)
1192                 return;
1193         /* Check if no data is available */
1194         if (!rx_status.s.bcnt)
1195                 return;
1196
1197         channel = rx_status.s.chnum;
1198         bytes = rx_status.s.bcnt;
1199         if (!bytes)
1200                 return;
1201
1202         /* Get where the DMA engine would have written this data */
1203         address = __cvmx_usb_read_csr64(usb, CVMX_USBNX_DMA0_INB_CHN0(usb->index) + channel*8);
1204         ptr = cvmx_phys_to_ptr(address);
1205         __cvmx_usb_write_csr64(usb, CVMX_USBNX_DMA0_INB_CHN0(usb->index) + channel*8, address + bytes);
1206
1207         /* Loop writing the FIFO data for this packet into memory */
1208         while (bytes > 0) {
1209                 *ptr++ = __cvmx_usb_read_csr32(usb, USB_FIFO_ADDRESS(channel, usb->index));
1210                 bytes -= 4;
1211         }
1212         CVMX_SYNCW;
1213
1214         return;
1215 }
1216
1217
1218 /**
1219  * Fill the TX hardware fifo with data out of the software
1220  * fifos
1221  *
1222  * @usb:            USB device state populated by cvmx_usb_initialize().
1223  * @fifo:           Software fifo to use
1224  * @available:      Amount of space in the hardware fifo
1225  *
1226  * Returns: Non zero if the hardware fifo was too small and needs
1227  *          to be serviced again.
1228  */
1229 static int __cvmx_usb_fill_tx_hw(struct cvmx_usb_state *usb,
1230                                  struct cvmx_usb_tx_fifo *fifo, int available)
1231 {
1232         /*
1233          * We're done either when there isn't anymore space or the software FIFO
1234          * is empty
1235          */
1236         while (available && (fifo->head != fifo->tail)) {
1237                 int i = fifo->tail;
1238                 const uint32_t *ptr = cvmx_phys_to_ptr(fifo->entry[i].address);
1239                 uint64_t csr_address = USB_FIFO_ADDRESS(fifo->entry[i].channel, usb->index) ^ 4;
1240                 int words = available;
1241
1242                 /* Limit the amount of data to waht the SW fifo has */
1243                 if (fifo->entry[i].size <= available) {
1244                         words = fifo->entry[i].size;
1245                         fifo->tail++;
1246                         if (fifo->tail > MAX_CHANNELS)
1247                                 fifo->tail = 0;
1248                 }
1249
1250                 /* Update the next locations and counts */
1251                 available -= words;
1252                 fifo->entry[i].address += words * 4;
1253                 fifo->entry[i].size -= words;
1254
1255                 /*
1256                  * Write the HW fifo data. The read every three writes is due
1257                  * to an errata on CN3XXX chips
1258                  */
1259                 while (words > 3) {
1260                         cvmx_write64_uint32(csr_address, *ptr++);
1261                         cvmx_write64_uint32(csr_address, *ptr++);
1262                         cvmx_write64_uint32(csr_address, *ptr++);
1263                         cvmx_read64_uint64(CVMX_USBNX_DMA0_INB_CHN0(usb->index));
1264                         words -= 3;
1265                 }
1266                 cvmx_write64_uint32(csr_address, *ptr++);
1267                 if (--words) {
1268                         cvmx_write64_uint32(csr_address, *ptr++);
1269                         if (--words)
1270                                 cvmx_write64_uint32(csr_address, *ptr++);
1271                 }
1272                 cvmx_read64_uint64(CVMX_USBNX_DMA0_INB_CHN0(usb->index));
1273         }
1274         return fifo->head != fifo->tail;
1275 }
1276
1277
1278 /**
1279  * Check the hardware FIFOs and fill them as needed
1280  *
1281  * @usb:        USB device state populated by cvmx_usb_initialize().
1282  */
1283 static void __cvmx_usb_poll_tx_fifo(struct cvmx_usb_state *usb)
1284 {
1285         if (usb->periodic.head != usb->periodic.tail) {
1286                 union cvmx_usbcx_hptxsts tx_status;
1287                 tx_status.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HPTXSTS(usb->index));
1288                 if (__cvmx_usb_fill_tx_hw(usb, &usb->periodic, tx_status.s.ptxfspcavail))
1289                         USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk, ptxfempmsk, 1);
1290                 else
1291                         USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk, ptxfempmsk, 0);
1292         }
1293
1294         if (usb->nonperiodic.head != usb->nonperiodic.tail) {
1295                 union cvmx_usbcx_gnptxsts tx_status;
1296                 tx_status.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GNPTXSTS(usb->index));
1297                 if (__cvmx_usb_fill_tx_hw(usb, &usb->nonperiodic, tx_status.s.nptxfspcavail))
1298                         USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk, nptxfempmsk, 1);
1299                 else
1300                         USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk, nptxfempmsk, 0);
1301         }
1302
1303         return;
1304 }
1305
1306
1307 /**
1308  * Fill the TX FIFO with an outgoing packet
1309  *
1310  * @usb:          USB device state populated by cvmx_usb_initialize().
1311  * @channel:      Channel number to get packet from
1312  */
1313 static void __cvmx_usb_fill_tx_fifo(struct cvmx_usb_state *usb, int channel)
1314 {
1315         union cvmx_usbcx_hccharx hcchar;
1316         union cvmx_usbcx_hcspltx usbc_hcsplt;
1317         union cvmx_usbcx_hctsizx usbc_hctsiz;
1318         struct cvmx_usb_tx_fifo *fifo;
1319
1320         /* We only need to fill data on outbound channels */
1321         hcchar.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCCHARX(channel, usb->index));
1322         if (hcchar.s.epdir != CVMX_USB_DIRECTION_OUT)
1323                 return;
1324
1325         /* OUT Splits only have data on the start and not the complete */
1326         usbc_hcsplt.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCSPLTX(channel, usb->index));
1327         if (usbc_hcsplt.s.spltena && usbc_hcsplt.s.compsplt)
1328                 return;
1329
1330         /*
1331          * Find out how many bytes we need to fill and convert it into 32bit
1332          * words.
1333          */
1334         usbc_hctsiz.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCTSIZX(channel, usb->index));
1335         if (!usbc_hctsiz.s.xfersize)
1336                 return;
1337
1338         if ((hcchar.s.eptype == CVMX_USB_TRANSFER_INTERRUPT) ||
1339                 (hcchar.s.eptype == CVMX_USB_TRANSFER_ISOCHRONOUS))
1340                 fifo = &usb->periodic;
1341         else
1342                 fifo = &usb->nonperiodic;
1343
1344         fifo->entry[fifo->head].channel = channel;
1345         fifo->entry[fifo->head].address = __cvmx_usb_read_csr64(usb, CVMX_USBNX_DMA0_OUTB_CHN0(usb->index) + channel*8);
1346         fifo->entry[fifo->head].size = (usbc_hctsiz.s.xfersize+3)>>2;
1347         fifo->head++;
1348         if (fifo->head > MAX_CHANNELS)
1349                 fifo->head = 0;
1350
1351         __cvmx_usb_poll_tx_fifo(usb);
1352
1353         return;
1354 }
1355
1356 /**
1357  * Perform channel specific setup for Control transactions. All
1358  * the generic stuff will already have been done in
1359  * __cvmx_usb_start_channel()
1360  *
1361  * @usb:          USB device state populated by cvmx_usb_initialize().
1362  * @channel:      Channel to setup
1363  * @pipe:         Pipe for control transaction
1364  */
1365 static void __cvmx_usb_start_channel_control(struct cvmx_usb_state *usb,
1366                                              int channel,
1367                                              struct cvmx_usb_pipe *pipe)
1368 {
1369         struct cvmx_usb_transaction *transaction =
1370                 list_first_entry(&pipe->transactions, typeof(*transaction),
1371                                  node);
1372         union cvmx_usb_control_header *header =
1373                 cvmx_phys_to_ptr(transaction->control_header);
1374         int bytes_to_transfer = transaction->buffer_length - transaction->actual_bytes;
1375         int packets_to_transfer;
1376         union cvmx_usbcx_hctsizx usbc_hctsiz;
1377
1378         usbc_hctsiz.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCTSIZX(channel, usb->index));
1379
1380         switch (transaction->stage) {
1381         case CVMX_USB_STAGE_NON_CONTROL:
1382         case CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE:
1383                 cvmx_dprintf("%s: ERROR - Non control stage\n", __FUNCTION__);
1384                 break;
1385         case CVMX_USB_STAGE_SETUP:
1386                 usbc_hctsiz.s.pid = 3; /* Setup */
1387                 bytes_to_transfer = sizeof(*header);
1388                 /* All Control operations start with a setup going OUT */
1389                 USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index), union cvmx_usbcx_hccharx, epdir, CVMX_USB_DIRECTION_OUT);
1390                 /*
1391                  * Setup send the control header instead of the buffer data. The
1392                  * buffer data will be used in the next stage
1393                  */
1394                 __cvmx_usb_write_csr64(usb, CVMX_USBNX_DMA0_OUTB_CHN0(usb->index) + channel*8, transaction->control_header);
1395                 break;
1396         case CVMX_USB_STAGE_SETUP_SPLIT_COMPLETE:
1397                 usbc_hctsiz.s.pid = 3; /* Setup */
1398                 bytes_to_transfer = 0;
1399                 /* All Control operations start with a setup going OUT */
1400                 USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index), union cvmx_usbcx_hccharx, epdir, CVMX_USB_DIRECTION_OUT);
1401                 USB_SET_FIELD32(CVMX_USBCX_HCSPLTX(channel, usb->index), union cvmx_usbcx_hcspltx, compsplt, 1);
1402                 break;
1403         case CVMX_USB_STAGE_DATA:
1404                 usbc_hctsiz.s.pid = __cvmx_usb_get_data_pid(pipe);
1405                 if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
1406                         if (header->s.request_type & 0x80)
1407                                 bytes_to_transfer = 0;
1408                         else if (bytes_to_transfer > pipe->max_packet)
1409                                 bytes_to_transfer = pipe->max_packet;
1410                 }
1411                 USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index),
1412                                 union cvmx_usbcx_hccharx, epdir,
1413                                 ((header->s.request_type & 0x80) ?
1414                                         CVMX_USB_DIRECTION_IN :
1415                                         CVMX_USB_DIRECTION_OUT));
1416                 break;
1417         case CVMX_USB_STAGE_DATA_SPLIT_COMPLETE:
1418                 usbc_hctsiz.s.pid = __cvmx_usb_get_data_pid(pipe);
1419                 if (!(header->s.request_type & 0x80))
1420                         bytes_to_transfer = 0;
1421                 USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index),
1422                                 union cvmx_usbcx_hccharx, epdir,
1423                                 ((header->s.request_type & 0x80) ?
1424                                         CVMX_USB_DIRECTION_IN :
1425                                         CVMX_USB_DIRECTION_OUT));
1426                 USB_SET_FIELD32(CVMX_USBCX_HCSPLTX(channel, usb->index), union cvmx_usbcx_hcspltx, compsplt, 1);
1427                 break;
1428         case CVMX_USB_STAGE_STATUS:
1429                 usbc_hctsiz.s.pid = __cvmx_usb_get_data_pid(pipe);
1430                 bytes_to_transfer = 0;
1431                 USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index), union cvmx_usbcx_hccharx, epdir,
1432                                 ((header->s.request_type & 0x80) ?
1433                                         CVMX_USB_DIRECTION_OUT :
1434                                         CVMX_USB_DIRECTION_IN));
1435                 break;
1436         case CVMX_USB_STAGE_STATUS_SPLIT_COMPLETE:
1437                 usbc_hctsiz.s.pid = __cvmx_usb_get_data_pid(pipe);
1438                 bytes_to_transfer = 0;
1439                 USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index), union cvmx_usbcx_hccharx, epdir,
1440                                 ((header->s.request_type & 0x80) ?
1441                                         CVMX_USB_DIRECTION_OUT :
1442                                         CVMX_USB_DIRECTION_IN));
1443                 USB_SET_FIELD32(CVMX_USBCX_HCSPLTX(channel, usb->index), union cvmx_usbcx_hcspltx, compsplt, 1);
1444                 break;
1445         }
1446
1447         /*
1448          * Make sure the transfer never exceeds the byte limit of the hardware.
1449          * Further bytes will be sent as continued transactions
1450          */
1451         if (bytes_to_transfer > MAX_TRANSFER_BYTES) {
1452                 /* Round MAX_TRANSFER_BYTES to a multiple of out packet size */
1453                 bytes_to_transfer = MAX_TRANSFER_BYTES / pipe->max_packet;
1454                 bytes_to_transfer *= pipe->max_packet;
1455         }
1456
1457         /*
1458          * Calculate the number of packets to transfer. If the length is zero
1459          * we still need to transfer one packet
1460          */
1461         packets_to_transfer = (bytes_to_transfer + pipe->max_packet - 1) / pipe->max_packet;
1462         if (packets_to_transfer == 0)
1463                 packets_to_transfer = 1;
1464         else if ((packets_to_transfer > 1) && (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)) {
1465                 /*
1466                  * Limit to one packet when not using DMA. Channels must be
1467                  * restarted between every packet for IN transactions, so there
1468                  * is no reason to do multiple packets in a row
1469                  */
1470                 packets_to_transfer = 1;
1471                 bytes_to_transfer = packets_to_transfer * pipe->max_packet;
1472         } else if (packets_to_transfer > MAX_TRANSFER_PACKETS) {
1473                 /*
1474                  * Limit the number of packet and data transferred to what the
1475                  * hardware can handle
1476                  */
1477                 packets_to_transfer = MAX_TRANSFER_PACKETS;
1478                 bytes_to_transfer = packets_to_transfer * pipe->max_packet;
1479         }
1480
1481         usbc_hctsiz.s.xfersize = bytes_to_transfer;
1482         usbc_hctsiz.s.pktcnt = packets_to_transfer;
1483
1484         __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCTSIZX(channel, usb->index), usbc_hctsiz.u32);
1485         return;
1486 }
1487
1488
1489 /**
1490  * Start a channel to perform the pipe's head transaction
1491  *
1492  * @usb:          USB device state populated by cvmx_usb_initialize().
1493  * @channel:      Channel to setup
1494  * @pipe:         Pipe to start
1495  */
1496 static void __cvmx_usb_start_channel(struct cvmx_usb_state *usb,
1497                                      int channel,
1498                                      struct cvmx_usb_pipe *pipe)
1499 {
1500         struct cvmx_usb_transaction *transaction =
1501                 list_first_entry(&pipe->transactions, typeof(*transaction),
1502                                  node);
1503
1504         /* Make sure all writes to the DMA region get flushed */
1505         CVMX_SYNCW;
1506
1507         /* Attach the channel to the pipe */
1508         usb->pipe_for_channel[channel] = pipe;
1509         pipe->channel = channel;
1510         pipe->flags |= __CVMX_USB_PIPE_FLAGS_SCHEDULED;
1511
1512         /* Mark this channel as in use */
1513         usb->idle_hardware_channels &= ~(1<<channel);
1514
1515         /* Enable the channel interrupt bits */
1516         {
1517                 union cvmx_usbcx_hcintx usbc_hcint;
1518                 union cvmx_usbcx_hcintmskx usbc_hcintmsk;
1519                 union cvmx_usbcx_haintmsk usbc_haintmsk;
1520
1521                 /* Clear all channel status bits */
1522                 usbc_hcint.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCINTX(channel, usb->index));
1523                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCINTX(channel, usb->index), usbc_hcint.u32);
1524
1525                 usbc_hcintmsk.u32 = 0;
1526                 usbc_hcintmsk.s.chhltdmsk = 1;
1527                 if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA) {
1528                         /*
1529                          * Channels need these extra interrupts when we aren't
1530                          * in DMA mode.
1531                          */
1532                         usbc_hcintmsk.s.datatglerrmsk = 1;
1533                         usbc_hcintmsk.s.frmovrunmsk = 1;
1534                         usbc_hcintmsk.s.bblerrmsk = 1;
1535                         usbc_hcintmsk.s.xacterrmsk = 1;
1536                         if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
1537                                 /*
1538                                  * Splits don't generate xfercompl, so we need
1539                                  * ACK and NYET.
1540                                  */
1541                                 usbc_hcintmsk.s.nyetmsk = 1;
1542                                 usbc_hcintmsk.s.ackmsk = 1;
1543                         }
1544                         usbc_hcintmsk.s.nakmsk = 1;
1545                         usbc_hcintmsk.s.stallmsk = 1;
1546                         usbc_hcintmsk.s.xfercomplmsk = 1;
1547                 }
1548                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCINTMSKX(channel, usb->index), usbc_hcintmsk.u32);
1549
1550                 /* Enable the channel interrupt to propagate */
1551                 usbc_haintmsk.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HAINTMSK(usb->index));
1552                 usbc_haintmsk.s.haintmsk |= 1<<channel;
1553                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HAINTMSK(usb->index), usbc_haintmsk.u32);
1554         }
1555
1556         /* Setup the locations the DMA engines use  */
1557         {
1558                 uint64_t dma_address = transaction->buffer + transaction->actual_bytes;
1559                 if (transaction->type == CVMX_USB_TRANSFER_ISOCHRONOUS)
1560                         dma_address = transaction->buffer + transaction->iso_packets[0].offset + transaction->actual_bytes;
1561                 __cvmx_usb_write_csr64(usb, CVMX_USBNX_DMA0_OUTB_CHN0(usb->index) + channel*8, dma_address);
1562                 __cvmx_usb_write_csr64(usb, CVMX_USBNX_DMA0_INB_CHN0(usb->index) + channel*8, dma_address);
1563         }
1564
1565         /* Setup both the size of the transfer and the SPLIT characteristics */
1566         {
1567                 union cvmx_usbcx_hcspltx usbc_hcsplt = {.u32 = 0};
1568                 union cvmx_usbcx_hctsizx usbc_hctsiz = {.u32 = 0};
1569                 int packets_to_transfer;
1570                 int bytes_to_transfer = transaction->buffer_length - transaction->actual_bytes;
1571
1572                 /*
1573                  * ISOCHRONOUS transactions store each individual transfer size
1574                  * in the packet structure, not the global buffer_length
1575                  */
1576                 if (transaction->type == CVMX_USB_TRANSFER_ISOCHRONOUS)
1577                         bytes_to_transfer = transaction->iso_packets[0].length - transaction->actual_bytes;
1578
1579                 /*
1580                  * We need to do split transactions when we are talking to non
1581                  * high speed devices that are behind a high speed hub
1582                  */
1583                 if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
1584                         /*
1585                          * On the start split phase (stage is even) record the
1586                          * frame number we will need to send the split complete.
1587                          * We only store the lower two bits since the time ahead
1588                          * can only be two frames
1589                          */
1590                         if ((transaction->stage&1) == 0) {
1591                                 if (transaction->type == CVMX_USB_TRANSFER_BULK)
1592                                         pipe->split_sc_frame = (usb->frame_number + 1) & 0x7f;
1593                                 else
1594                                         pipe->split_sc_frame = (usb->frame_number + 2) & 0x7f;
1595                         } else
1596                                 pipe->split_sc_frame = -1;
1597
1598                         usbc_hcsplt.s.spltena = 1;
1599                         usbc_hcsplt.s.hubaddr = pipe->hub_device_addr;
1600                         usbc_hcsplt.s.prtaddr = pipe->hub_port;
1601                         usbc_hcsplt.s.compsplt = (transaction->stage == CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE);
1602
1603                         /*
1604                          * SPLIT transactions can only ever transmit one data
1605                          * packet so limit the transfer size to the max packet
1606                          * size
1607                          */
1608                         if (bytes_to_transfer > pipe->max_packet)
1609                                 bytes_to_transfer = pipe->max_packet;
1610
1611                         /*
1612                          * ISOCHRONOUS OUT splits are unique in that they limit
1613                          * data transfers to 188 byte chunks representing the
1614                          * begin/middle/end of the data or all
1615                          */
1616                         if (!usbc_hcsplt.s.compsplt &&
1617                                 (pipe->transfer_dir == CVMX_USB_DIRECTION_OUT) &&
1618                                 (pipe->transfer_type == CVMX_USB_TRANSFER_ISOCHRONOUS)) {
1619                                 /*
1620                                  * Clear the split complete frame number as
1621                                  * there isn't going to be a split complete
1622                                  */
1623                                 pipe->split_sc_frame = -1;
1624                                 /*
1625                                  * See if we've started this transfer and sent
1626                                  * data
1627                                  */
1628                                 if (transaction->actual_bytes == 0) {
1629                                         /*
1630                                          * Nothing sent yet, this is either a
1631                                          * begin or the entire payload
1632                                          */
1633                                         if (bytes_to_transfer <= 188)
1634                                                 /* Entire payload in one go */
1635                                                 usbc_hcsplt.s.xactpos = 3;
1636                                         else
1637                                                 /* First part of payload */
1638                                                 usbc_hcsplt.s.xactpos = 2;
1639                                 } else {
1640                                         /*
1641                                          * Continuing the previous data, we must
1642                                          * either be in the middle or at the end
1643                                          */
1644                                         if (bytes_to_transfer <= 188)
1645                                                 /* End of payload */
1646                                                 usbc_hcsplt.s.xactpos = 1;
1647                                         else
1648                                                 /* Middle of payload */
1649                                                 usbc_hcsplt.s.xactpos = 0;
1650                                 }
1651                                 /*
1652                                  * Again, the transfer size is limited to 188
1653                                  * bytes
1654                                  */
1655                                 if (bytes_to_transfer > 188)
1656                                         bytes_to_transfer = 188;
1657                         }
1658                 }
1659
1660                 /*
1661                  * Make sure the transfer never exceeds the byte limit of the
1662                  * hardware. Further bytes will be sent as continued
1663                  * transactions
1664                  */
1665                 if (bytes_to_transfer > MAX_TRANSFER_BYTES) {
1666                         /*
1667                          * Round MAX_TRANSFER_BYTES to a multiple of out packet
1668                          * size
1669                          */
1670                         bytes_to_transfer = MAX_TRANSFER_BYTES / pipe->max_packet;
1671                         bytes_to_transfer *= pipe->max_packet;
1672                 }
1673
1674                 /*
1675                  * Calculate the number of packets to transfer. If the length is
1676                  * zero we still need to transfer one packet
1677                  */
1678                 packets_to_transfer = (bytes_to_transfer + pipe->max_packet - 1) / pipe->max_packet;
1679                 if (packets_to_transfer == 0)
1680                         packets_to_transfer = 1;
1681                 else if ((packets_to_transfer > 1) && (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)) {
1682                         /*
1683                          * Limit to one packet when not using DMA. Channels must
1684                          * be restarted between every packet for IN
1685                          * transactions, so there is no reason to do multiple
1686                          * packets in a row
1687                          */
1688                         packets_to_transfer = 1;
1689                         bytes_to_transfer = packets_to_transfer * pipe->max_packet;
1690                 } else if (packets_to_transfer > MAX_TRANSFER_PACKETS) {
1691                         /*
1692                          * Limit the number of packet and data transferred to
1693                          * what the hardware can handle
1694                          */
1695                         packets_to_transfer = MAX_TRANSFER_PACKETS;
1696                         bytes_to_transfer = packets_to_transfer * pipe->max_packet;
1697                 }
1698
1699                 usbc_hctsiz.s.xfersize = bytes_to_transfer;
1700                 usbc_hctsiz.s.pktcnt = packets_to_transfer;
1701
1702                 /* Update the DATA0/DATA1 toggle */
1703                 usbc_hctsiz.s.pid = __cvmx_usb_get_data_pid(pipe);
1704                 /*
1705                  * High speed pipes may need a hardware ping before they start
1706                  */
1707                 if (pipe->flags & __CVMX_USB_PIPE_FLAGS_NEED_PING)
1708                         usbc_hctsiz.s.dopng = 1;
1709
1710                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCSPLTX(channel, usb->index), usbc_hcsplt.u32);
1711                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCTSIZX(channel, usb->index), usbc_hctsiz.u32);
1712         }
1713
1714         /* Setup the Host Channel Characteristics Register */
1715         {
1716                 union cvmx_usbcx_hccharx usbc_hcchar = {.u32 = 0};
1717
1718                 /*
1719                  * Set the startframe odd/even properly. This is only used for
1720                  * periodic
1721                  */
1722                 usbc_hcchar.s.oddfrm = usb->frame_number&1;
1723
1724                 /*
1725                  * Set the number of back to back packets allowed by this
1726                  * endpoint. Split transactions interpret "ec" as the number of
1727                  * immediate retries of failure. These retries happen too
1728                  * quickly, so we disable these entirely for splits
1729                  */
1730                 if (__cvmx_usb_pipe_needs_split(usb, pipe))
1731                         usbc_hcchar.s.ec = 1;
1732                 else if (pipe->multi_count < 1)
1733                         usbc_hcchar.s.ec = 1;
1734                 else if (pipe->multi_count > 3)
1735                         usbc_hcchar.s.ec = 3;
1736                 else
1737                         usbc_hcchar.s.ec = pipe->multi_count;
1738
1739                 /* Set the rest of the endpoint specific settings */
1740                 usbc_hcchar.s.devaddr = pipe->device_addr;
1741                 usbc_hcchar.s.eptype = transaction->type;
1742                 usbc_hcchar.s.lspddev = (pipe->device_speed == CVMX_USB_SPEED_LOW);
1743                 usbc_hcchar.s.epdir = pipe->transfer_dir;
1744                 usbc_hcchar.s.epnum = pipe->endpoint_num;
1745                 usbc_hcchar.s.mps = pipe->max_packet;
1746                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCCHARX(channel, usb->index), usbc_hcchar.u32);
1747         }
1748
1749         /* Do transaction type specific fixups as needed */
1750         switch (transaction->type) {
1751         case CVMX_USB_TRANSFER_CONTROL:
1752                 __cvmx_usb_start_channel_control(usb, channel, pipe);
1753                 break;
1754         case CVMX_USB_TRANSFER_BULK:
1755         case CVMX_USB_TRANSFER_INTERRUPT:
1756                 break;
1757         case CVMX_USB_TRANSFER_ISOCHRONOUS:
1758                 if (!__cvmx_usb_pipe_needs_split(usb, pipe)) {
1759                         /*
1760                          * ISO transactions require different PIDs depending on
1761                          * direction and how many packets are needed
1762                          */
1763                         if (pipe->transfer_dir == CVMX_USB_DIRECTION_OUT) {
1764                                 if (pipe->multi_count < 2) /* Need DATA0 */
1765                                         USB_SET_FIELD32(CVMX_USBCX_HCTSIZX(channel, usb->index), union cvmx_usbcx_hctsizx, pid, 0);
1766                                 else /* Need MDATA */
1767                                         USB_SET_FIELD32(CVMX_USBCX_HCTSIZX(channel, usb->index), union cvmx_usbcx_hctsizx, pid, 3);
1768                         }
1769                 }
1770                 break;
1771         }
1772         {
1773                 union cvmx_usbcx_hctsizx usbc_hctsiz = {.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCTSIZX(channel, usb->index))};
1774                 transaction->xfersize = usbc_hctsiz.s.xfersize;
1775                 transaction->pktcnt = usbc_hctsiz.s.pktcnt;
1776         }
1777         /* Remeber when we start a split transaction */
1778         if (__cvmx_usb_pipe_needs_split(usb, pipe))
1779                 usb->active_split = transaction;
1780         USB_SET_FIELD32(CVMX_USBCX_HCCHARX(channel, usb->index), union cvmx_usbcx_hccharx, chena, 1);
1781         if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)
1782                 __cvmx_usb_fill_tx_fifo(usb, channel);
1783         return;
1784 }
1785
1786
1787 /**
1788  * Find a pipe that is ready to be scheduled to hardware.
1789  * @usb:         USB device state populated by cvmx_usb_initialize().
1790  * @list:        Pipe list to search
1791  * @current_frame:
1792  *               Frame counter to use as a time reference.
1793  *
1794  * Returns: Pipe or NULL if none are ready
1795  */
1796 static struct cvmx_usb_pipe *__cvmx_usb_find_ready_pipe(struct cvmx_usb_state *usb, struct list_head *list, uint64_t current_frame)
1797 {
1798         struct cvmx_usb_pipe *pipe;
1799
1800         list_for_each_entry(pipe, list, node) {
1801                 struct cvmx_usb_transaction *t =
1802                         list_first_entry(&pipe->transactions, typeof(*t), node);
1803                 if (!(pipe->flags & __CVMX_USB_PIPE_FLAGS_SCHEDULED) && t &&
1804                         (pipe->next_tx_frame <= current_frame) &&
1805                         ((pipe->split_sc_frame == -1) || ((((int)current_frame - (int)pipe->split_sc_frame) & 0x7f) < 0x40)) &&
1806                         (!usb->active_split || (usb->active_split == t))) {
1807                         CVMX_PREFETCH(pipe, 128);
1808                         CVMX_PREFETCH(t, 0);
1809                         return pipe;
1810                 }
1811         }
1812         return NULL;
1813 }
1814
1815
1816 /**
1817  * Called whenever a pipe might need to be scheduled to the
1818  * hardware.
1819  *
1820  * @usb:         USB device state populated by cvmx_usb_initialize().
1821  * @is_sof:      True if this schedule was called on a SOF interrupt.
1822  */
1823 static void __cvmx_usb_schedule(struct cvmx_usb_state *usb, int is_sof)
1824 {
1825         int channel;
1826         struct cvmx_usb_pipe *pipe;
1827         int need_sof;
1828         enum cvmx_usb_transfer ttype;
1829
1830         if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA) {
1831                 /*
1832                  * Without DMA we need to be careful to not schedule something
1833                  * at the end of a frame and cause an overrun.
1834                  */
1835                 union cvmx_usbcx_hfnum hfnum = {.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HFNUM(usb->index))};
1836                 union cvmx_usbcx_hfir hfir = {.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HFIR(usb->index))};
1837                 if (hfnum.s.frrem < hfir.s.frint/4)
1838                         goto done;
1839         }
1840
1841         while (usb->idle_hardware_channels) {
1842                 /* Find an idle channel */
1843                 channel = __fls(usb->idle_hardware_channels);
1844                 if (unlikely(channel > 7))
1845                         break;
1846
1847                 /* Find a pipe needing service */
1848                 pipe = NULL;
1849                 if (is_sof) {
1850                         /*
1851                          * Only process periodic pipes on SOF interrupts. This
1852                          * way we are sure that the periodic data is sent in the
1853                          * beginning of the frame
1854                          */
1855                         pipe = __cvmx_usb_find_ready_pipe(usb, usb->active_pipes + CVMX_USB_TRANSFER_ISOCHRONOUS, usb->frame_number);
1856                         if (likely(!pipe))
1857                                 pipe = __cvmx_usb_find_ready_pipe(usb, usb->active_pipes + CVMX_USB_TRANSFER_INTERRUPT, usb->frame_number);
1858                 }
1859                 if (likely(!pipe)) {
1860                         pipe = __cvmx_usb_find_ready_pipe(usb, usb->active_pipes + CVMX_USB_TRANSFER_CONTROL, usb->frame_number);
1861                         if (likely(!pipe))
1862                                 pipe = __cvmx_usb_find_ready_pipe(usb, usb->active_pipes + CVMX_USB_TRANSFER_BULK, usb->frame_number);
1863                 }
1864                 if (!pipe)
1865                         break;
1866
1867                 __cvmx_usb_start_channel(usb, channel, pipe);
1868         }
1869
1870 done:
1871         /*
1872          * Only enable SOF interrupts when we have transactions pending in the
1873          * future that might need to be scheduled
1874          */
1875         need_sof = 0;
1876         for (ttype = CVMX_USB_TRANSFER_CONTROL; ttype <= CVMX_USB_TRANSFER_INTERRUPT; ttype++) {
1877                 list_for_each_entry(pipe, &usb->active_pipes[ttype], node) {
1878                         if (pipe->next_tx_frame > usb->frame_number) {
1879                                 need_sof = 1;
1880                                 break;
1881                         }
1882                 }
1883         }
1884         USB_SET_FIELD32(CVMX_USBCX_GINTMSK(usb->index), union cvmx_usbcx_gintmsk, sofmsk, need_sof);
1885         return;
1886 }
1887
1888 static inline struct octeon_hcd *cvmx_usb_to_octeon(struct cvmx_usb_state *p)
1889 {
1890         return container_of(p, struct octeon_hcd, usb);
1891 }
1892
1893 static inline struct usb_hcd *octeon_to_hcd(struct octeon_hcd *p)
1894 {
1895         return container_of((void *)p, struct usb_hcd, hcd_priv);
1896 }
1897
1898 static void octeon_usb_urb_complete_callback(struct cvmx_usb_state *usb,
1899                                              enum cvmx_usb_complete status,
1900                                              struct cvmx_usb_pipe *pipe,
1901                                              struct cvmx_usb_transaction
1902                                                 *transaction,
1903                                              int bytes_transferred,
1904                                              struct urb *urb)
1905 {
1906         struct octeon_hcd *priv = cvmx_usb_to_octeon(usb);
1907         struct usb_hcd *hcd = octeon_to_hcd(priv);
1908         struct device *dev = hcd->self.controller;
1909
1910         urb->actual_length = bytes_transferred;
1911         urb->hcpriv = NULL;
1912
1913         if (!list_empty(&urb->urb_list))
1914                 /*
1915                  * It is on the dequeue_list, but we are going to call
1916                  * usb_hcd_giveback_urb(), so we must clear it from
1917                  * the list.  We got to it before the
1918                  * octeon_usb_urb_dequeue_work() tasklet did.
1919                  */
1920                 list_del_init(&urb->urb_list);
1921
1922         /* For Isochronous transactions we need to update the URB packet status
1923            list from data in our private copy */
1924         if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) {
1925                 int i;
1926                 /*
1927                  * The pointer to the private list is stored in the setup_packet
1928                  * field.
1929                  */
1930                 struct cvmx_usb_iso_packet *iso_packet =
1931                         (struct cvmx_usb_iso_packet *) urb->setup_packet;
1932                 /* Recalculate the transfer size by adding up each packet */
1933                 urb->actual_length = 0;
1934                 for (i = 0; i < urb->number_of_packets; i++) {
1935                         if (iso_packet[i].status == CVMX_USB_COMPLETE_SUCCESS) {
1936                                 urb->iso_frame_desc[i].status = 0;
1937                                 urb->iso_frame_desc[i].actual_length = iso_packet[i].length;
1938                                 urb->actual_length += urb->iso_frame_desc[i].actual_length;
1939                         } else {
1940                                 dev_dbg(dev, "ISOCHRONOUS packet=%d of %d status=%d pipe=%p transaction=%p size=%d\n",
1941                                         i, urb->number_of_packets,
1942                                         iso_packet[i].status, pipe,
1943                                         transaction, iso_packet[i].length);
1944                                 urb->iso_frame_desc[i].status = -EREMOTEIO;
1945                         }
1946                 }
1947                 /* Free the private list now that we don't need it anymore */
1948                 kfree(iso_packet);
1949                 urb->setup_packet = NULL;
1950         }
1951
1952         switch (status) {
1953         case CVMX_USB_COMPLETE_SUCCESS:
1954                 urb->status = 0;
1955                 break;
1956         case CVMX_USB_COMPLETE_CANCEL:
1957                 if (urb->status == 0)
1958                         urb->status = -ENOENT;
1959                 break;
1960         case CVMX_USB_COMPLETE_STALL:
1961                 dev_dbg(dev, "status=stall pipe=%p transaction=%p size=%d\n",
1962                         pipe, transaction, bytes_transferred);
1963                 urb->status = -EPIPE;
1964                 break;
1965         case CVMX_USB_COMPLETE_BABBLEERR:
1966                 dev_dbg(dev, "status=babble pipe=%p transaction=%p size=%d\n",
1967                         pipe, transaction, bytes_transferred);
1968                 urb->status = -EPIPE;
1969                 break;
1970         case CVMX_USB_COMPLETE_SHORT:
1971                 dev_dbg(dev, "status=short pipe=%p transaction=%p size=%d\n",
1972                         pipe, transaction, bytes_transferred);
1973                 urb->status = -EREMOTEIO;
1974                 break;
1975         case CVMX_USB_COMPLETE_ERROR:
1976         case CVMX_USB_COMPLETE_XACTERR:
1977         case CVMX_USB_COMPLETE_DATATGLERR:
1978         case CVMX_USB_COMPLETE_FRAMEERR:
1979                 dev_dbg(dev, "status=%d pipe=%p transaction=%p size=%d\n",
1980                         status, pipe, transaction, bytes_transferred);
1981                 urb->status = -EPROTO;
1982                 break;
1983         }
1984         spin_unlock(&priv->lock);
1985         usb_hcd_giveback_urb(octeon_to_hcd(priv), urb, urb->status);
1986         spin_lock(&priv->lock);
1987 }
1988
1989 /**
1990  * Signal the completion of a transaction and free it. The
1991  * transaction will be removed from the pipe transaction list.
1992  *
1993  * @usb:         USB device state populated by cvmx_usb_initialize().
1994  * @pipe:        Pipe the transaction is on
1995  * @transaction:
1996  *               Transaction that completed
1997  * @complete_code:
1998  *               Completion code
1999  */
2000 static void __cvmx_usb_perform_complete(struct cvmx_usb_state *usb,
2001                                         struct cvmx_usb_pipe *pipe,
2002                                         struct cvmx_usb_transaction *transaction,
2003                                         enum cvmx_usb_complete complete_code)
2004 {
2005         /* If this was a split then clear our split in progress marker */
2006         if (usb->active_split == transaction)
2007                 usb->active_split = NULL;
2008
2009         /*
2010          * Isochronous transactions need extra processing as they might not be
2011          * done after a single data transfer
2012          */
2013         if (unlikely(transaction->type == CVMX_USB_TRANSFER_ISOCHRONOUS)) {
2014                 /* Update the number of bytes transferred in this ISO packet */
2015                 transaction->iso_packets[0].length = transaction->actual_bytes;
2016                 transaction->iso_packets[0].status = complete_code;
2017
2018                 /*
2019                  * If there are more ISOs pending and we succeeded, schedule the
2020                  * next one
2021                  */
2022                 if ((transaction->iso_number_packets > 1) && (complete_code == CVMX_USB_COMPLETE_SUCCESS)) {
2023                         /* No bytes transferred for this packet as of yet */
2024                         transaction->actual_bytes = 0;
2025                         /* One less ISO waiting to transfer */
2026                         transaction->iso_number_packets--;
2027                         /* Increment to the next location in our packet array */
2028                         transaction->iso_packets++;
2029                         transaction->stage = CVMX_USB_STAGE_NON_CONTROL;
2030                         goto done;
2031                 }
2032         }
2033
2034         /* Remove the transaction from the pipe list */
2035         list_del(&transaction->node);
2036         if (list_empty(&pipe->transactions))
2037                 list_move_tail(&pipe->node, &usb->idle_pipes);
2038         octeon_usb_urb_complete_callback(usb, complete_code, pipe,
2039                                          transaction,
2040                                          transaction->actual_bytes,
2041                                          transaction->urb);
2042         kfree(transaction);
2043 done:
2044         return;
2045 }
2046
2047
2048 /**
2049  * Submit a usb transaction to a pipe. Called for all types
2050  * of transactions.
2051  *
2052  * @usb:
2053  * @pipe:           Which pipe to submit to.
2054  * @type:           Transaction type
2055  * @buffer:         User buffer for the transaction
2056  * @buffer_length:
2057  *                  User buffer's length in bytes
2058  * @control_header:
2059  *                  For control transactions, the 8 byte standard header
2060  * @iso_start_frame:
2061  *                  For ISO transactions, the start frame
2062  * @iso_number_packets:
2063  *                  For ISO, the number of packet in the transaction.
2064  * @iso_packets:
2065  *                  A description of each ISO packet
2066  * @urb:            URB for the callback
2067  *
2068  * Returns: Transaction or NULL on failure.
2069  */
2070 static struct cvmx_usb_transaction *__cvmx_usb_submit_transaction(struct cvmx_usb_state *usb,
2071                                                                   struct cvmx_usb_pipe *pipe,
2072                                                                   enum cvmx_usb_transfer type,
2073                                                                   uint64_t buffer,
2074                                                                   int buffer_length,
2075                                                                   uint64_t control_header,
2076                                                                   int iso_start_frame,
2077                                                                   int iso_number_packets,
2078                                                                   struct cvmx_usb_iso_packet *iso_packets,
2079                                                                   struct urb *urb)
2080 {
2081         struct cvmx_usb_transaction *transaction;
2082
2083         if (unlikely(pipe->transfer_type != type))
2084                 return NULL;
2085
2086         transaction = kzalloc(sizeof(*transaction), GFP_ATOMIC);
2087         if (unlikely(!transaction))
2088                 return NULL;
2089
2090         transaction->type = type;
2091         transaction->buffer = buffer;
2092         transaction->buffer_length = buffer_length;
2093         transaction->control_header = control_header;
2094         /* FIXME: This is not used, implement it. */
2095         transaction->iso_start_frame = iso_start_frame;
2096         transaction->iso_number_packets = iso_number_packets;
2097         transaction->iso_packets = iso_packets;
2098         transaction->urb = urb;
2099         if (transaction->type == CVMX_USB_TRANSFER_CONTROL)
2100                 transaction->stage = CVMX_USB_STAGE_SETUP;
2101         else
2102                 transaction->stage = CVMX_USB_STAGE_NON_CONTROL;
2103
2104         if (!list_empty(&pipe->transactions)) {
2105                 list_add_tail(&transaction->node, &pipe->transactions);
2106         } else {
2107                 list_add_tail(&transaction->node, &pipe->transactions);
2108                 list_move_tail(&pipe->node,
2109                                &usb->active_pipes[pipe->transfer_type]);
2110
2111                 /*
2112                  * We may need to schedule the pipe if this was the head of the
2113                  * pipe.
2114                  */
2115                 __cvmx_usb_schedule(usb, 0);
2116         }
2117
2118         return transaction;
2119 }
2120
2121
2122 /**
2123  * Call to submit a USB Bulk transfer to a pipe.
2124  *
2125  * @usb:            USB device state populated by cvmx_usb_initialize().
2126  * @pipe:           Handle to the pipe for the transfer.
2127  * @urb:            URB.
2128  *
2129  * Returns: A submitted transaction or NULL on failure.
2130  */
2131 static struct cvmx_usb_transaction *cvmx_usb_submit_bulk(struct cvmx_usb_state *usb,
2132                                                          struct cvmx_usb_pipe *pipe,
2133                                                          struct urb *urb)
2134 {
2135         return __cvmx_usb_submit_transaction(usb, pipe, CVMX_USB_TRANSFER_BULK,
2136                                              urb->transfer_dma,
2137                                              urb->transfer_buffer_length,
2138                                              0, /* control_header */
2139                                              0, /* iso_start_frame */
2140                                              0, /* iso_number_packets */
2141                                              NULL, /* iso_packets */
2142                                              urb);
2143 }
2144
2145
2146 /**
2147  * Call to submit a USB Interrupt transfer to a pipe.
2148  *
2149  * @usb:            USB device state populated by cvmx_usb_initialize().
2150  * @pipe:           Handle to the pipe for the transfer.
2151  * @urb:            URB returned when the callback is called.
2152  *
2153  * Returns: A submitted transaction or NULL on failure.
2154  */
2155 static struct cvmx_usb_transaction *cvmx_usb_submit_interrupt(struct cvmx_usb_state *usb,
2156                                                               struct cvmx_usb_pipe *pipe,
2157                                                               struct urb *urb)
2158 {
2159         return __cvmx_usb_submit_transaction(usb, pipe,
2160                                              CVMX_USB_TRANSFER_INTERRUPT,
2161                                              urb->transfer_dma,
2162                                              urb->transfer_buffer_length,
2163                                              0, /* control_header */
2164                                              0, /* iso_start_frame */
2165                                              0, /* iso_number_packets */
2166                                              NULL, /* iso_packets */
2167                                              urb);
2168 }
2169
2170
2171 /**
2172  * Call to submit a USB Control transfer to a pipe.
2173  *
2174  * @usb:            USB device state populated by cvmx_usb_initialize().
2175  * @pipe:           Handle to the pipe for the transfer.
2176  * @urb:            URB.
2177  *
2178  * Returns: A submitted transaction or NULL on failure.
2179  */
2180 static struct cvmx_usb_transaction *cvmx_usb_submit_control(struct cvmx_usb_state *usb,
2181                                                             struct cvmx_usb_pipe *pipe,
2182                                                             struct urb *urb)
2183 {
2184         int buffer_length = urb->transfer_buffer_length;
2185         uint64_t control_header = urb->setup_dma;
2186         union cvmx_usb_control_header *header =
2187                 cvmx_phys_to_ptr(control_header);
2188
2189         if ((header->s.request_type & 0x80) == 0)
2190                 buffer_length = le16_to_cpu(header->s.length);
2191
2192         return __cvmx_usb_submit_transaction(usb, pipe,
2193                                              CVMX_USB_TRANSFER_CONTROL,
2194                                              urb->transfer_dma, buffer_length,
2195                                              control_header,
2196                                              0, /* iso_start_frame */
2197                                              0, /* iso_number_packets */
2198                                              NULL, /* iso_packets */
2199                                              urb);
2200 }
2201
2202
2203 /**
2204  * Call to submit a USB Isochronous transfer to a pipe.
2205  *
2206  * @usb:            USB device state populated by cvmx_usb_initialize().
2207  * @pipe:           Handle to the pipe for the transfer.
2208  * @urb:            URB returned when the callback is called.
2209  *
2210  * Returns: A submitted transaction or NULL on failure.
2211  */
2212 static struct cvmx_usb_transaction *cvmx_usb_submit_isochronous(struct cvmx_usb_state *usb,
2213                                                                 struct cvmx_usb_pipe *pipe,
2214                                                                 struct urb *urb)
2215 {
2216         struct cvmx_usb_iso_packet *packets;
2217
2218         packets = (struct cvmx_usb_iso_packet *) urb->setup_packet;
2219         return __cvmx_usb_submit_transaction(usb, pipe,
2220                                              CVMX_USB_TRANSFER_ISOCHRONOUS,
2221                                              urb->transfer_dma,
2222                                              urb->transfer_buffer_length,
2223                                              0, /* control_header */
2224                                              urb->start_frame,
2225                                              urb->number_of_packets,
2226                                              packets, urb);
2227 }
2228
2229
2230 /**
2231  * Cancel one outstanding request in a pipe. Canceling a request
2232  * can fail if the transaction has already completed before cancel
2233  * is called. Even after a successful cancel call, it may take
2234  * a frame or two for the cvmx_usb_poll() function to call the
2235  * associated callback.
2236  *
2237  * @usb:         USB device state populated by cvmx_usb_initialize().
2238  * @pipe:        Pipe to cancel requests in.
2239  * @transaction: Transaction to cancel, returned by the submit function.
2240  *
2241  * Returns: 0 or a negative error code.
2242  */
2243 static int cvmx_usb_cancel(struct cvmx_usb_state *usb,
2244                            struct cvmx_usb_pipe *pipe,
2245                            struct cvmx_usb_transaction *transaction)
2246 {
2247         /*
2248          * If the transaction is the HEAD of the queue and scheduled. We need to
2249          * treat it special
2250          */
2251         if (list_first_entry(&pipe->transactions, typeof(*transaction), node) ==
2252             transaction && (pipe->flags & __CVMX_USB_PIPE_FLAGS_SCHEDULED)) {
2253                 union cvmx_usbcx_hccharx usbc_hcchar;
2254
2255                 usb->pipe_for_channel[pipe->channel] = NULL;
2256                 pipe->flags &= ~__CVMX_USB_PIPE_FLAGS_SCHEDULED;
2257
2258                 CVMX_SYNCW;
2259
2260                 usbc_hcchar.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCCHARX(pipe->channel, usb->index));
2261                 /*
2262                  * If the channel isn't enabled then the transaction already
2263                  * completed.
2264                  */
2265                 if (usbc_hcchar.s.chena) {
2266                         usbc_hcchar.s.chdis = 1;
2267                         __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCCHARX(pipe->channel, usb->index), usbc_hcchar.u32);
2268                 }
2269         }
2270         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_CANCEL);
2271         return 0;
2272 }
2273
2274
2275 /**
2276  * Cancel all outstanding requests in a pipe. Logically all this
2277  * does is call cvmx_usb_cancel() in a loop.
2278  *
2279  * @usb:         USB device state populated by cvmx_usb_initialize().
2280  * @pipe:        Pipe to cancel requests in.
2281  *
2282  * Returns: 0 or a negative error code.
2283  */
2284 static int cvmx_usb_cancel_all(struct cvmx_usb_state *usb,
2285                                struct cvmx_usb_pipe *pipe)
2286 {
2287         struct cvmx_usb_transaction *transaction, *next;
2288
2289         /* Simply loop through and attempt to cancel each transaction */
2290         list_for_each_entry_safe(transaction, next, &pipe->transactions, node) {
2291                 int result = cvmx_usb_cancel(usb, pipe, transaction);
2292                 if (unlikely(result != 0))
2293                         return result;
2294         }
2295         return 0;
2296 }
2297
2298
2299 /**
2300  * Close a pipe created with cvmx_usb_open_pipe().
2301  *
2302  * @usb:         USB device state populated by cvmx_usb_initialize().
2303  * @pipe:        Pipe to close.
2304  *
2305  * Returns: 0 or a negative error code. EBUSY is returned if the pipe has
2306  *          outstanding transfers.
2307  */
2308 static int cvmx_usb_close_pipe(struct cvmx_usb_state *usb,
2309                                struct cvmx_usb_pipe *pipe)
2310 {
2311         /* Fail if the pipe has pending transactions */
2312         if (!list_empty(&pipe->transactions))
2313                 return -EBUSY;
2314
2315         list_del(&pipe->node);
2316         kfree(pipe);
2317
2318         return 0;
2319 }
2320
2321 /**
2322  * Get the current USB protocol level frame number. The frame
2323  * number is always in the range of 0-0x7ff.
2324  *
2325  * @usb: USB device state populated by cvmx_usb_initialize().
2326  *
2327  * Returns: USB frame number
2328  */
2329 static int cvmx_usb_get_frame_number(struct cvmx_usb_state *usb)
2330 {
2331         int frame_number;
2332         union cvmx_usbcx_hfnum usbc_hfnum;
2333
2334         usbc_hfnum.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HFNUM(usb->index));
2335         frame_number = usbc_hfnum.s.frnum;
2336
2337         return frame_number;
2338 }
2339
2340
2341 /**
2342  * Poll a channel for status
2343  *
2344  * @usb:     USB device
2345  * @channel: Channel to poll
2346  *
2347  * Returns: Zero on success
2348  */
2349 static int __cvmx_usb_poll_channel(struct cvmx_usb_state *usb, int channel)
2350 {
2351         union cvmx_usbcx_hcintx usbc_hcint;
2352         union cvmx_usbcx_hctsizx usbc_hctsiz;
2353         union cvmx_usbcx_hccharx usbc_hcchar;
2354         struct cvmx_usb_pipe *pipe;
2355         struct cvmx_usb_transaction *transaction;
2356         int bytes_this_transfer;
2357         int bytes_in_last_packet;
2358         int packets_processed;
2359         int buffer_space_left;
2360
2361         /* Read the interrupt status bits for the channel */
2362         usbc_hcint.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCINTX(channel, usb->index));
2363
2364         if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA) {
2365                 usbc_hcchar.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCCHARX(channel, usb->index));
2366
2367                 if (usbc_hcchar.s.chena && usbc_hcchar.s.chdis) {
2368                         /*
2369                          * There seems to be a bug in CN31XX which can cause
2370                          * interrupt IN transfers to get stuck until we do a
2371                          * write of HCCHARX without changing things
2372                          */
2373                         __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCCHARX(channel, usb->index), usbc_hcchar.u32);
2374                         return 0;
2375                 }
2376
2377                 /*
2378                  * In non DMA mode the channels don't halt themselves. We need
2379                  * to manually disable channels that are left running
2380                  */
2381                 if (!usbc_hcint.s.chhltd) {
2382                         if (usbc_hcchar.s.chena) {
2383                                 union cvmx_usbcx_hcintmskx hcintmsk;
2384                                 /* Disable all interrupts except CHHLTD */
2385                                 hcintmsk.u32 = 0;
2386                                 hcintmsk.s.chhltdmsk = 1;
2387                                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCINTMSKX(channel, usb->index), hcintmsk.u32);
2388                                 usbc_hcchar.s.chdis = 1;
2389                                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCCHARX(channel, usb->index), usbc_hcchar.u32);
2390                                 return 0;
2391                         } else if (usbc_hcint.s.xfercompl) {
2392                                 /*
2393                                  * Successful IN/OUT with transfer complete.
2394                                  * Channel halt isn't needed.
2395                                  */
2396                         } else {
2397                                 cvmx_dprintf("USB%d: Channel %d interrupt without halt\n", usb->index, channel);
2398                                 return 0;
2399                         }
2400                 }
2401         } else {
2402                 /*
2403                  * There is are no interrupts that we need to process when the
2404                  * channel is still running
2405                  */
2406                 if (!usbc_hcint.s.chhltd)
2407                         return 0;
2408         }
2409
2410         /* Disable the channel interrupts now that it is done */
2411         __cvmx_usb_write_csr32(usb, CVMX_USBCX_HCINTMSKX(channel, usb->index), 0);
2412         usb->idle_hardware_channels |= (1<<channel);
2413
2414         /* Make sure this channel is tied to a valid pipe */
2415         pipe = usb->pipe_for_channel[channel];
2416         CVMX_PREFETCH(pipe, 0);
2417         CVMX_PREFETCH(pipe, 128);
2418         if (!pipe)
2419                 return 0;
2420         transaction = list_first_entry(&pipe->transactions, typeof(*transaction),
2421                                        node);
2422         CVMX_PREFETCH(transaction, 0);
2423
2424         /*
2425          * Disconnect this pipe from the HW channel. Later the schedule
2426          * function will figure out which pipe needs to go
2427          */
2428         usb->pipe_for_channel[channel] = NULL;
2429         pipe->flags &= ~__CVMX_USB_PIPE_FLAGS_SCHEDULED;
2430
2431         /*
2432          * Read the channel config info so we can figure out how much data
2433          * transfered
2434          */
2435         usbc_hcchar.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCCHARX(channel, usb->index));
2436         usbc_hctsiz.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HCTSIZX(channel, usb->index));
2437
2438         /*
2439          * Calculating the number of bytes successfully transferred is dependent
2440          * on the transfer direction
2441          */
2442         packets_processed = transaction->pktcnt - usbc_hctsiz.s.pktcnt;
2443         if (usbc_hcchar.s.epdir) {
2444                 /*
2445                  * IN transactions are easy. For every byte received the
2446                  * hardware decrements xfersize. All we need to do is subtract
2447                  * the current value of xfersize from its starting value and we
2448                  * know how many bytes were written to the buffer
2449                  */
2450                 bytes_this_transfer = transaction->xfersize - usbc_hctsiz.s.xfersize;
2451         } else {
2452                 /*
2453                  * OUT transaction don't decrement xfersize. Instead pktcnt is
2454                  * decremented on every successful packet send. The hardware
2455                  * does this when it receives an ACK, or NYET. If it doesn't
2456                  * receive one of these responses pktcnt doesn't change
2457                  */
2458                 bytes_this_transfer = packets_processed * usbc_hcchar.s.mps;
2459                 /*
2460                  * The last packet may not be a full transfer if we didn't have
2461                  * enough data
2462                  */
2463                 if (bytes_this_transfer > transaction->xfersize)
2464                         bytes_this_transfer = transaction->xfersize;
2465         }
2466         /* Figure out how many bytes were in the last packet of the transfer */
2467         if (packets_processed)
2468                 bytes_in_last_packet = bytes_this_transfer - (packets_processed-1) * usbc_hcchar.s.mps;
2469         else
2470                 bytes_in_last_packet = bytes_this_transfer;
2471
2472         /*
2473          * As a special case, setup transactions output the setup header, not
2474          * the user's data. For this reason we don't count setup data as bytes
2475          * transferred
2476          */
2477         if ((transaction->stage == CVMX_USB_STAGE_SETUP) ||
2478                 (transaction->stage == CVMX_USB_STAGE_SETUP_SPLIT_COMPLETE))
2479                 bytes_this_transfer = 0;
2480
2481         /*
2482          * Add the bytes transferred to the running total. It is important that
2483          * bytes_this_transfer doesn't count any data that needs to be
2484          * retransmitted
2485          */
2486         transaction->actual_bytes += bytes_this_transfer;
2487         if (transaction->type == CVMX_USB_TRANSFER_ISOCHRONOUS)
2488                 buffer_space_left = transaction->iso_packets[0].length - transaction->actual_bytes;
2489         else
2490                 buffer_space_left = transaction->buffer_length - transaction->actual_bytes;
2491
2492         /*
2493          * We need to remember the PID toggle state for the next transaction.
2494          * The hardware already updated it for the next transaction
2495          */
2496         pipe->pid_toggle = !(usbc_hctsiz.s.pid == 0);
2497
2498         /*
2499          * For high speed bulk out, assume the next transaction will need to do
2500          * a ping before proceeding. If this isn't true the ACK processing below
2501          * will clear this flag
2502          */
2503         if ((pipe->device_speed == CVMX_USB_SPEED_HIGH) &&
2504                 (pipe->transfer_type == CVMX_USB_TRANSFER_BULK) &&
2505                 (pipe->transfer_dir == CVMX_USB_DIRECTION_OUT))
2506                 pipe->flags |= __CVMX_USB_PIPE_FLAGS_NEED_PING;
2507
2508         if (usbc_hcint.s.stall) {
2509                 /*
2510                  * STALL as a response means this transaction cannot be
2511                  * completed because the device can't process transactions. Tell
2512                  * the user. Any data that was transferred will be counted on
2513                  * the actual bytes transferred
2514                  */
2515                 pipe->pid_toggle = 0;
2516                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_STALL);
2517         } else if (usbc_hcint.s.xacterr) {
2518                 /*
2519                  * We know at least one packet worked if we get a ACK or NAK.
2520                  * Reset the retry counter
2521                  */
2522                 if (usbc_hcint.s.nak || usbc_hcint.s.ack)
2523                         transaction->retries = 0;
2524                 transaction->retries++;
2525                 if (transaction->retries > MAX_RETRIES) {
2526                         /*
2527                          * XactErr as a response means the device signaled
2528                          * something wrong with the transfer. For example, PID
2529                          * toggle errors cause these
2530                          */
2531                         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_XACTERR);
2532                 } else {
2533                         /*
2534                          * If this was a split then clear our split in progress
2535                          * marker
2536                          */
2537                         if (usb->active_split == transaction)
2538                                 usb->active_split = NULL;
2539                         /*
2540                          * Rewind to the beginning of the transaction by anding
2541                          * off the split complete bit
2542                          */
2543                         transaction->stage &= ~1;
2544                         pipe->split_sc_frame = -1;
2545                         pipe->next_tx_frame += pipe->interval;
2546                         if (pipe->next_tx_frame < usb->frame_number)
2547                                 pipe->next_tx_frame = usb->frame_number + pipe->interval -
2548                                                       (usb->frame_number - pipe->next_tx_frame) % pipe->interval;
2549                 }
2550         } else if (usbc_hcint.s.bblerr) {
2551                 /* Babble Error (BblErr) */
2552                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_BABBLEERR);
2553         } else if (usbc_hcint.s.datatglerr) {
2554                 /* We'll retry the exact same transaction again */
2555                 transaction->retries++;
2556         } else if (usbc_hcint.s.nyet) {
2557                 /*
2558                  * NYET as a response is only allowed in three cases: as a
2559                  * response to a ping, as a response to a split transaction, and
2560                  * as a response to a bulk out. The ping case is handled by
2561                  * hardware, so we only have splits and bulk out
2562                  */
2563                 if (!__cvmx_usb_pipe_needs_split(usb, pipe)) {
2564                         transaction->retries = 0;
2565                         /*
2566                          * If there is more data to go then we need to try
2567                          * again. Otherwise this transaction is complete
2568                          */
2569                         if ((buffer_space_left == 0) || (bytes_in_last_packet < pipe->max_packet))
2570                                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2571                 } else {
2572                         /*
2573                          * Split transactions retry the split complete 4 times
2574                          * then rewind to the start split and do the entire
2575                          * transactions again
2576                          */
2577                         transaction->retries++;
2578                         if ((transaction->retries & 0x3) == 0) {
2579                                 /*
2580                                  * Rewind to the beginning of the transaction by
2581                                  * anding off the split complete bit
2582                                  */
2583                                 transaction->stage &= ~1;
2584                                 pipe->split_sc_frame = -1;
2585                         }
2586                 }
2587         } else if (usbc_hcint.s.ack) {
2588                 transaction->retries = 0;
2589                 /*
2590                  * The ACK bit can only be checked after the other error bits.
2591                  * This is because a multi packet transfer may succeed in a
2592                  * number of packets and then get a different response on the
2593                  * last packet. In this case both ACK and the last response bit
2594                  * will be set. If none of the other response bits is set, then
2595                  * the last packet must have been an ACK
2596                  *
2597                  * Since we got an ACK, we know we don't need to do a ping on
2598                  * this pipe
2599                  */
2600                 pipe->flags &= ~__CVMX_USB_PIPE_FLAGS_NEED_PING;
2601
2602                 switch (transaction->type) {
2603                 case CVMX_USB_TRANSFER_CONTROL:
2604                         switch (transaction->stage) {
2605                         case CVMX_USB_STAGE_NON_CONTROL:
2606                         case CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE:
2607                                 /* This should be impossible */
2608                                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_ERROR);
2609                                 break;
2610                         case CVMX_USB_STAGE_SETUP:
2611                                 pipe->pid_toggle = 1;
2612                                 if (__cvmx_usb_pipe_needs_split(usb, pipe))
2613                                         transaction->stage = CVMX_USB_STAGE_SETUP_SPLIT_COMPLETE;
2614                                 else {
2615                                         union cvmx_usb_control_header *header =
2616                                                 cvmx_phys_to_ptr(transaction->control_header);
2617                                         if (header->s.length)
2618                                                 transaction->stage = CVMX_USB_STAGE_DATA;
2619                                         else
2620                                                 transaction->stage = CVMX_USB_STAGE_STATUS;
2621                                 }
2622                                 break;
2623                         case CVMX_USB_STAGE_SETUP_SPLIT_COMPLETE:
2624                                 {
2625                                         union cvmx_usb_control_header *header =
2626                                                 cvmx_phys_to_ptr(transaction->control_header);
2627                                         if (header->s.length)
2628                                                 transaction->stage = CVMX_USB_STAGE_DATA;
2629                                         else
2630                                                 transaction->stage = CVMX_USB_STAGE_STATUS;
2631                                 }
2632                                 break;
2633                         case CVMX_USB_STAGE_DATA:
2634                                 if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
2635                                         transaction->stage = CVMX_USB_STAGE_DATA_SPLIT_COMPLETE;
2636                                         /*
2637                                          * For setup OUT data that are splits,
2638                                          * the hardware doesn't appear to count
2639                                          * transferred data. Here we manually
2640                                          * update the data transferred
2641                                          */
2642                                         if (!usbc_hcchar.s.epdir) {
2643                                                 if (buffer_space_left < pipe->max_packet)
2644                                                         transaction->actual_bytes += buffer_space_left;
2645                                                 else
2646                                                         transaction->actual_bytes += pipe->max_packet;
2647                                         }
2648                                 } else if ((buffer_space_left == 0) || (bytes_in_last_packet < pipe->max_packet)) {
2649                                         pipe->pid_toggle = 1;
2650                                         transaction->stage = CVMX_USB_STAGE_STATUS;
2651                                 }
2652                                 break;
2653                         case CVMX_USB_STAGE_DATA_SPLIT_COMPLETE:
2654                                 if ((buffer_space_left == 0) || (bytes_in_last_packet < pipe->max_packet)) {
2655                                         pipe->pid_toggle = 1;
2656                                         transaction->stage = CVMX_USB_STAGE_STATUS;
2657                                 } else {
2658                                         transaction->stage = CVMX_USB_STAGE_DATA;
2659                                 }
2660                                 break;
2661                         case CVMX_USB_STAGE_STATUS:
2662                                 if (__cvmx_usb_pipe_needs_split(usb, pipe))
2663                                         transaction->stage = CVMX_USB_STAGE_STATUS_SPLIT_COMPLETE;
2664                                 else
2665                                         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2666                                 break;
2667                         case CVMX_USB_STAGE_STATUS_SPLIT_COMPLETE:
2668                                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2669                                 break;
2670                         }
2671                         break;
2672                 case CVMX_USB_TRANSFER_BULK:
2673                 case CVMX_USB_TRANSFER_INTERRUPT:
2674                         /*
2675                          * The only time a bulk transfer isn't complete when it
2676                          * finishes with an ACK is during a split transaction.
2677                          * For splits we need to continue the transfer if more
2678                          * data is needed
2679                          */
2680                         if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
2681                                 if (transaction->stage == CVMX_USB_STAGE_NON_CONTROL)
2682                                         transaction->stage = CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE;
2683                                 else {
2684                                         if (buffer_space_left && (bytes_in_last_packet == pipe->max_packet))
2685                                                 transaction->stage = CVMX_USB_STAGE_NON_CONTROL;
2686                                         else {
2687                                                 if (transaction->type == CVMX_USB_TRANSFER_INTERRUPT)
2688                                                         pipe->next_tx_frame += pipe->interval;
2689                                                         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2690                                         }
2691                                 }
2692                         } else {
2693                                 if ((pipe->device_speed == CVMX_USB_SPEED_HIGH) &&
2694                                     (pipe->transfer_type == CVMX_USB_TRANSFER_BULK) &&
2695                                     (pipe->transfer_dir == CVMX_USB_DIRECTION_OUT) &&
2696                                     (usbc_hcint.s.nak))
2697                                         pipe->flags |= __CVMX_USB_PIPE_FLAGS_NEED_PING;
2698                                 if (!buffer_space_left || (bytes_in_last_packet < pipe->max_packet)) {
2699                                         if (transaction->type == CVMX_USB_TRANSFER_INTERRUPT)
2700                                                 pipe->next_tx_frame += pipe->interval;
2701                                         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2702                                 }
2703                         }
2704                         break;
2705                 case CVMX_USB_TRANSFER_ISOCHRONOUS:
2706                         if (__cvmx_usb_pipe_needs_split(usb, pipe)) {
2707                                 /*
2708                                  * ISOCHRONOUS OUT splits don't require a
2709                                  * complete split stage. Instead they use a
2710                                  * sequence of begin OUT splits to transfer the
2711                                  * data 188 bytes at a time. Once the transfer
2712                                  * is complete, the pipe sleeps until the next
2713                                  * schedule interval
2714                                  */
2715                                 if (pipe->transfer_dir == CVMX_USB_DIRECTION_OUT) {
2716                                         /*
2717                                          * If no space left or this wasn't a max
2718                                          * size packet then this transfer is
2719                                          * complete. Otherwise start it again to
2720                                          * send the next 188 bytes
2721                                          */
2722                                         if (!buffer_space_left || (bytes_this_transfer < 188)) {
2723                                                 pipe->next_tx_frame += pipe->interval;
2724                                                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2725                                         }
2726                                 } else {
2727                                         if (transaction->stage == CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE) {
2728                                                 /*
2729                                                  * We are in the incoming data
2730                                                  * phase. Keep getting data
2731                                                  * until we run out of space or
2732                                                  * get a small packet
2733                                                  */
2734                                                 if ((buffer_space_left == 0) || (bytes_in_last_packet < pipe->max_packet)) {
2735                                                         pipe->next_tx_frame += pipe->interval;
2736                                                         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2737                                                 }
2738                                         } else
2739                                                 transaction->stage = CVMX_USB_STAGE_NON_CONTROL_SPLIT_COMPLETE;
2740                                 }
2741                         } else {
2742                                 pipe->next_tx_frame += pipe->interval;
2743                                 __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_SUCCESS);
2744                         }
2745                         break;
2746                 }
2747         } else if (usbc_hcint.s.nak) {
2748                 /*
2749                  * If this was a split then clear our split in progress marker.
2750                  */
2751                 if (usb->active_split == transaction)
2752                         usb->active_split = NULL;
2753                 /*
2754                  * NAK as a response means the device couldn't accept the
2755                  * transaction, but it should be retried in the future. Rewind
2756                  * to the beginning of the transaction by anding off the split
2757                  * complete bit. Retry in the next interval
2758                  */
2759                 transaction->retries = 0;
2760                 transaction->stage &= ~1;
2761                 pipe->next_tx_frame += pipe->interval;
2762                 if (pipe->next_tx_frame < usb->frame_number)
2763                         pipe->next_tx_frame = usb->frame_number + pipe->interval -
2764                                 (usb->frame_number - pipe->next_tx_frame) % pipe->interval;
2765         } else {
2766                 struct cvmx_usb_port_status port;
2767                 port = cvmx_usb_get_status(usb);
2768                 if (port.port_enabled) {
2769                         /* We'll retry the exact same transaction again */
2770                         transaction->retries++;
2771                 } else {
2772                         /*
2773                          * We get channel halted interrupts with no result bits
2774                          * sets when the cable is unplugged
2775                          */
2776                         __cvmx_usb_perform_complete(usb, pipe, transaction, CVMX_USB_COMPLETE_ERROR);
2777                 }
2778         }
2779         return 0;
2780 }
2781
2782 static void octeon_usb_port_callback(struct cvmx_usb_state *usb)
2783 {
2784         struct octeon_hcd *priv = cvmx_usb_to_octeon(usb);
2785
2786         spin_unlock(&priv->lock);
2787         usb_hcd_poll_rh_status(octeon_to_hcd(priv));
2788         spin_lock(&priv->lock);
2789 }
2790
2791 /**
2792  * Poll the USB block for status and call all needed callback
2793  * handlers. This function is meant to be called in the interrupt
2794  * handler for the USB controller. It can also be called
2795  * periodically in a loop for non-interrupt based operation.
2796  *
2797  * @usb: USB device state populated by cvmx_usb_initialize().
2798  *
2799  * Returns: 0 or a negative error code.
2800  */
2801 static int cvmx_usb_poll(struct cvmx_usb_state *usb)
2802 {
2803         union cvmx_usbcx_hfnum usbc_hfnum;
2804         union cvmx_usbcx_gintsts usbc_gintsts;
2805
2806         CVMX_PREFETCH(usb, 0);
2807         CVMX_PREFETCH(usb, 1*128);
2808         CVMX_PREFETCH(usb, 2*128);
2809         CVMX_PREFETCH(usb, 3*128);
2810         CVMX_PREFETCH(usb, 4*128);
2811
2812         /* Update the frame counter */
2813         usbc_hfnum.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HFNUM(usb->index));
2814         if ((usb->frame_number&0x3fff) > usbc_hfnum.s.frnum)
2815                 usb->frame_number += 0x4000;
2816         usb->frame_number &= ~0x3fffull;
2817         usb->frame_number |= usbc_hfnum.s.frnum;
2818
2819         /* Read the pending interrupts */
2820         usbc_gintsts.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_GINTSTS(usb->index));
2821
2822         /* Clear the interrupts now that we know about them */
2823         __cvmx_usb_write_csr32(usb, CVMX_USBCX_GINTSTS(usb->index), usbc_gintsts.u32);
2824
2825         if (usbc_gintsts.s.rxflvl) {
2826                 /*
2827                  * RxFIFO Non-Empty (RxFLvl)
2828                  * Indicates that there is at least one packet pending to be
2829                  * read from the RxFIFO.
2830                  *
2831                  * In DMA mode this is handled by hardware
2832                  */
2833                 if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)
2834                         __cvmx_usb_poll_rx_fifo(usb);
2835         }
2836         if (usbc_gintsts.s.ptxfemp || usbc_gintsts.s.nptxfemp) {
2837                 /* Fill the Tx FIFOs when not in DMA mode */
2838                 if (usb->init_flags & CVMX_USB_INITIALIZE_FLAGS_NO_DMA)
2839                         __cvmx_usb_poll_tx_fifo(usb);
2840         }
2841         if (usbc_gintsts.s.disconnint || usbc_gintsts.s.prtint) {
2842                 union cvmx_usbcx_hprt usbc_hprt;
2843                 /*
2844                  * Disconnect Detected Interrupt (DisconnInt)
2845                  * Asserted when a device disconnect is detected.
2846                  *
2847                  * Host Port Interrupt (PrtInt)
2848                  * The core sets this bit to indicate a change in port status of
2849                  * one of the O2P USB core ports in Host mode. The application
2850                  * must read the Host Port Control and Status (HPRT) register to
2851                  * determine the exact event that caused this interrupt. The
2852                  * application must clear the appropriate status bit in the Host
2853                  * Port Control and Status register to clear this bit.
2854                  *
2855                  * Call the user's port callback
2856                  */
2857                 octeon_usb_port_callback(usb);
2858                 /* Clear the port change bits */
2859                 usbc_hprt.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HPRT(usb->index));
2860                 usbc_hprt.s.prtena = 0;
2861                 __cvmx_usb_write_csr32(usb, CVMX_USBCX_HPRT(usb->index), usbc_hprt.u32);
2862         }
2863         if (usbc_gintsts.s.hchint) {
2864                 /*
2865                  * Host Channels Interrupt (HChInt)
2866                  * The core sets this bit to indicate that an interrupt is
2867                  * pending on one of the channels of the core (in Host mode).
2868                  * The application must read the Host All Channels Interrupt
2869                  * (HAINT) register to determine the exact number of the channel
2870                  * on which the interrupt occurred, and then read the
2871                  * corresponding Host Channel-n Interrupt (HCINTn) register to
2872                  * determine the exact cause of the interrupt. The application
2873                  * must clear the appropriate status bit in the HCINTn register
2874                  * to clear this bit.
2875                  */
2876                 union cvmx_usbcx_haint usbc_haint;
2877                 usbc_haint.u32 = __cvmx_usb_read_csr32(usb, CVMX_USBCX_HAINT(usb->index));
2878                 while (usbc_haint.u32) {
2879                         int channel;
2880
2881                         channel = __fls(usbc_haint.u32);
2882                         __cvmx_usb_poll_channel(usb, channel);
2883                         usbc_haint.u32 ^= 1<<channel;
2884                 }
2885         }
2886
2887         __cvmx_usb_schedule(usb, usbc_gintsts.s.sof);
2888
2889         return 0;
2890 }
2891
2892 /* convert between an HCD pointer and the corresponding struct octeon_hcd */
2893 static inline struct octeon_hcd *hcd_to_octeon(struct usb_hcd *hcd)
2894 {
2895         return (struct octeon_hcd *)(hcd->hcd_priv);
2896 }
2897
2898 static irqreturn_t octeon_usb_irq(struct usb_hcd *hcd)
2899 {
2900         struct octeon_hcd *priv = hcd_to_octeon(hcd);
2901         unsigned long flags;
2902
2903         spin_lock_irqsave(&priv->lock, flags);
2904         cvmx_usb_poll(&priv->usb);
2905         spin_unlock_irqrestore(&priv->lock, flags);
2906         return IRQ_HANDLED;
2907 }
2908
2909 static int octeon_usb_start(struct usb_hcd *hcd)
2910 {
2911         hcd->state = HC_STATE_RUNNING;
2912         return 0;
2913 }
2914
2915 static void octeon_usb_stop(struct usb_hcd *hcd)
2916 {
2917         hcd->state = HC_STATE_HALT;
2918 }
2919
2920 static int octeon_usb_get_frame_number(struct usb_hcd *hcd)
2921 {
2922         struct octeon_hcd *priv = hcd_to_octeon(hcd);
2923
2924         return cvmx_usb_get_frame_number(&priv->usb);
2925 }
2926
2927 static int octeon_usb_urb_enqueue(struct usb_hcd *hcd,
2928                                   struct urb *urb,
2929                                   gfp_t mem_flags)
2930 {
2931         struct octeon_hcd *priv = hcd_to_octeon(hcd);
2932         struct device *dev = hcd->self.controller;
2933         struct cvmx_usb_transaction *transaction = NULL;
2934         struct cvmx_usb_pipe *pipe;
2935         unsigned long flags;
2936         struct cvmx_usb_iso_packet *iso_packet;
2937         struct usb_host_endpoint *ep = urb->ep;
2938
2939         urb->status = 0;
2940         INIT_LIST_HEAD(&urb->urb_list); /* not enqueued on dequeue_list */
2941         spin_lock_irqsave(&priv->lock, flags);
2942
2943         if (!ep->hcpriv) {
2944                 enum cvmx_usb_transfer transfer_type;
2945                 enum cvmx_usb_speed speed;
2946                 int split_device = 0;
2947                 int split_port = 0;
2948                 switch (usb_pipetype(urb->pipe)) {
2949                 case PIPE_ISOCHRONOUS:
2950                         transfer_type = CVMX_USB_TRANSFER_ISOCHRONOUS;
2951                         break;
2952                 case PIPE_INTERRUPT:
2953                         transfer_type = CVMX_USB_TRANSFER_INTERRUPT;
2954                         break;
2955                 case PIPE_CONTROL:
2956                         transfer_type = CVMX_USB_TRANSFER_CONTROL;
2957                         break;
2958                 default:
2959                         transfer_type = CVMX_USB_TRANSFER_BULK;
2960                         break;
2961                 }
2962                 switch (urb->dev->speed) {
2963                 case USB_SPEED_LOW:
2964                         speed = CVMX_USB_SPEED_LOW;
2965                         break;
2966                 case USB_SPEED_FULL:
2967                         speed = CVMX_USB_SPEED_FULL;
2968                         break;
2969                 default:
2970                         speed = CVMX_USB_SPEED_HIGH;
2971                         break;
2972                 }
2973                 /*
2974                  * For slow devices on high speed ports we need to find the hub
2975                  * that does the speed translation so we know where to send the
2976                  * split transactions.
2977                  */
2978                 if (speed != CVMX_USB_SPEED_HIGH) {
2979                         /*
2980                          * Start at this device and work our way up the usb
2981                          * tree.
2982                          */
2983                         struct usb_device *dev = urb->dev;
2984                         while (dev->parent) {
2985                                 /*
2986                                  * If our parent is high speed then he'll
2987                                  * receive the splits.
2988                                  */
2989                                 if (dev->parent->speed == USB_SPEED_HIGH) {
2990                                         split_device = dev->parent->devnum;
2991                                         split_port = dev->portnum;
2992                                         break;
2993                                 }
2994                                 /*
2995                                  * Move up the tree one level. If we make it all
2996                                  * the way up the tree, then the port must not
2997                                  * be in high speed mode and we don't need a
2998                                  * split.
2999                                  */
3000                                 dev = dev->parent;
3001                         }
3002                 }
3003                 pipe = cvmx_usb_open_pipe(&priv->usb, usb_pipedevice(urb->pipe),
3004                                           usb_pipeendpoint(urb->pipe), speed,
3005                                           le16_to_cpu(ep->desc.wMaxPacketSize) & 0x7ff,
3006                                           transfer_type,
3007                                           usb_pipein(urb->pipe) ?
3008                                                 CVMX_USB_DIRECTION_IN :
3009                                                 CVMX_USB_DIRECTION_OUT,
3010                                           urb->interval,
3011                                           (le16_to_cpu(ep->desc.wMaxPacketSize) >> 11) & 0x3,
3012                                           split_device, split_port);
3013                 if (!pipe) {
3014                         spin_unlock_irqrestore(&priv->lock, flags);
3015                         dev_dbg(dev, "Failed to create pipe\n");
3016                         return -ENOMEM;
3017                 }
3018                 ep->hcpriv = pipe;
3019         } else {
3020                 pipe = ep->hcpriv;
3021         }
3022
3023         switch (usb_pipetype(urb->pipe)) {
3024         case PIPE_ISOCHRONOUS:
3025                 dev_dbg(dev, "Submit isochronous to %d.%d\n",
3026                         usb_pipedevice(urb->pipe), usb_pipeendpoint(urb->pipe));
3027                 /*
3028                  * Allocate a structure to use for our private list of
3029                  * isochronous packets.
3030                  */
3031                 iso_packet = kmalloc(urb->number_of_packets *
3032                                      sizeof(struct cvmx_usb_iso_packet),
3033                                      GFP_ATOMIC);
3034                 if (iso_packet) {
3035                         int i;
3036                         /* Fill the list with the data from the URB */
3037                         for (i = 0; i < urb->number_of_packets; i++) {
3038                                 iso_packet[i].offset = urb->iso_frame_desc[i].offset;
3039                                 iso_packet[i].length = urb->iso_frame_desc[i].length;
3040                                 iso_packet[i].status = CVMX_USB_COMPLETE_ERROR;
3041                         }
3042                         /*
3043                          * Store a pointer to the list in the URB setup_packet
3044                          * field. We know this currently isn't being used and
3045                          * this saves us a bunch of logic.
3046                          */
3047                         urb->setup_packet = (char *)iso_packet;
3048                         transaction = cvmx_usb_submit_isochronous(&priv->usb,
3049                                                                   pipe, urb);
3050                         /*
3051                          * If submit failed we need to free our private packet
3052                          * list.
3053                          */
3054                         if (!transaction) {
3055                                 urb->setup_packet = NULL;
3056                                 kfree(iso_packet);
3057                         }
3058                 }
3059                 break;
3060         case PIPE_INTERRUPT:
3061                 dev_dbg(dev, "Submit interrupt to %d.%d\n",
3062                         usb_pipedevice(urb->pipe), usb_pipeendpoint(urb->pipe));
3063                 transaction = cvmx_usb_submit_interrupt(&priv->usb, pipe, urb);
3064                 break;
3065         case PIPE_CONTROL:
3066                 dev_dbg(dev, "Submit control to %d.%d\n",
3067                         usb_pipedevice(urb->pipe), usb_pipeendpoint(urb->pipe));
3068                 transaction = cvmx_usb_submit_control(&priv->usb, pipe, urb);
3069                 break;
3070         case PIPE_BULK:
3071                 dev_dbg(dev, "Submit bulk to %d.%d\n",
3072                         usb_pipedevice(urb->pipe), usb_pipeendpoint(urb->pipe));
3073                 transaction = cvmx_usb_submit_bulk(&priv->usb, pipe, urb);
3074                 break;
3075         }
3076         if (!transaction) {
3077                 spin_unlock_irqrestore(&priv->lock, flags);
3078                 dev_dbg(dev, "Failed to submit\n");
3079                 return -ENOMEM;
3080         }
3081         urb->hcpriv = transaction;
3082         spin_unlock_irqrestore(&priv->lock, flags);
3083         return 0;
3084 }
3085
3086 static void octeon_usb_urb_dequeue_work(unsigned long arg)
3087 {
3088         struct urb *urb;
3089         struct urb *next;
3090         unsigned long flags;
3091         struct octeon_hcd *priv = (struct octeon_hcd *)arg;
3092
3093         spin_lock_irqsave(&priv->lock, flags);
3094
3095         list_for_each_entry_safe(urb, next, &priv->dequeue_list, urb_list) {
3096                 list_del_init(&urb->urb_list);
3097                 cvmx_usb_cancel(&priv->usb, urb->ep->hcpriv, urb->hcpriv);
3098         }
3099
3100         spin_unlock_irqrestore(&priv->lock, flags);
3101 }
3102
3103 static int octeon_usb_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
3104 {
3105         struct octeon_hcd *priv = hcd_to_octeon(hcd);
3106         unsigned long flags;
3107
3108         if (!urb->dev)
3109                 return -EINVAL;
3110
3111         spin_lock_irqsave(&priv->lock, flags);
3112
3113         urb->status = status;
3114         list_add_tail(&urb->urb_list, &priv->dequeue_list);
3115
3116         spin_unlock_irqrestore(&priv->lock, flags);
3117
3118         tasklet_schedule(&priv->dequeue_tasklet);
3119
3120         return 0;
3121 }
3122
3123 static void octeon_usb_endpoint_disable(struct usb_hcd *hcd, struct usb_host_endpoint *ep)
3124 {
3125         struct device *dev = hcd->self.controller;
3126
3127         if (ep->hcpriv) {
3128                 struct octeon_hcd *priv = hcd_to_octeon(hcd);
3129                 struct cvmx_usb_pipe *pipe = ep->hcpriv;
3130                 unsigned long flags;
3131                 spin_lock_irqsave(&priv->lock, flags);
3132                 cvmx_usb_cancel_all(&priv->usb, pipe);
3133                 if (cvmx_usb_close_pipe(&priv->usb, pipe))
3134                         dev_dbg(dev, "Closing pipe %p failed\n", pipe);
3135                 spin_unlock_irqrestore(&priv->lock, flags);
3136                 ep->hcpriv = NULL;
3137         }
3138 }
3139
3140 static int octeon_usb_hub_status_data(struct usb_hcd *hcd, char *buf)
3141 {
3142         struct octeon_hcd *priv = hcd_to_octeon(hcd);
3143         struct cvmx_usb_port_status port_status;
3144         unsigned long flags;
3145
3146         spin_lock_irqsave(&priv->lock, flags);
3147         port_status = cvmx_usb_get_status(&priv->usb);
3148         spin_unlock_irqrestore(&priv->lock, flags);
3149         buf[0] = 0;
3150         buf[0] = port_status.connect_change << 1;
3151
3152         return (buf[0] != 0);
3153 }
3154
3155 static int octeon_usb_hub_control(struct usb_hcd *hcd, u16 typeReq, u16 wValue, u16 wIndex, char *buf, u16 wLength)
3156 {
3157         struct octeon_hcd *priv = hcd_to_octeon(hcd);
3158         struct device *dev = hcd->self.controller;
3159         struct cvmx_usb_port_status usb_port_status;
3160         int port_status;
3161         struct usb_hub_descriptor *desc;
3162         unsigned long flags;
3163
3164         switch (typeReq) {
3165         case ClearHubFeature:
3166                 dev_dbg(dev, "ClearHubFeature\n");
3167                 switch (wValue) {
3168                 case C_HUB_LOCAL_POWER:
3169                 case C_HUB_OVER_CURRENT:
3170                         /* Nothing required here */
3171                         break;
3172                 default:
3173                         return -EINVAL;
3174                 }
3175                 break;
3176         case ClearPortFeature:
3177                 dev_dbg(dev, "ClearPortFeature\n");
3178                 if (wIndex != 1) {
3179                         dev_dbg(dev, " INVALID\n");
3180                         return -EINVAL;
3181                 }
3182
3183                 switch (wValue) {
3184                 case USB_PORT_FEAT_ENABLE:
3185                         dev_dbg(dev, " ENABLE\n");
3186                         spin_lock_irqsave(&priv->lock, flags);
3187                         cvmx_usb_disable(&priv->usb);
3188                         spin_unlock_irqrestore(&priv->lock, flags);
3189                         break;
3190                 case USB_PORT_FEAT_SUSPEND:
3191                         dev_dbg(dev, " SUSPEND\n");
3192                         /* Not supported on Octeon */
3193                         break;
3194                 case USB_PORT_FEAT_POWER:
3195                         dev_dbg(dev, " POWER\n");
3196                         /* Not supported on Octeon */
3197                         break;
3198                 case USB_PORT_FEAT_INDICATOR:
3199                         dev_dbg(dev, " INDICATOR\n");
3200                         /* Port inidicator not supported */
3201                         break;
3202                 case USB_PORT_FEAT_C_CONNECTION:
3203                         dev_dbg(dev, " C_CONNECTION\n");
3204                         /* Clears drivers internal connect status change flag */
3205                         spin_lock_irqsave(&priv->lock, flags);
3206                         priv->usb.port_status = cvmx_usb_get_status(&priv->usb);
3207                         spin_unlock_irqrestore(&priv->lock, flags);
3208                         break;
3209                 case USB_PORT_FEAT_C_RESET:
3210                         dev_dbg(dev, " C_RESET\n");
3211                         /*
3212                          * Clears the driver's internal Port Reset Change flag.
3213                          */
3214                         spin_lock_irqsave(&priv->lock, flags);
3215                         priv->usb.port_status = cvmx_usb_get_status(&priv->usb);
3216                         spin_unlock_irqrestore(&priv->lock, flags);
3217                         break;
3218                 case USB_PORT_FEAT_C_ENABLE:
3219                         dev_dbg(dev, " C_ENABLE\n");
3220                         /*
3221                          * Clears the driver's internal Port Enable/Disable
3222                          * Change flag.
3223                          */
3224                         spin_lock_irqsave(&priv->lock, flags);
3225                         priv->usb.port_status = cvmx_usb_get_status(&priv->usb);
3226                         spin_unlock_irqrestore(&priv->lock, flags);
3227                         break;
3228                 case USB_PORT_FEAT_C_SUSPEND:
3229                         dev_dbg(dev, " C_SUSPEND\n");
3230                         /*
3231                          * Clears the driver's internal Port Suspend Change
3232                          * flag, which is set when resume signaling on the host
3233                          * port is complete.
3234                          */
3235                         break;
3236                 case USB_PORT_FEAT_C_OVER_CURRENT:
3237                         dev_dbg(dev, " C_OVER_CURRENT\n");
3238                         /* Clears the driver's overcurrent Change flag */
3239                         spin_lock_irqsave(&priv->lock, flags);
3240                         priv->usb.port_status = cvmx_usb_get_status(&priv->usb);
3241                         spin_unlock_irqrestore(&priv->lock, flags);
3242                         break;
3243                 default:
3244                         dev_dbg(dev, " UNKNOWN\n");
3245                         return -EINVAL;
3246                 }
3247                 break;
3248         case GetHubDescriptor:
3249                 dev_dbg(dev, "GetHubDescriptor\n");
3250                 desc = (struct usb_hub_descriptor *)buf;
3251                 desc->bDescLength = 9;
3252                 desc->bDescriptorType = 0x29;
3253                 desc->bNbrPorts = 1;
3254                 desc->wHubCharacteristics = 0x08;
3255                 desc->bPwrOn2PwrGood = 1;
3256                 desc->bHubContrCurrent = 0;
3257                 desc->u.hs.DeviceRemovable[0] = 0;
3258                 desc->u.hs.DeviceRemovable[1] = 0xff;
3259                 break;
3260         case GetHubStatus:
3261                 dev_dbg(dev, "GetHubStatus\n");
3262                 *(__le32 *) buf = 0;
3263                 break;
3264         case GetPortStatus:
3265                 dev_dbg(dev, "GetPortStatus\n");
3266                 if (wIndex != 1) {
3267                         dev_dbg(dev, " INVALID\n");
3268                         return -EINVAL;
3269                 }
3270
3271                 spin_lock_irqsave(&priv->lock, flags);
3272                 usb_port_status = cvmx_usb_get_status(&priv->usb);
3273                 spin_unlock_irqrestore(&priv->lock, flags);
3274                 port_status = 0;
3275
3276                 if (usb_port_status.connect_change) {
3277                         port_status |= (1 << USB_PORT_FEAT_C_CONNECTION);
3278                         dev_dbg(dev, " C_CONNECTION\n");
3279                 }
3280
3281                 if (usb_port_status.port_enabled) {
3282                         port_status |= (1 << USB_PORT_FEAT_C_ENABLE);
3283                         dev_dbg(dev, " C_ENABLE\n");
3284                 }
3285
3286                 if (usb_port_status.connected) {
3287                         port_status |= (1 << USB_PORT_FEAT_CONNECTION);
3288                         dev_dbg(dev, " CONNECTION\n");
3289                 }
3290
3291                 if (usb_port_status.port_enabled) {
3292                         port_status |= (1 << USB_PORT_FEAT_ENABLE);
3293                         dev_dbg(dev, " ENABLE\n");
3294                 }
3295
3296                 if (usb_port_status.port_over_current) {
3297                         port_status |= (1 << USB_PORT_FEAT_OVER_CURRENT);
3298                         dev_dbg(dev, " OVER_CURRENT\n");
3299                 }
3300
3301                 if (usb_port_status.port_powered) {
3302                         port_status |= (1 << USB_PORT_FEAT_POWER);
3303                         dev_dbg(dev, " POWER\n");
3304                 }
3305
3306                 if (usb_port_status.port_speed == CVMX_USB_SPEED_HIGH) {
3307                         port_status |= USB_PORT_STAT_HIGH_SPEED;
3308                         dev_dbg(dev, " HIGHSPEED\n");
3309                 } else if (usb_port_status.port_speed == CVMX_USB_SPEED_LOW) {
3310                         port_status |= (1 << USB_PORT_FEAT_LOWSPEED);
3311                         dev_dbg(dev, " LOWSPEED\n");
3312                 }
3313
3314                 *((__le32 *) buf) = cpu_to_le32(port_status);
3315                 break;
3316         case SetHubFeature:
3317                 dev_dbg(dev, "SetHubFeature\n");
3318                 /* No HUB features supported */
3319                 break;
3320         case SetPortFeature:
3321                 dev_dbg(dev, "SetPortFeature\n");
3322                 if (wIndex != 1) {
3323                         dev_dbg(dev, " INVALID\n");
3324                         return -EINVAL;
3325                 }
3326
3327                 switch (wValue) {
3328                 case USB_PORT_FEAT_SUSPEND:
3329                         dev_dbg(dev, " SUSPEND\n");
3330                         return -EINVAL;
3331                 case USB_PORT_FEAT_POWER:
3332                         dev_dbg(dev, " POWER\n");
3333                         return -EINVAL;
3334                 case USB_PORT_FEAT_RESET:
3335                         dev_dbg(dev, " RESET\n");
3336                         spin_lock_irqsave(&priv->lock, flags);
3337                         cvmx_usb_disable(&priv->usb);
3338                         if (cvmx_usb_enable(&priv->usb))
3339                                 dev_dbg(dev, "Failed to enable the port\n");
3340                         spin_unlock_irqrestore(&priv->lock, flags);
3341                         return 0;
3342                 case USB_PORT_FEAT_INDICATOR:
3343                         dev_dbg(dev, " INDICATOR\n");
3344                         /* Not supported */
3345                         break;
3346                 default:
3347                         dev_dbg(dev, " UNKNOWN\n");
3348                         return -EINVAL;
3349                 }
3350                 break;
3351         default:
3352                 dev_dbg(dev, "Unknown root hub request\n");
3353                 return -EINVAL;
3354         }
3355         return 0;
3356 }
3357
3358 static const struct hc_driver octeon_hc_driver = {
3359         .description            = "Octeon USB",
3360         .product_desc           = "Octeon Host Controller",
3361         .hcd_priv_size          = sizeof(struct octeon_hcd),
3362         .irq                    = octeon_usb_irq,
3363         .flags                  = HCD_MEMORY | HCD_USB2,
3364         .start                  = octeon_usb_start,
3365         .stop                   = octeon_usb_stop,
3366         .urb_enqueue            = octeon_usb_urb_enqueue,
3367         .urb_dequeue            = octeon_usb_urb_dequeue,
3368         .endpoint_disable       = octeon_usb_endpoint_disable,
3369         .get_frame_number       = octeon_usb_get_frame_number,
3370         .hub_status_data        = octeon_usb_hub_status_data,
3371         .hub_control            = octeon_usb_hub_control,
3372 };
3373
3374 static int octeon_usb_probe(struct platform_device *pdev)
3375 {
3376         int status;
3377         int initialize_flags;
3378         int usb_num;
3379         struct resource *res_mem;
3380         struct device_node *usbn_node;
3381         int irq = platform_get_irq(pdev, 0);
3382         struct device *dev = &pdev->dev;
3383         struct octeon_hcd *priv;
3384         struct usb_hcd *hcd;
3385         unsigned long flags;
3386         u32 clock_rate = 48000000;
3387         bool is_crystal_clock = false;
3388         const char *clock_type;
3389         int i;
3390
3391         if (dev->of_node == NULL) {
3392                 dev_err(dev, "Error: empty of_node\n");
3393                 return -ENXIO;
3394         }
3395         usbn_node = dev->of_node->parent;
3396
3397         i = of_property_read_u32(usbn_node,
3398                                  "refclk-frequency", &clock_rate);
3399         if (i) {
3400                 dev_err(dev, "No USBN \"refclk-frequency\"\n");
3401                 return -ENXIO;
3402         }
3403         switch (clock_rate) {
3404         case 12000000:
3405                 initialize_flags = CVMX_USB_INITIALIZE_FLAGS_CLOCK_12MHZ;
3406                 break;
3407         case 24000000:
3408                 initialize_flags = CVMX_USB_INITIALIZE_FLAGS_CLOCK_24MHZ;
3409                 break;
3410         case 48000000:
3411                 initialize_flags = CVMX_USB_INITIALIZE_FLAGS_CLOCK_48MHZ;
3412                 break;
3413         default:
3414                 dev_err(dev, "Illebal USBN \"refclk-frequency\" %u\n", clock_rate);
3415                 return -ENXIO;
3416
3417         }
3418
3419         i = of_property_read_string(usbn_node,
3420                                     "refclk-type", &clock_type);
3421
3422         if (!i && strcmp("crystal", clock_type) == 0)
3423                 is_crystal_clock = true;
3424
3425         if (is_crystal_clock)
3426                 initialize_flags |= CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_XI;
3427         else
3428                 initialize_flags |= CVMX_USB_INITIALIZE_FLAGS_CLOCK_XO_GND;
3429
3430         res_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
3431         if (res_mem == NULL) {
3432                 dev_err(dev, "found no memory resource\n");
3433                 return -ENXIO;
3434         }
3435         usb_num = (res_mem->start >> 44) & 1;
3436
3437         if (irq < 0) {
3438                 /* Defective device tree, but we know how to fix it. */
3439                 irq_hw_number_t hwirq = usb_num ? (1 << 6) + 17 : 56;
3440                 irq = irq_create_mapping(NULL, hwirq);
3441         }
3442
3443         /*
3444          * Set the DMA mask to 64bits so we get buffers already translated for
3445          * DMA.
3446          */
3447         dev->coherent_dma_mask = ~0;
3448         dev->dma_mask = &dev->coherent_dma_mask;
3449
3450         /*
3451          * Only cn52XX and cn56XX have DWC_OTG USB hardware and the
3452          * IOB priority registers.  Under heavy network load USB
3453          * hardware can be starved by the IOB causing a crash.  Give
3454          * it a priority boost if it has been waiting more than 400
3455          * cycles to avoid this situation.
3456          *
3457          * Testing indicates that a cnt_val of 8192 is not sufficient,
3458          * but no failures are seen with 4096.  We choose a value of
3459          * 400 to give a safety factor of 10.
3460          */
3461         if (OCTEON_IS_MODEL(OCTEON_CN52XX) || OCTEON_IS_MODEL(OCTEON_CN56XX)) {
3462                 union cvmx_iob_n2c_l2c_pri_cnt pri_cnt;
3463
3464                 pri_cnt.u64 = 0;
3465                 pri_cnt.s.cnt_enb = 1;
3466                 pri_cnt.s.cnt_val = 400;
3467                 cvmx_write_csr(CVMX_IOB_N2C_L2C_PRI_CNT, pri_cnt.u64);
3468         }
3469
3470         hcd = usb_create_hcd(&octeon_hc_driver, dev, dev_name(dev));
3471         if (!hcd) {
3472                 dev_dbg(dev, "Failed to allocate memory for HCD\n");
3473                 return -1;
3474         }
3475         hcd->uses_new_polling = 1;
3476         priv = (struct octeon_hcd *)hcd->hcd_priv;
3477
3478         spin_lock_init(&priv->lock);
3479
3480         tasklet_init(&priv->dequeue_tasklet, octeon_usb_urb_dequeue_work, (unsigned long)priv);
3481         INIT_LIST_HEAD(&priv->dequeue_list);
3482
3483         status = cvmx_usb_initialize(&priv->usb, usb_num, initialize_flags);
3484         if (status) {
3485                 dev_dbg(dev, "USB initialization failed with %d\n", status);
3486                 kfree(hcd);
3487                 return -1;
3488         }
3489
3490         /* This delay is needed for CN3010, but I don't know why... */
3491         mdelay(10);
3492
3493         spin_lock_irqsave(&priv->lock, flags);
3494         cvmx_usb_poll(&priv->usb);
3495         spin_unlock_irqrestore(&priv->lock, flags);
3496
3497         status = usb_add_hcd(hcd, irq, 0);
3498         if (status) {
3499                 dev_dbg(dev, "USB add HCD failed with %d\n", status);
3500                 kfree(hcd);
3501                 return -1;
3502         }
3503         device_wakeup_enable(hcd->self.controller);
3504
3505         dev_info(dev, "Registered HCD for port %d on irq %d\n", usb_num, irq);
3506
3507         return 0;
3508 }
3509
3510 static int octeon_usb_remove(struct platform_device *pdev)
3511 {
3512         int status;
3513         struct device *dev = &pdev->dev;
3514         struct usb_hcd *hcd = dev_get_drvdata(dev);
3515         struct octeon_hcd *priv = hcd_to_octeon(hcd);
3516         unsigned long flags;
3517
3518         usb_remove_hcd(hcd);
3519         tasklet_kill(&priv->dequeue_tasklet);
3520         spin_lock_irqsave(&priv->lock, flags);
3521         status = cvmx_usb_shutdown(&priv->usb);
3522         spin_unlock_irqrestore(&priv->lock, flags);
3523         if (status)
3524                 dev_dbg(dev, "USB shutdown failed with %d\n", status);
3525
3526         kfree(hcd);
3527
3528         return 0;
3529 }
3530
3531 static struct of_device_id octeon_usb_match[] = {
3532         {
3533                 .compatible = "cavium,octeon-5750-usbc",
3534         },
3535         {},
3536 };
3537
3538 static struct platform_driver octeon_usb_driver = {
3539         .driver = {
3540                 .name       = "OcteonUSB",
3541                 .owner          = THIS_MODULE,
3542                 .of_match_table = octeon_usb_match,
3543         },
3544         .probe      = octeon_usb_probe,
3545         .remove     = octeon_usb_remove,
3546 };
3547
3548 static int __init octeon_usb_driver_init(void)
3549 {
3550         if (usb_disabled())
3551                 return 0;
3552
3553         return platform_driver_register(&octeon_usb_driver);
3554 }
3555 module_init(octeon_usb_driver_init);
3556
3557 static void __exit octeon_usb_driver_exit(void)
3558 {
3559         if (usb_disabled())
3560                 return;
3561
3562         platform_driver_unregister(&octeon_usb_driver);
3563 }
3564 module_exit(octeon_usb_driver_exit);
3565
3566 MODULE_LICENSE("GPL");
3567 MODULE_AUTHOR("Cavium, Inc. <support@cavium.com>");
3568 MODULE_DESCRIPTION("Cavium Inc. OCTEON USB Host driver.");