Merge tag 'efi-2020-07-rc6' of https://gitlab.denx.de/u-boot/custodians/u-boot-efi
[oweals/u-boot.git] / drivers / usb / host / xhci-ring.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * USB HOST XHCI Controller stack
4  *
5  * Based on xHCI host controller driver in linux-kernel
6  * by Sarah Sharp.
7  *
8  * Copyright (C) 2008 Intel Corp.
9  * Author: Sarah Sharp
10  *
11  * Copyright (C) 2013 Samsung Electronics Co.Ltd
12  * Authors: Vivek Gautam <gautam.vivek@samsung.com>
13  *          Vikas Sajjan <vikas.sajjan@samsung.com>
14  */
15
16 #include <common.h>
17 #include <cpu_func.h>
18 #include <log.h>
19 #include <asm/byteorder.h>
20 #include <usb.h>
21 #include <asm/unaligned.h>
22 #include <linux/bug.h>
23 #include <linux/errno.h>
24
25 #include <usb/xhci.h>
26
27 /**
28  * Is this TRB a link TRB or was the last TRB the last TRB in this event ring
29  * segment?  I.e. would the updated event TRB pointer step off the end of the
30  * event seg ?
31  *
32  * @param ctrl  Host controller data structure
33  * @param ring  pointer to the ring
34  * @param seg   poniter to the segment to which TRB belongs
35  * @param trb   poniter to the ring trb
36  * @return 1 if this TRB a link TRB else 0
37  */
38 static int last_trb(struct xhci_ctrl *ctrl, struct xhci_ring *ring,
39                         struct xhci_segment *seg, union xhci_trb *trb)
40 {
41         if (ring == ctrl->event_ring)
42                 return trb == &seg->trbs[TRBS_PER_SEGMENT];
43         else
44                 return TRB_TYPE_LINK_LE32(trb->link.control);
45 }
46
47 /**
48  * Does this link TRB point to the first segment in a ring,
49  * or was the previous TRB the last TRB on the last segment in the ERST?
50  *
51  * @param ctrl  Host controller data structure
52  * @param ring  pointer to the ring
53  * @param seg   poniter to the segment to which TRB belongs
54  * @param trb   poniter to the ring trb
55  * @return 1 if this TRB is the last TRB on the last segment else 0
56  */
57 static bool last_trb_on_last_seg(struct xhci_ctrl *ctrl,
58                                  struct xhci_ring *ring,
59                                  struct xhci_segment *seg,
60                                  union xhci_trb *trb)
61 {
62         if (ring == ctrl->event_ring)
63                 return ((trb == &seg->trbs[TRBS_PER_SEGMENT]) &&
64                         (seg->next == ring->first_seg));
65         else
66                 return le32_to_cpu(trb->link.control) & LINK_TOGGLE;
67 }
68
69 /**
70  * See Cycle bit rules. SW is the consumer for the event ring only.
71  * Don't make a ring full of link TRBs.  That would be dumb and this would loop.
72  *
73  * If we've just enqueued a TRB that is in the middle of a TD (meaning the
74  * chain bit is set), then set the chain bit in all the following link TRBs.
75  * If we've enqueued the last TRB in a TD, make sure the following link TRBs
76  * have their chain bit cleared (so that each Link TRB is a separate TD).
77  *
78  * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit
79  * set, but other sections talk about dealing with the chain bit set.  This was
80  * fixed in the 0.96 specification errata, but we have to assume that all 0.95
81  * xHCI hardware can't handle the chain bit being cleared on a link TRB.
82  *
83  * @param ctrl  Host controller data structure
84  * @param ring  pointer to the ring
85  * @param more_trbs_coming      flag to indicate whether more trbs
86  *                              are expected or NOT.
87  *                              Will you enqueue more TRBs before calling
88  *                              prepare_ring()?
89  * @return none
90  */
91 static void inc_enq(struct xhci_ctrl *ctrl, struct xhci_ring *ring,
92                                                 bool more_trbs_coming)
93 {
94         u32 chain;
95         union xhci_trb *next;
96
97         chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN;
98         next = ++(ring->enqueue);
99
100         /*
101          * Update the dequeue pointer further if that was a link TRB or we're at
102          * the end of an event ring segment (which doesn't have link TRBS)
103          */
104         while (last_trb(ctrl, ring, ring->enq_seg, next)) {
105                 if (ring != ctrl->event_ring) {
106                         /*
107                          * If the caller doesn't plan on enqueueing more
108                          * TDs before ringing the doorbell, then we
109                          * don't want to give the link TRB to the
110                          * hardware just yet.  We'll give the link TRB
111                          * back in prepare_ring() just before we enqueue
112                          * the TD at the top of the ring.
113                          */
114                         if (!chain && !more_trbs_coming)
115                                 break;
116
117                         /*
118                          * If we're not dealing with 0.95 hardware or
119                          * isoc rings on AMD 0.96 host,
120                          * carry over the chain bit of the previous TRB
121                          * (which may mean the chain bit is cleared).
122                          */
123                         next->link.control &= cpu_to_le32(~TRB_CHAIN);
124                         next->link.control |= cpu_to_le32(chain);
125
126                         next->link.control ^= cpu_to_le32(TRB_CYCLE);
127                         xhci_flush_cache((uintptr_t)next,
128                                          sizeof(union xhci_trb));
129                 }
130                 /* Toggle the cycle bit after the last ring segment. */
131                 if (last_trb_on_last_seg(ctrl, ring,
132                                         ring->enq_seg, next))
133                         ring->cycle_state = (ring->cycle_state ? 0 : 1);
134
135                 ring->enq_seg = ring->enq_seg->next;
136                 ring->enqueue = ring->enq_seg->trbs;
137                 next = ring->enqueue;
138         }
139 }
140
141 /**
142  * See Cycle bit rules. SW is the consumer for the event ring only.
143  * Don't make a ring full of link TRBs.  That would be dumb and this would loop.
144  *
145  * @param ctrl  Host controller data structure
146  * @param ring  Ring whose Dequeue TRB pointer needs to be incremented.
147  * return none
148  */
149 static void inc_deq(struct xhci_ctrl *ctrl, struct xhci_ring *ring)
150 {
151         do {
152                 /*
153                  * Update the dequeue pointer further if that was a link TRB or
154                  * we're at the end of an event ring segment (which doesn't have
155                  * link TRBS)
156                  */
157                 if (last_trb(ctrl, ring, ring->deq_seg, ring->dequeue)) {
158                         if (ring == ctrl->event_ring &&
159                                         last_trb_on_last_seg(ctrl, ring,
160                                                 ring->deq_seg, ring->dequeue)) {
161                                 ring->cycle_state = (ring->cycle_state ? 0 : 1);
162                         }
163                         ring->deq_seg = ring->deq_seg->next;
164                         ring->dequeue = ring->deq_seg->trbs;
165                 } else {
166                         ring->dequeue++;
167                 }
168         } while (last_trb(ctrl, ring, ring->deq_seg, ring->dequeue));
169 }
170
171 /**
172  * Generic function for queueing a TRB on a ring.
173  * The caller must have checked to make sure there's room on the ring.
174  *
175  * @param       more_trbs_coming:   Will you enqueue more TRBs before calling
176  *                              prepare_ring()?
177  * @param ctrl  Host controller data structure
178  * @param ring  pointer to the ring
179  * @param more_trbs_coming      flag to indicate whether more trbs
180  * @param trb_fields    pointer to trb field array containing TRB contents
181  * @return pointer to the enqueued trb
182  */
183 static struct xhci_generic_trb *queue_trb(struct xhci_ctrl *ctrl,
184                                           struct xhci_ring *ring,
185                                           bool more_trbs_coming,
186                                           unsigned int *trb_fields)
187 {
188         struct xhci_generic_trb *trb;
189         int i;
190
191         trb = &ring->enqueue->generic;
192
193         for (i = 0; i < 4; i++)
194                 trb->field[i] = cpu_to_le32(trb_fields[i]);
195
196         xhci_flush_cache((uintptr_t)trb, sizeof(struct xhci_generic_trb));
197
198         inc_enq(ctrl, ring, more_trbs_coming);
199
200         return trb;
201 }
202
203 /**
204  * Does various checks on the endpoint ring, and makes it ready
205  * to queue num_trbs.
206  *
207  * @param ctrl          Host controller data structure
208  * @param ep_ring       pointer to the EP Transfer Ring
209  * @param ep_state      State of the End Point
210  * @return error code in case of invalid ep_state, 0 on success
211  */
212 static int prepare_ring(struct xhci_ctrl *ctrl, struct xhci_ring *ep_ring,
213                                                         u32 ep_state)
214 {
215         union xhci_trb *next = ep_ring->enqueue;
216
217         /* Make sure the endpoint has been added to xHC schedule */
218         switch (ep_state) {
219         case EP_STATE_DISABLED:
220                 /*
221                  * USB core changed config/interfaces without notifying us,
222                  * or hardware is reporting the wrong state.
223                  */
224                 puts("WARN urb submitted to disabled ep\n");
225                 return -ENOENT;
226         case EP_STATE_ERROR:
227                 puts("WARN waiting for error on ep to be cleared\n");
228                 return -EINVAL;
229         case EP_STATE_HALTED:
230                 puts("WARN halted endpoint, queueing URB anyway.\n");
231         case EP_STATE_STOPPED:
232         case EP_STATE_RUNNING:
233                 debug("EP STATE RUNNING.\n");
234                 break;
235         default:
236                 puts("ERROR unknown endpoint state for ep\n");
237                 return -EINVAL;
238         }
239
240         while (last_trb(ctrl, ep_ring, ep_ring->enq_seg, next)) {
241                 /*
242                  * If we're not dealing with 0.95 hardware or isoc rings
243                  * on AMD 0.96 host, clear the chain bit.
244                  */
245                 next->link.control &= cpu_to_le32(~TRB_CHAIN);
246
247                 next->link.control ^= cpu_to_le32(TRB_CYCLE);
248
249                 xhci_flush_cache((uintptr_t)next, sizeof(union xhci_trb));
250
251                 /* Toggle the cycle bit after the last ring segment. */
252                 if (last_trb_on_last_seg(ctrl, ep_ring,
253                                         ep_ring->enq_seg, next))
254                         ep_ring->cycle_state = (ep_ring->cycle_state ? 0 : 1);
255                 ep_ring->enq_seg = ep_ring->enq_seg->next;
256                 ep_ring->enqueue = ep_ring->enq_seg->trbs;
257                 next = ep_ring->enqueue;
258         }
259
260         return 0;
261 }
262
263 /**
264  * Generic function for queueing a command TRB on the command ring.
265  * Check to make sure there's room on the command ring for one command TRB.
266  *
267  * @param ctrl          Host controller data structure
268  * @param ptr           Pointer address to write in the first two fields (opt.)
269  * @param slot_id       Slot ID to encode in the flags field (opt.)
270  * @param ep_index      Endpoint index to encode in the flags field (opt.)
271  * @param cmd           Command type to enqueue
272  * @return none
273  */
274 void xhci_queue_command(struct xhci_ctrl *ctrl, u8 *ptr, u32 slot_id,
275                         u32 ep_index, trb_type cmd)
276 {
277         u32 fields[4];
278         u64 val_64 = (uintptr_t)ptr;
279
280         BUG_ON(prepare_ring(ctrl, ctrl->cmd_ring, EP_STATE_RUNNING));
281
282         fields[0] = lower_32_bits(val_64);
283         fields[1] = upper_32_bits(val_64);
284         fields[2] = 0;
285         fields[3] = TRB_TYPE(cmd) | SLOT_ID_FOR_TRB(slot_id) |
286                     ctrl->cmd_ring->cycle_state;
287
288         /*
289          * Only 'reset endpoint', 'stop endpoint' and 'set TR dequeue pointer'
290          * commands need endpoint id encoded.
291          */
292         if (cmd >= TRB_RESET_EP && cmd <= TRB_SET_DEQ)
293                 fields[3] |= EP_ID_FOR_TRB(ep_index);
294
295         queue_trb(ctrl, ctrl->cmd_ring, false, fields);
296
297         /* Ring the command ring doorbell */
298         xhci_writel(&ctrl->dba->doorbell[0], DB_VALUE_HOST);
299 }
300
301 /**
302  * The TD size is the number of bytes remaining in the TD (including this TRB),
303  * right shifted by 10.
304  * It must fit in bits 21:17, so it can't be bigger than 31.
305  *
306  * @param remainder     remaining packets to be sent
307  * @return remainder if remainder is less than max else max
308  */
309 static u32 xhci_td_remainder(unsigned int remainder)
310 {
311         u32 max = (1 << (21 - 17 + 1)) - 1;
312
313         if ((remainder >> 10) >= max)
314                 return max << 17;
315         else
316                 return (remainder >> 10) << 17;
317 }
318
319 /**
320  * Finds out the remanining packets to be sent
321  *
322  * @param running_total total size sent so far
323  * @param trb_buff_len  length of the TRB Buffer
324  * @param total_packet_count    total packet count
325  * @param maxpacketsize         max packet size of current pipe
326  * @param num_trbs_left         number of TRBs left to be processed
327  * @return 0 if running_total or trb_buff_len is 0, else remainder
328  */
329 static u32 xhci_v1_0_td_remainder(int running_total,
330                                 int trb_buff_len,
331                                 unsigned int total_packet_count,
332                                 int maxpacketsize,
333                                 unsigned int num_trbs_left)
334 {
335         int packets_transferred;
336
337         /* One TRB with a zero-length data packet. */
338         if (num_trbs_left == 0 || (running_total == 0 && trb_buff_len == 0))
339                 return 0;
340
341         /*
342          * All the TRB queueing functions don't count the current TRB in
343          * running_total.
344          */
345         packets_transferred = (running_total + trb_buff_len) / maxpacketsize;
346
347         if ((total_packet_count - packets_transferred) > 31)
348                 return 31 << 17;
349         return (total_packet_count - packets_transferred) << 17;
350 }
351
352 /**
353  * Ring the doorbell of the End Point
354  *
355  * @param udev          pointer to the USB device structure
356  * @param ep_index      index of the endpoint
357  * @param start_cycle   cycle flag of the first TRB
358  * @param start_trb     pionter to the first TRB
359  * @return none
360  */
361 static void giveback_first_trb(struct usb_device *udev, int ep_index,
362                                 int start_cycle,
363                                 struct xhci_generic_trb *start_trb)
364 {
365         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
366
367         /*
368          * Pass all the TRBs to the hardware at once and make sure this write
369          * isn't reordered.
370          */
371         if (start_cycle)
372                 start_trb->field[3] |= cpu_to_le32(start_cycle);
373         else
374                 start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE);
375
376         xhci_flush_cache((uintptr_t)start_trb, sizeof(struct xhci_generic_trb));
377
378         /* Ringing EP doorbell here */
379         xhci_writel(&ctrl->dba->doorbell[udev->slot_id],
380                                 DB_VALUE(ep_index, 0));
381
382         return;
383 }
384
385 /**** POLLING mechanism for XHCI ****/
386
387 /**
388  * Finalizes a handled event TRB by advancing our dequeue pointer and giving
389  * the TRB back to the hardware for recycling. Must call this exactly once at
390  * the end of each event handler, and not touch the TRB again afterwards.
391  *
392  * @param ctrl  Host controller data structure
393  * @return none
394  */
395 void xhci_acknowledge_event(struct xhci_ctrl *ctrl)
396 {
397         /* Advance our dequeue pointer to the next event */
398         inc_deq(ctrl, ctrl->event_ring);
399
400         /* Inform the hardware */
401         xhci_writeq(&ctrl->ir_set->erst_dequeue,
402                 (uintptr_t)ctrl->event_ring->dequeue | ERST_EHB);
403 }
404
405 /**
406  * Checks if there is a new event to handle on the event ring.
407  *
408  * @param ctrl  Host controller data structure
409  * @return 0 if failure else 1 on success
410  */
411 static int event_ready(struct xhci_ctrl *ctrl)
412 {
413         union xhci_trb *event;
414
415         xhci_inval_cache((uintptr_t)ctrl->event_ring->dequeue,
416                          sizeof(union xhci_trb));
417
418         event = ctrl->event_ring->dequeue;
419
420         /* Does the HC or OS own the TRB? */
421         if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) !=
422                 ctrl->event_ring->cycle_state)
423                 return 0;
424
425         return 1;
426 }
427
428 /**
429  * Waits for a specific type of event and returns it. Discards unexpected
430  * events. Caller *must* call xhci_acknowledge_event() after it is finished
431  * processing the event, and must not access the returned pointer afterwards.
432  *
433  * @param ctrl          Host controller data structure
434  * @param expected      TRB type expected from Event TRB
435  * @return pointer to event trb
436  */
437 union xhci_trb *xhci_wait_for_event(struct xhci_ctrl *ctrl, trb_type expected)
438 {
439         trb_type type;
440         unsigned long ts = get_timer(0);
441
442         do {
443                 union xhci_trb *event = ctrl->event_ring->dequeue;
444
445                 if (!event_ready(ctrl))
446                         continue;
447
448                 type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->event_cmd.flags));
449                 if (type == expected)
450                         return event;
451
452                 if (type == TRB_PORT_STATUS)
453                 /* TODO: remove this once enumeration has been reworked */
454                         /*
455                          * Port status change events always have a
456                          * successful completion code
457                          */
458                         BUG_ON(GET_COMP_CODE(
459                                 le32_to_cpu(event->generic.field[2])) !=
460                                                                 COMP_SUCCESS);
461                 else
462                         printf("Unexpected XHCI event TRB, skipping... "
463                                 "(%08x %08x %08x %08x)\n",
464                                 le32_to_cpu(event->generic.field[0]),
465                                 le32_to_cpu(event->generic.field[1]),
466                                 le32_to_cpu(event->generic.field[2]),
467                                 le32_to_cpu(event->generic.field[3]));
468
469                 xhci_acknowledge_event(ctrl);
470         } while (get_timer(ts) < XHCI_TIMEOUT);
471
472         if (expected == TRB_TRANSFER)
473                 return NULL;
474
475         printf("XHCI timeout on event type %d... cannot recover.\n", expected);
476         BUG();
477 }
478
479 /*
480  * Stops transfer processing for an endpoint and throws away all unprocessed
481  * TRBs by setting the xHC's dequeue pointer to our enqueue pointer. The next
482  * xhci_bulk_tx/xhci_ctrl_tx on this enpoint will add new transfers there and
483  * ring the doorbell, causing this endpoint to start working again.
484  * (Careful: This will BUG() when there was no transfer in progress. Shouldn't
485  * happen in practice for current uses and is too complicated to fix right now.)
486  */
487 static void abort_td(struct usb_device *udev, int ep_index)
488 {
489         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
490         struct xhci_ring *ring =  ctrl->devs[udev->slot_id]->eps[ep_index].ring;
491         union xhci_trb *event;
492         u32 field;
493
494         xhci_queue_command(ctrl, NULL, udev->slot_id, ep_index, TRB_STOP_RING);
495
496         event = xhci_wait_for_event(ctrl, TRB_TRANSFER);
497         field = le32_to_cpu(event->trans_event.flags);
498         BUG_ON(TRB_TO_SLOT_ID(field) != udev->slot_id);
499         BUG_ON(TRB_TO_EP_INDEX(field) != ep_index);
500         BUG_ON(GET_COMP_CODE(le32_to_cpu(event->trans_event.transfer_len
501                 != COMP_STOP)));
502         xhci_acknowledge_event(ctrl);
503
504         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
505         BUG_ON(TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags))
506                 != udev->slot_id || GET_COMP_CODE(le32_to_cpu(
507                 event->event_cmd.status)) != COMP_SUCCESS);
508         xhci_acknowledge_event(ctrl);
509
510         xhci_queue_command(ctrl, (void *)((uintptr_t)ring->enqueue |
511                 ring->cycle_state), udev->slot_id, ep_index, TRB_SET_DEQ);
512         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
513         BUG_ON(TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags))
514                 != udev->slot_id || GET_COMP_CODE(le32_to_cpu(
515                 event->event_cmd.status)) != COMP_SUCCESS);
516         xhci_acknowledge_event(ctrl);
517 }
518
519 static void record_transfer_result(struct usb_device *udev,
520                                    union xhci_trb *event, int length)
521 {
522         udev->act_len = min(length, length -
523                 (int)EVENT_TRB_LEN(le32_to_cpu(event->trans_event.transfer_len)));
524
525         switch (GET_COMP_CODE(le32_to_cpu(event->trans_event.transfer_len))) {
526         case COMP_SUCCESS:
527                 BUG_ON(udev->act_len != length);
528                 /* fallthrough */
529         case COMP_SHORT_TX:
530                 udev->status = 0;
531                 break;
532         case COMP_STALL:
533                 udev->status = USB_ST_STALLED;
534                 break;
535         case COMP_DB_ERR:
536         case COMP_TRB_ERR:
537                 udev->status = USB_ST_BUF_ERR;
538                 break;
539         case COMP_BABBLE:
540                 udev->status = USB_ST_BABBLE_DET;
541                 break;
542         default:
543                 udev->status = 0x80;  /* USB_ST_TOO_LAZY_TO_MAKE_A_NEW_MACRO */
544         }
545 }
546
547 /**** Bulk and Control transfer methods ****/
548 /**
549  * Queues up the BULK Request
550  *
551  * @param udev          pointer to the USB device structure
552  * @param pipe          contains the DIR_IN or OUT , devnum
553  * @param length        length of the buffer
554  * @param buffer        buffer to be read/written based on the request
555  * @return returns 0 if successful else -1 on failure
556  */
557 int xhci_bulk_tx(struct usb_device *udev, unsigned long pipe,
558                         int length, void *buffer)
559 {
560         int num_trbs = 0;
561         struct xhci_generic_trb *start_trb;
562         bool first_trb = false;
563         int start_cycle;
564         u32 field = 0;
565         u32 length_field = 0;
566         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
567         int slot_id = udev->slot_id;
568         int ep_index;
569         struct xhci_virt_device *virt_dev;
570         struct xhci_ep_ctx *ep_ctx;
571         struct xhci_ring *ring;         /* EP transfer ring */
572         union xhci_trb *event;
573
574         int running_total, trb_buff_len;
575         unsigned int total_packet_count;
576         int maxpacketsize;
577         u64 addr;
578         int ret;
579         u32 trb_fields[4];
580         u64 val_64 = (uintptr_t)buffer;
581
582         debug("dev=%p, pipe=%lx, buffer=%p, length=%d\n",
583                 udev, pipe, buffer, length);
584
585         ep_index = usb_pipe_ep_index(pipe);
586         virt_dev = ctrl->devs[slot_id];
587
588         xhci_inval_cache((uintptr_t)virt_dev->out_ctx->bytes,
589                          virt_dev->out_ctx->size);
590
591         ep_ctx = xhci_get_ep_ctx(ctrl, virt_dev->out_ctx, ep_index);
592
593         ring = virt_dev->eps[ep_index].ring;
594         /*
595          * How much data is (potentially) left before the 64KB boundary?
596          * XHCI Spec puts restriction( TABLE 49 and 6.4.1 section of XHCI Spec)
597          * that the buffer should not span 64KB boundary. if so
598          * we send request in more than 1 TRB by chaining them.
599          */
600         running_total = TRB_MAX_BUFF_SIZE -
601                         (lower_32_bits(val_64) & (TRB_MAX_BUFF_SIZE - 1));
602         trb_buff_len = running_total;
603         running_total &= TRB_MAX_BUFF_SIZE - 1;
604
605         /*
606          * If there's some data on this 64KB chunk, or we have to send a
607          * zero-length transfer, we need at least one TRB
608          */
609         if (running_total != 0 || length == 0)
610                 num_trbs++;
611
612         /* How many more 64KB chunks to transfer, how many more TRBs? */
613         while (running_total < length) {
614                 num_trbs++;
615                 running_total += TRB_MAX_BUFF_SIZE;
616         }
617
618         /*
619          * XXX: Calling routine prepare_ring() called in place of
620          * prepare_trasfer() as there in 'Linux' since we are not
621          * maintaining multiple TDs/transfer at the same time.
622          */
623         ret = prepare_ring(ctrl, ring,
624                            le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK);
625         if (ret < 0)
626                 return ret;
627
628         /*
629          * Don't give the first TRB to the hardware (by toggling the cycle bit)
630          * until we've finished creating all the other TRBs.  The ring's cycle
631          * state may change as we enqueue the other TRBs, so save it too.
632          */
633         start_trb = &ring->enqueue->generic;
634         start_cycle = ring->cycle_state;
635
636         running_total = 0;
637         maxpacketsize = usb_maxpacket(udev, pipe);
638
639         total_packet_count = DIV_ROUND_UP(length, maxpacketsize);
640
641         /* How much data is in the first TRB? */
642         /*
643          * How much data is (potentially) left before the 64KB boundary?
644          * XHCI Spec puts restriction( TABLE 49 and 6.4.1 section of XHCI Spec)
645          * that the buffer should not span 64KB boundary. if so
646          * we send request in more than 1 TRB by chaining them.
647          */
648         addr = val_64;
649
650         if (trb_buff_len > length)
651                 trb_buff_len = length;
652
653         first_trb = true;
654
655         /* flush the buffer before use */
656         xhci_flush_cache((uintptr_t)buffer, length);
657
658         /* Queue the first TRB, even if it's zero-length */
659         do {
660                 u32 remainder = 0;
661                 field = 0;
662                 /* Don't change the cycle bit of the first TRB until later */
663                 if (first_trb) {
664                         first_trb = false;
665                         if (start_cycle == 0)
666                                 field |= TRB_CYCLE;
667                 } else {
668                         field |= ring->cycle_state;
669                 }
670
671                 /*
672                  * Chain all the TRBs together; clear the chain bit in the last
673                  * TRB to indicate it's the last TRB in the chain.
674                  */
675                 if (num_trbs > 1)
676                         field |= TRB_CHAIN;
677                 else
678                         field |= TRB_IOC;
679
680                 /* Only set interrupt on short packet for IN endpoints */
681                 if (usb_pipein(pipe))
682                         field |= TRB_ISP;
683
684                 /* Set the TRB length, TD size, and interrupter fields. */
685                 if (HC_VERSION(xhci_readl(&ctrl->hccr->cr_capbase)) < 0x100)
686                         remainder = xhci_td_remainder(length - running_total);
687                 else
688                         remainder = xhci_v1_0_td_remainder(running_total,
689                                                            trb_buff_len,
690                                                            total_packet_count,
691                                                            maxpacketsize,
692                                                            num_trbs - 1);
693
694                 length_field = ((trb_buff_len & TRB_LEN_MASK) |
695                                 remainder |
696                                 ((0 & TRB_INTR_TARGET_MASK) <<
697                                 TRB_INTR_TARGET_SHIFT));
698
699                 trb_fields[0] = lower_32_bits(addr);
700                 trb_fields[1] = upper_32_bits(addr);
701                 trb_fields[2] = length_field;
702                 trb_fields[3] = field | (TRB_NORMAL << TRB_TYPE_SHIFT);
703
704                 queue_trb(ctrl, ring, (num_trbs > 1), trb_fields);
705
706                 --num_trbs;
707
708                 running_total += trb_buff_len;
709
710                 /* Calculate length for next transfer */
711                 addr += trb_buff_len;
712                 trb_buff_len = min((length - running_total), TRB_MAX_BUFF_SIZE);
713         } while (running_total < length);
714
715         giveback_first_trb(udev, ep_index, start_cycle, start_trb);
716
717         event = xhci_wait_for_event(ctrl, TRB_TRANSFER);
718         if (!event) {
719                 debug("XHCI bulk transfer timed out, aborting...\n");
720                 abort_td(udev, ep_index);
721                 udev->status = USB_ST_NAK_REC;  /* closest thing to a timeout */
722                 udev->act_len = 0;
723                 return -ETIMEDOUT;
724         }
725         field = le32_to_cpu(event->trans_event.flags);
726
727         BUG_ON(TRB_TO_SLOT_ID(field) != slot_id);
728         BUG_ON(TRB_TO_EP_INDEX(field) != ep_index);
729         BUG_ON(*(void **)(uintptr_t)le64_to_cpu(event->trans_event.buffer) -
730                 buffer > (size_t)length);
731
732         record_transfer_result(udev, event, length);
733         xhci_acknowledge_event(ctrl);
734         xhci_inval_cache((uintptr_t)buffer, length);
735
736         return (udev->status != USB_ST_NOT_PROC) ? 0 : -1;
737 }
738
739 /**
740  * Queues up the Control Transfer Request
741  *
742  * @param udev  pointer to the USB device structure
743  * @param pipe          contains the DIR_IN or OUT , devnum
744  * @param req           request type
745  * @param length        length of the buffer
746  * @param buffer        buffer to be read/written based on the request
747  * @return returns 0 if successful else error code on failure
748  */
749 int xhci_ctrl_tx(struct usb_device *udev, unsigned long pipe,
750                         struct devrequest *req, int length,
751                         void *buffer)
752 {
753         int ret;
754         int start_cycle;
755         int num_trbs;
756         u32 field;
757         u32 length_field;
758         u64 buf_64 = 0;
759         struct xhci_generic_trb *start_trb;
760         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
761         int slot_id = udev->slot_id;
762         int ep_index;
763         u32 trb_fields[4];
764         struct xhci_virt_device *virt_dev = ctrl->devs[slot_id];
765         struct xhci_ring *ep_ring;
766         union xhci_trb *event;
767
768         debug("req=%u (%#x), type=%u (%#x), value=%u (%#x), index=%u\n",
769                 req->request, req->request,
770                 req->requesttype, req->requesttype,
771                 le16_to_cpu(req->value), le16_to_cpu(req->value),
772                 le16_to_cpu(req->index));
773
774         ep_index = usb_pipe_ep_index(pipe);
775
776         ep_ring = virt_dev->eps[ep_index].ring;
777
778         /*
779          * Check to see if the max packet size for the default control
780          * endpoint changed during FS device enumeration
781          */
782         if (udev->speed == USB_SPEED_FULL) {
783                 ret = xhci_check_maxpacket(udev);
784                 if (ret < 0)
785                         return ret;
786         }
787
788         xhci_inval_cache((uintptr_t)virt_dev->out_ctx->bytes,
789                          virt_dev->out_ctx->size);
790
791         struct xhci_ep_ctx *ep_ctx = NULL;
792         ep_ctx = xhci_get_ep_ctx(ctrl, virt_dev->out_ctx, ep_index);
793
794         /* 1 TRB for setup, 1 for status */
795         num_trbs = 2;
796         /*
797          * Don't need to check if we need additional event data and normal TRBs,
798          * since data in control transfers will never get bigger than 16MB
799          * XXX: can we get a buffer that crosses 64KB boundaries?
800          */
801
802         if (length > 0)
803                 num_trbs++;
804         /*
805          * XXX: Calling routine prepare_ring() called in place of
806          * prepare_trasfer() as there in 'Linux' since we are not
807          * maintaining multiple TDs/transfer at the same time.
808          */
809         ret = prepare_ring(ctrl, ep_ring,
810                                 le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK);
811
812         if (ret < 0)
813                 return ret;
814
815         /*
816          * Don't give the first TRB to the hardware (by toggling the cycle bit)
817          * until we've finished creating all the other TRBs.  The ring's cycle
818          * state may change as we enqueue the other TRBs, so save it too.
819          */
820         start_trb = &ep_ring->enqueue->generic;
821         start_cycle = ep_ring->cycle_state;
822
823         debug("start_trb %p, start_cycle %d\n", start_trb, start_cycle);
824
825         /* Queue setup TRB - see section 6.4.1.2.1 */
826         /* FIXME better way to translate setup_packet into two u32 fields? */
827         field = 0;
828         field |= TRB_IDT | (TRB_SETUP << TRB_TYPE_SHIFT);
829         if (start_cycle == 0)
830                 field |= 0x1;
831
832         /* xHCI 1.0 6.4.1.2.1: Transfer Type field */
833         if (HC_VERSION(xhci_readl(&ctrl->hccr->cr_capbase)) >= 0x100) {
834                 if (length > 0) {
835                         if (req->requesttype & USB_DIR_IN)
836                                 field |= (TRB_DATA_IN << TRB_TX_TYPE_SHIFT);
837                         else
838                                 field |= (TRB_DATA_OUT << TRB_TX_TYPE_SHIFT);
839                 }
840         }
841
842         debug("req->requesttype = %d, req->request = %d,"
843                 "le16_to_cpu(req->value) = %d,"
844                 "le16_to_cpu(req->index) = %d,"
845                 "le16_to_cpu(req->length) = %d\n",
846                 req->requesttype, req->request, le16_to_cpu(req->value),
847                 le16_to_cpu(req->index), le16_to_cpu(req->length));
848
849         trb_fields[0] = req->requesttype | req->request << 8 |
850                                 le16_to_cpu(req->value) << 16;
851         trb_fields[1] = le16_to_cpu(req->index) |
852                         le16_to_cpu(req->length) << 16;
853         /* TRB_LEN | (TRB_INTR_TARGET) */
854         trb_fields[2] = (8 | ((0 & TRB_INTR_TARGET_MASK) <<
855                         TRB_INTR_TARGET_SHIFT));
856         /* Immediate data in pointer */
857         trb_fields[3] = field;
858         queue_trb(ctrl, ep_ring, true, trb_fields);
859
860         /* Re-initializing field to zero */
861         field = 0;
862         /* If there's data, queue data TRBs */
863         /* Only set interrupt on short packet for IN endpoints */
864         if (usb_pipein(pipe))
865                 field = TRB_ISP | (TRB_DATA << TRB_TYPE_SHIFT);
866         else
867                 field = (TRB_DATA << TRB_TYPE_SHIFT);
868
869         length_field = (length & TRB_LEN_MASK) | xhci_td_remainder(length) |
870                         ((0 & TRB_INTR_TARGET_MASK) << TRB_INTR_TARGET_SHIFT);
871         debug("length_field = %d, length = %d,"
872                 "xhci_td_remainder(length) = %d , TRB_INTR_TARGET(0) = %d\n",
873                 length_field, (length & TRB_LEN_MASK),
874                 xhci_td_remainder(length), 0);
875
876         if (length > 0) {
877                 if (req->requesttype & USB_DIR_IN)
878                         field |= TRB_DIR_IN;
879                 buf_64 = (uintptr_t)buffer;
880
881                 trb_fields[0] = lower_32_bits(buf_64);
882                 trb_fields[1] = upper_32_bits(buf_64);
883                 trb_fields[2] = length_field;
884                 trb_fields[3] = field | ep_ring->cycle_state;
885
886                 xhci_flush_cache((uintptr_t)buffer, length);
887                 queue_trb(ctrl, ep_ring, true, trb_fields);
888         }
889
890         /*
891          * Queue status TRB -
892          * see Table 7 and sections 4.11.2.2 and 6.4.1.2.3
893          */
894
895         /* If the device sent data, the status stage is an OUT transfer */
896         field = 0;
897         if (length > 0 && req->requesttype & USB_DIR_IN)
898                 field = 0;
899         else
900                 field = TRB_DIR_IN;
901
902         trb_fields[0] = 0;
903         trb_fields[1] = 0;
904         trb_fields[2] = ((0 & TRB_INTR_TARGET_MASK) << TRB_INTR_TARGET_SHIFT);
905                 /* Event on completion */
906         trb_fields[3] = field | TRB_IOC |
907                         (TRB_STATUS << TRB_TYPE_SHIFT) |
908                         ep_ring->cycle_state;
909
910         queue_trb(ctrl, ep_ring, false, trb_fields);
911
912         giveback_first_trb(udev, ep_index, start_cycle, start_trb);
913
914         event = xhci_wait_for_event(ctrl, TRB_TRANSFER);
915         if (!event)
916                 goto abort;
917         field = le32_to_cpu(event->trans_event.flags);
918
919         BUG_ON(TRB_TO_SLOT_ID(field) != slot_id);
920         BUG_ON(TRB_TO_EP_INDEX(field) != ep_index);
921
922         record_transfer_result(udev, event, length);
923         xhci_acknowledge_event(ctrl);
924
925         /* Invalidate buffer to make it available to usb-core */
926         if (length > 0)
927                 xhci_inval_cache((uintptr_t)buffer, length);
928
929         if (GET_COMP_CODE(le32_to_cpu(event->trans_event.transfer_len))
930                         == COMP_SHORT_TX) {
931                 /* Short data stage, clear up additional status stage event */
932                 event = xhci_wait_for_event(ctrl, TRB_TRANSFER);
933                 if (!event)
934                         goto abort;
935                 BUG_ON(TRB_TO_SLOT_ID(field) != slot_id);
936                 BUG_ON(TRB_TO_EP_INDEX(field) != ep_index);
937                 xhci_acknowledge_event(ctrl);
938         }
939
940         return (udev->status != USB_ST_NOT_PROC) ? 0 : -1;
941
942 abort:
943         debug("XHCI control transfer timed out, aborting...\n");
944         abort_td(udev, ep_index);
945         udev->status = USB_ST_NAK_REC;
946         udev->act_len = 0;
947         return -ETIMEDOUT;
948 }