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