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