GNU Linux-libre 4.9.333-gnu1
[releases.git] / drivers / usb / gadget / udc / dummy_hcd.c
1 /*
2  * dummy_hcd.c -- Dummy/Loopback USB host and device emulator driver.
3  *
4  * Maintainer: Alan Stern <stern@rowland.harvard.edu>
5  *
6  * Copyright (C) 2003 David Brownell
7  * Copyright (C) 2003-2005 Alan Stern
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  */
14
15
16 /*
17  * This exposes a device side "USB gadget" API, driven by requests to a
18  * Linux-USB host controller driver.  USB traffic is simulated; there's
19  * no need for USB hardware.  Use this with two other drivers:
20  *
21  *  - Gadget driver, responding to requests (slave);
22  *  - Host-side device driver, as already familiar in Linux.
23  *
24  * Having this all in one kernel can help some stages of development,
25  * bypassing some hardware (and driver) issues.  UML could help too.
26  */
27
28 #include <linux/module.h>
29 #include <linux/kernel.h>
30 #include <linux/delay.h>
31 #include <linux/ioport.h>
32 #include <linux/slab.h>
33 #include <linux/errno.h>
34 #include <linux/init.h>
35 #include <linux/timer.h>
36 #include <linux/list.h>
37 #include <linux/interrupt.h>
38 #include <linux/platform_device.h>
39 #include <linux/usb.h>
40 #include <linux/usb/gadget.h>
41 #include <linux/usb/hcd.h>
42 #include <linux/scatterlist.h>
43
44 #include <asm/byteorder.h>
45 #include <linux/io.h>
46 #include <asm/irq.h>
47 #include <asm/unaligned.h>
48
49 #define DRIVER_DESC     "USB Host+Gadget Emulator"
50 #define DRIVER_VERSION  "02 May 2005"
51
52 #define POWER_BUDGET    500     /* in mA; use 8 for low-power port testing */
53 #define POWER_BUDGET_3  900     /* in mA */
54
55 static const char       driver_name[] = "dummy_hcd";
56 static const char       driver_desc[] = "USB Host+Gadget Emulator";
57
58 static const char       gadget_name[] = "dummy_udc";
59
60 MODULE_DESCRIPTION(DRIVER_DESC);
61 MODULE_AUTHOR("David Brownell");
62 MODULE_LICENSE("GPL");
63
64 struct dummy_hcd_module_parameters {
65         bool is_super_speed;
66         bool is_high_speed;
67         unsigned int num;
68 };
69
70 static struct dummy_hcd_module_parameters mod_data = {
71         .is_super_speed = false,
72         .is_high_speed = true,
73         .num = 1,
74 };
75 module_param_named(is_super_speed, mod_data.is_super_speed, bool, S_IRUGO);
76 MODULE_PARM_DESC(is_super_speed, "true to simulate SuperSpeed connection");
77 module_param_named(is_high_speed, mod_data.is_high_speed, bool, S_IRUGO);
78 MODULE_PARM_DESC(is_high_speed, "true to simulate HighSpeed connection");
79 module_param_named(num, mod_data.num, uint, S_IRUGO);
80 MODULE_PARM_DESC(num, "number of emulated controllers");
81 /*-------------------------------------------------------------------------*/
82
83 /* gadget side driver data structres */
84 struct dummy_ep {
85         struct list_head                queue;
86         unsigned long                   last_io;        /* jiffies timestamp */
87         struct usb_gadget               *gadget;
88         const struct usb_endpoint_descriptor *desc;
89         struct usb_ep                   ep;
90         unsigned                        halted:1;
91         unsigned                        wedged:1;
92         unsigned                        already_seen:1;
93         unsigned                        setup_stage:1;
94         unsigned                        stream_en:1;
95 };
96
97 struct dummy_request {
98         struct list_head                queue;          /* ep's requests */
99         struct usb_request              req;
100 };
101
102 static inline struct dummy_ep *usb_ep_to_dummy_ep(struct usb_ep *_ep)
103 {
104         return container_of(_ep, struct dummy_ep, ep);
105 }
106
107 static inline struct dummy_request *usb_request_to_dummy_request
108                 (struct usb_request *_req)
109 {
110         return container_of(_req, struct dummy_request, req);
111 }
112
113 /*-------------------------------------------------------------------------*/
114
115 /*
116  * Every device has ep0 for control requests, plus up to 30 more endpoints,
117  * in one of two types:
118  *
119  *   - Configurable:  direction (in/out), type (bulk, iso, etc), and endpoint
120  *     number can be changed.  Names like "ep-a" are used for this type.
121  *
122  *   - Fixed Function:  in other cases.  some characteristics may be mutable;
123  *     that'd be hardware-specific.  Names like "ep12out-bulk" are used.
124  *
125  * Gadget drivers are responsible for not setting up conflicting endpoint
126  * configurations, illegal or unsupported packet lengths, and so on.
127  */
128
129 static const char ep0name[] = "ep0";
130
131 static const struct {
132         const char *name;
133         const struct usb_ep_caps caps;
134 } ep_info[] = {
135 #define EP_INFO(_name, _caps) \
136         { \
137                 .name = _name, \
138                 .caps = _caps, \
139         }
140
141         /* everyone has ep0 */
142         EP_INFO(ep0name,
143                 USB_EP_CAPS(USB_EP_CAPS_TYPE_CONTROL, USB_EP_CAPS_DIR_ALL)),
144         /* act like a pxa250: fifteen fixed function endpoints */
145         EP_INFO("ep1in-bulk",
146                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_IN)),
147         EP_INFO("ep2out-bulk",
148                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_OUT)),
149         EP_INFO("ep3in-iso",
150                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ISO, USB_EP_CAPS_DIR_IN)),
151         EP_INFO("ep4out-iso",
152                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ISO, USB_EP_CAPS_DIR_OUT)),
153         EP_INFO("ep5in-int",
154                 USB_EP_CAPS(USB_EP_CAPS_TYPE_INT, USB_EP_CAPS_DIR_IN)),
155         EP_INFO("ep6in-bulk",
156                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_IN)),
157         EP_INFO("ep7out-bulk",
158                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_OUT)),
159         EP_INFO("ep8in-iso",
160                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ISO, USB_EP_CAPS_DIR_IN)),
161         EP_INFO("ep9out-iso",
162                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ISO, USB_EP_CAPS_DIR_OUT)),
163         EP_INFO("ep10in-int",
164                 USB_EP_CAPS(USB_EP_CAPS_TYPE_INT, USB_EP_CAPS_DIR_IN)),
165         EP_INFO("ep11in-bulk",
166                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_IN)),
167         EP_INFO("ep12out-bulk",
168                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_OUT)),
169         EP_INFO("ep13in-iso",
170                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ISO, USB_EP_CAPS_DIR_IN)),
171         EP_INFO("ep14out-iso",
172                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ISO, USB_EP_CAPS_DIR_OUT)),
173         EP_INFO("ep15in-int",
174                 USB_EP_CAPS(USB_EP_CAPS_TYPE_INT, USB_EP_CAPS_DIR_IN)),
175         /* or like sa1100: two fixed function endpoints */
176         EP_INFO("ep1out-bulk",
177                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_OUT)),
178         EP_INFO("ep2in-bulk",
179                 USB_EP_CAPS(USB_EP_CAPS_TYPE_BULK, USB_EP_CAPS_DIR_IN)),
180         /* and now some generic EPs so we have enough in multi config */
181         EP_INFO("ep3out",
182                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
183         EP_INFO("ep4in",
184                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_IN)),
185         EP_INFO("ep5out",
186                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
187         EP_INFO("ep6out",
188                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
189         EP_INFO("ep7in",
190                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_IN)),
191         EP_INFO("ep8out",
192                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
193         EP_INFO("ep9in",
194                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_IN)),
195         EP_INFO("ep10out",
196                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
197         EP_INFO("ep11out",
198                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
199         EP_INFO("ep12in",
200                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_IN)),
201         EP_INFO("ep13out",
202                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
203         EP_INFO("ep14in",
204                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_IN)),
205         EP_INFO("ep15out",
206                 USB_EP_CAPS(USB_EP_CAPS_TYPE_ALL, USB_EP_CAPS_DIR_OUT)),
207
208 #undef EP_INFO
209 };
210
211 #define DUMMY_ENDPOINTS ARRAY_SIZE(ep_info)
212
213 /*-------------------------------------------------------------------------*/
214
215 #define FIFO_SIZE               64
216
217 struct urbp {
218         struct urb              *urb;
219         struct list_head        urbp_list;
220         struct sg_mapping_iter  miter;
221         u32                     miter_started;
222 };
223
224
225 enum dummy_rh_state {
226         DUMMY_RH_RESET,
227         DUMMY_RH_SUSPENDED,
228         DUMMY_RH_RUNNING
229 };
230
231 struct dummy_hcd {
232         struct dummy                    *dum;
233         enum dummy_rh_state             rh_state;
234         struct timer_list               timer;
235         u32                             port_status;
236         u32                             old_status;
237         unsigned long                   re_timeout;
238
239         struct usb_device               *udev;
240         struct list_head                urbp_list;
241         struct urbp                     *next_frame_urbp;
242
243         u32                             stream_en_ep;
244         u8                              num_stream[30 / 2];
245
246         unsigned                        active:1;
247         unsigned                        old_active:1;
248         unsigned                        resuming:1;
249 };
250
251 struct dummy {
252         spinlock_t                      lock;
253
254         /*
255          * SLAVE/GADGET side support
256          */
257         struct dummy_ep                 ep[DUMMY_ENDPOINTS];
258         int                             address;
259         int                             callback_usage;
260         struct usb_gadget               gadget;
261         struct usb_gadget_driver        *driver;
262         struct dummy_request            fifo_req;
263         u8                              fifo_buf[FIFO_SIZE];
264         u16                             devstatus;
265         unsigned                        ints_enabled:1;
266         unsigned                        udc_suspended:1;
267         unsigned                        pullup:1;
268
269         /*
270          * MASTER/HOST side support
271          */
272         struct dummy_hcd                *hs_hcd;
273         struct dummy_hcd                *ss_hcd;
274 };
275
276 static inline struct dummy_hcd *hcd_to_dummy_hcd(struct usb_hcd *hcd)
277 {
278         return (struct dummy_hcd *) (hcd->hcd_priv);
279 }
280
281 static inline struct usb_hcd *dummy_hcd_to_hcd(struct dummy_hcd *dum)
282 {
283         return container_of((void *) dum, struct usb_hcd, hcd_priv);
284 }
285
286 static inline struct device *dummy_dev(struct dummy_hcd *dum)
287 {
288         return dummy_hcd_to_hcd(dum)->self.controller;
289 }
290
291 static inline struct device *udc_dev(struct dummy *dum)
292 {
293         return dum->gadget.dev.parent;
294 }
295
296 static inline struct dummy *ep_to_dummy(struct dummy_ep *ep)
297 {
298         return container_of(ep->gadget, struct dummy, gadget);
299 }
300
301 static inline struct dummy_hcd *gadget_to_dummy_hcd(struct usb_gadget *gadget)
302 {
303         struct dummy *dum = container_of(gadget, struct dummy, gadget);
304         if (dum->gadget.speed == USB_SPEED_SUPER)
305                 return dum->ss_hcd;
306         else
307                 return dum->hs_hcd;
308 }
309
310 static inline struct dummy *gadget_dev_to_dummy(struct device *dev)
311 {
312         return container_of(dev, struct dummy, gadget.dev);
313 }
314
315 /*-------------------------------------------------------------------------*/
316
317 /* SLAVE/GADGET SIDE UTILITY ROUTINES */
318
319 /* called with spinlock held */
320 static void nuke(struct dummy *dum, struct dummy_ep *ep)
321 {
322         while (!list_empty(&ep->queue)) {
323                 struct dummy_request    *req;
324
325                 req = list_entry(ep->queue.next, struct dummy_request, queue);
326                 list_del_init(&req->queue);
327                 req->req.status = -ESHUTDOWN;
328
329                 spin_unlock(&dum->lock);
330                 usb_gadget_giveback_request(&ep->ep, &req->req);
331                 spin_lock(&dum->lock);
332         }
333 }
334
335 /* caller must hold lock */
336 static void stop_activity(struct dummy *dum)
337 {
338         int i;
339
340         /* prevent any more requests */
341         dum->address = 0;
342
343         /* The timer is left running so that outstanding URBs can fail */
344
345         /* nuke any pending requests first, so driver i/o is quiesced */
346         for (i = 0; i < DUMMY_ENDPOINTS; ++i)
347                 nuke(dum, &dum->ep[i]);
348
349         /* driver now does any non-usb quiescing necessary */
350 }
351
352 /**
353  * set_link_state_by_speed() - Sets the current state of the link according to
354  *      the hcd speed
355  * @dum_hcd: pointer to the dummy_hcd structure to update the link state for
356  *
357  * This function updates the port_status according to the link state and the
358  * speed of the hcd.
359  */
360 static void set_link_state_by_speed(struct dummy_hcd *dum_hcd)
361 {
362         struct dummy *dum = dum_hcd->dum;
363
364         if (dummy_hcd_to_hcd(dum_hcd)->speed == HCD_USB3) {
365                 if ((dum_hcd->port_status & USB_SS_PORT_STAT_POWER) == 0) {
366                         dum_hcd->port_status = 0;
367                 } else if (!dum->pullup || dum->udc_suspended) {
368                         /* UDC suspend must cause a disconnect */
369                         dum_hcd->port_status &= ~(USB_PORT_STAT_CONNECTION |
370                                                 USB_PORT_STAT_ENABLE);
371                         if ((dum_hcd->old_status &
372                              USB_PORT_STAT_CONNECTION) != 0)
373                                 dum_hcd->port_status |=
374                                         (USB_PORT_STAT_C_CONNECTION << 16);
375                 } else {
376                         /* device is connected and not suspended */
377                         dum_hcd->port_status |= (USB_PORT_STAT_CONNECTION |
378                                                  USB_PORT_STAT_SPEED_5GBPS) ;
379                         if ((dum_hcd->old_status &
380                              USB_PORT_STAT_CONNECTION) == 0)
381                                 dum_hcd->port_status |=
382                                         (USB_PORT_STAT_C_CONNECTION << 16);
383                         if ((dum_hcd->port_status & USB_PORT_STAT_ENABLE) &&
384                             (dum_hcd->port_status &
385                              USB_PORT_STAT_LINK_STATE) == USB_SS_PORT_LS_U0 &&
386                             dum_hcd->rh_state != DUMMY_RH_SUSPENDED)
387                                 dum_hcd->active = 1;
388                 }
389         } else {
390                 if ((dum_hcd->port_status & USB_PORT_STAT_POWER) == 0) {
391                         dum_hcd->port_status = 0;
392                 } else if (!dum->pullup || dum->udc_suspended) {
393                         /* UDC suspend must cause a disconnect */
394                         dum_hcd->port_status &= ~(USB_PORT_STAT_CONNECTION |
395                                                 USB_PORT_STAT_ENABLE |
396                                                 USB_PORT_STAT_LOW_SPEED |
397                                                 USB_PORT_STAT_HIGH_SPEED |
398                                                 USB_PORT_STAT_SUSPEND);
399                         if ((dum_hcd->old_status &
400                              USB_PORT_STAT_CONNECTION) != 0)
401                                 dum_hcd->port_status |=
402                                         (USB_PORT_STAT_C_CONNECTION << 16);
403                 } else {
404                         dum_hcd->port_status |= USB_PORT_STAT_CONNECTION;
405                         if ((dum_hcd->old_status &
406                              USB_PORT_STAT_CONNECTION) == 0)
407                                 dum_hcd->port_status |=
408                                         (USB_PORT_STAT_C_CONNECTION << 16);
409                         if ((dum_hcd->port_status & USB_PORT_STAT_ENABLE) == 0)
410                                 dum_hcd->port_status &= ~USB_PORT_STAT_SUSPEND;
411                         else if ((dum_hcd->port_status &
412                                   USB_PORT_STAT_SUSPEND) == 0 &&
413                                         dum_hcd->rh_state != DUMMY_RH_SUSPENDED)
414                                 dum_hcd->active = 1;
415                 }
416         }
417 }
418
419 /* caller must hold lock */
420 static void set_link_state(struct dummy_hcd *dum_hcd)
421 {
422         struct dummy *dum = dum_hcd->dum;
423         unsigned int power_bit;
424
425         dum_hcd->active = 0;
426         if (dum->pullup)
427                 if ((dummy_hcd_to_hcd(dum_hcd)->speed == HCD_USB3 &&
428                      dum->gadget.speed != USB_SPEED_SUPER) ||
429                     (dummy_hcd_to_hcd(dum_hcd)->speed != HCD_USB3 &&
430                      dum->gadget.speed == USB_SPEED_SUPER))
431                         return;
432
433         set_link_state_by_speed(dum_hcd);
434         power_bit = (dummy_hcd_to_hcd(dum_hcd)->speed == HCD_USB3 ?
435                         USB_SS_PORT_STAT_POWER : USB_PORT_STAT_POWER);
436
437         if ((dum_hcd->port_status & USB_PORT_STAT_ENABLE) == 0 ||
438              dum_hcd->active)
439                 dum_hcd->resuming = 0;
440
441         /* Currently !connected or in reset */
442         if ((dum_hcd->port_status & power_bit) == 0 ||
443                         (dum_hcd->port_status & USB_PORT_STAT_RESET) != 0) {
444                 unsigned int disconnect = power_bit &
445                                 dum_hcd->old_status & (~dum_hcd->port_status);
446                 unsigned int reset = USB_PORT_STAT_RESET &
447                                 (~dum_hcd->old_status) & dum_hcd->port_status;
448
449                 /* Report reset and disconnect events to the driver */
450                 if (dum->ints_enabled && (disconnect || reset)) {
451                         stop_activity(dum);
452                         ++dum->callback_usage;
453                         spin_unlock(&dum->lock);
454                         if (reset)
455                                 usb_gadget_udc_reset(&dum->gadget, dum->driver);
456                         else
457                                 dum->driver->disconnect(&dum->gadget);
458                         spin_lock(&dum->lock);
459                         --dum->callback_usage;
460                 }
461         } else if (dum_hcd->active != dum_hcd->old_active &&
462                         dum->ints_enabled) {
463                 ++dum->callback_usage;
464                 spin_unlock(&dum->lock);
465                 if (dum_hcd->old_active && dum->driver->suspend)
466                         dum->driver->suspend(&dum->gadget);
467                 else if (!dum_hcd->old_active &&  dum->driver->resume)
468                         dum->driver->resume(&dum->gadget);
469                 spin_lock(&dum->lock);
470                 --dum->callback_usage;
471         }
472
473         dum_hcd->old_status = dum_hcd->port_status;
474         dum_hcd->old_active = dum_hcd->active;
475 }
476
477 /*-------------------------------------------------------------------------*/
478
479 /* SLAVE/GADGET SIDE DRIVER
480  *
481  * This only tracks gadget state.  All the work is done when the host
482  * side tries some (emulated) i/o operation.  Real device controller
483  * drivers would do real i/o using dma, fifos, irqs, timers, etc.
484  */
485
486 #define is_enabled(dum) \
487         (dum->port_status & USB_PORT_STAT_ENABLE)
488
489 static int dummy_enable(struct usb_ep *_ep,
490                 const struct usb_endpoint_descriptor *desc)
491 {
492         struct dummy            *dum;
493         struct dummy_hcd        *dum_hcd;
494         struct dummy_ep         *ep;
495         unsigned                max;
496         int                     retval;
497
498         ep = usb_ep_to_dummy_ep(_ep);
499         if (!_ep || !desc || ep->desc || _ep->name == ep0name
500                         || desc->bDescriptorType != USB_DT_ENDPOINT)
501                 return -EINVAL;
502         dum = ep_to_dummy(ep);
503         if (!dum->driver)
504                 return -ESHUTDOWN;
505
506         dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
507         if (!is_enabled(dum_hcd))
508                 return -ESHUTDOWN;
509
510         /*
511          * For HS/FS devices only bits 0..10 of the wMaxPacketSize represent the
512          * maximum packet size.
513          * For SS devices the wMaxPacketSize is limited by 1024.
514          */
515         max = usb_endpoint_maxp(desc) & 0x7ff;
516
517         /* drivers must not request bad settings, since lower levels
518          * (hardware or its drivers) may not check.  some endpoints
519          * can't do iso, many have maxpacket limitations, etc.
520          *
521          * since this "hardware" driver is here to help debugging, we
522          * have some extra sanity checks.  (there could be more though,
523          * especially for "ep9out" style fixed function ones.)
524          */
525         retval = -EINVAL;
526         switch (usb_endpoint_type(desc)) {
527         case USB_ENDPOINT_XFER_BULK:
528                 if (strstr(ep->ep.name, "-iso")
529                                 || strstr(ep->ep.name, "-int")) {
530                         goto done;
531                 }
532                 switch (dum->gadget.speed) {
533                 case USB_SPEED_SUPER:
534                         if (max == 1024)
535                                 break;
536                         goto done;
537                 case USB_SPEED_HIGH:
538                         if (max == 512)
539                                 break;
540                         goto done;
541                 case USB_SPEED_FULL:
542                         if (max == 8 || max == 16 || max == 32 || max == 64)
543                                 /* we'll fake any legal size */
544                                 break;
545                         /* save a return statement */
546                 default:
547                         goto done;
548                 }
549                 break;
550         case USB_ENDPOINT_XFER_INT:
551                 if (strstr(ep->ep.name, "-iso")) /* bulk is ok */
552                         goto done;
553                 /* real hardware might not handle all packet sizes */
554                 switch (dum->gadget.speed) {
555                 case USB_SPEED_SUPER:
556                 case USB_SPEED_HIGH:
557                         if (max <= 1024)
558                                 break;
559                         /* save a return statement */
560                 case USB_SPEED_FULL:
561                         if (max <= 64)
562                                 break;
563                         /* save a return statement */
564                 default:
565                         if (max <= 8)
566                                 break;
567                         goto done;
568                 }
569                 break;
570         case USB_ENDPOINT_XFER_ISOC:
571                 if (strstr(ep->ep.name, "-bulk")
572                                 || strstr(ep->ep.name, "-int"))
573                         goto done;
574                 /* real hardware might not handle all packet sizes */
575                 switch (dum->gadget.speed) {
576                 case USB_SPEED_SUPER:
577                 case USB_SPEED_HIGH:
578                         if (max <= 1024)
579                                 break;
580                         /* save a return statement */
581                 case USB_SPEED_FULL:
582                         if (max <= 1023)
583                                 break;
584                         /* save a return statement */
585                 default:
586                         goto done;
587                 }
588                 break;
589         default:
590                 /* few chips support control except on ep0 */
591                 goto done;
592         }
593
594         _ep->maxpacket = max;
595         if (usb_ss_max_streams(_ep->comp_desc)) {
596                 if (!usb_endpoint_xfer_bulk(desc)) {
597                         dev_err(udc_dev(dum), "Can't enable stream support on "
598                                         "non-bulk ep %s\n", _ep->name);
599                         return -EINVAL;
600                 }
601                 ep->stream_en = 1;
602         }
603         ep->desc = desc;
604
605         dev_dbg(udc_dev(dum), "enabled %s (ep%d%s-%s) maxpacket %d stream %s\n",
606                 _ep->name,
607                 desc->bEndpointAddress & 0x0f,
608                 (desc->bEndpointAddress & USB_DIR_IN) ? "in" : "out",
609                 ({ char *val;
610                  switch (usb_endpoint_type(desc)) {
611                  case USB_ENDPOINT_XFER_BULK:
612                          val = "bulk";
613                          break;
614                  case USB_ENDPOINT_XFER_ISOC:
615                          val = "iso";
616                          break;
617                  case USB_ENDPOINT_XFER_INT:
618                          val = "intr";
619                          break;
620                  default:
621                          val = "ctrl";
622                          break;
623                  } val; }),
624                 max, ep->stream_en ? "enabled" : "disabled");
625
626         /* at this point real hardware should be NAKing transfers
627          * to that endpoint, until a buffer is queued to it.
628          */
629         ep->halted = ep->wedged = 0;
630         retval = 0;
631 done:
632         return retval;
633 }
634
635 static int dummy_disable(struct usb_ep *_ep)
636 {
637         struct dummy_ep         *ep;
638         struct dummy            *dum;
639         unsigned long           flags;
640
641         ep = usb_ep_to_dummy_ep(_ep);
642         if (!_ep || !ep->desc || _ep->name == ep0name)
643                 return -EINVAL;
644         dum = ep_to_dummy(ep);
645
646         spin_lock_irqsave(&dum->lock, flags);
647         ep->desc = NULL;
648         ep->stream_en = 0;
649         nuke(dum, ep);
650         spin_unlock_irqrestore(&dum->lock, flags);
651
652         dev_dbg(udc_dev(dum), "disabled %s\n", _ep->name);
653         return 0;
654 }
655
656 static struct usb_request *dummy_alloc_request(struct usb_ep *_ep,
657                 gfp_t mem_flags)
658 {
659         struct dummy_request    *req;
660
661         if (!_ep)
662                 return NULL;
663
664         req = kzalloc(sizeof(*req), mem_flags);
665         if (!req)
666                 return NULL;
667         INIT_LIST_HEAD(&req->queue);
668         return &req->req;
669 }
670
671 static void dummy_free_request(struct usb_ep *_ep, struct usb_request *_req)
672 {
673         struct dummy_request    *req;
674
675         if (!_ep || !_req) {
676                 WARN_ON(1);
677                 return;
678         }
679
680         req = usb_request_to_dummy_request(_req);
681         WARN_ON(!list_empty(&req->queue));
682         kfree(req);
683 }
684
685 static void fifo_complete(struct usb_ep *ep, struct usb_request *req)
686 {
687 }
688
689 static int dummy_queue(struct usb_ep *_ep, struct usb_request *_req,
690                 gfp_t mem_flags)
691 {
692         struct dummy_ep         *ep;
693         struct dummy_request    *req;
694         struct dummy            *dum;
695         struct dummy_hcd        *dum_hcd;
696         unsigned long           flags;
697
698         req = usb_request_to_dummy_request(_req);
699         if (!_req || !list_empty(&req->queue) || !_req->complete)
700                 return -EINVAL;
701
702         ep = usb_ep_to_dummy_ep(_ep);
703         if (!_ep || (!ep->desc && _ep->name != ep0name))
704                 return -EINVAL;
705
706         dum = ep_to_dummy(ep);
707         dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
708         if (!dum->driver || !is_enabled(dum_hcd))
709                 return -ESHUTDOWN;
710
711 #if 0
712         dev_dbg(udc_dev(dum), "ep %p queue req %p to %s, len %d buf %p\n",
713                         ep, _req, _ep->name, _req->length, _req->buf);
714 #endif
715         _req->status = -EINPROGRESS;
716         _req->actual = 0;
717         spin_lock_irqsave(&dum->lock, flags);
718
719         /* implement an emulated single-request FIFO */
720         if (ep->desc && (ep->desc->bEndpointAddress & USB_DIR_IN) &&
721                         list_empty(&dum->fifo_req.queue) &&
722                         list_empty(&ep->queue) &&
723                         _req->length <= FIFO_SIZE) {
724                 req = &dum->fifo_req;
725                 req->req = *_req;
726                 req->req.buf = dum->fifo_buf;
727                 memcpy(dum->fifo_buf, _req->buf, _req->length);
728                 req->req.context = dum;
729                 req->req.complete = fifo_complete;
730
731                 list_add_tail(&req->queue, &ep->queue);
732                 spin_unlock(&dum->lock);
733                 _req->actual = _req->length;
734                 _req->status = 0;
735                 usb_gadget_giveback_request(_ep, _req);
736                 spin_lock(&dum->lock);
737         }  else
738                 list_add_tail(&req->queue, &ep->queue);
739         spin_unlock_irqrestore(&dum->lock, flags);
740
741         /* real hardware would likely enable transfers here, in case
742          * it'd been left NAKing.
743          */
744         return 0;
745 }
746
747 static int dummy_dequeue(struct usb_ep *_ep, struct usb_request *_req)
748 {
749         struct dummy_ep         *ep;
750         struct dummy            *dum;
751         int                     retval = -EINVAL;
752         unsigned long           flags;
753         struct dummy_request    *req = NULL;
754
755         if (!_ep || !_req)
756                 return retval;
757         ep = usb_ep_to_dummy_ep(_ep);
758         dum = ep_to_dummy(ep);
759
760         if (!dum->driver)
761                 return -ESHUTDOWN;
762
763         local_irq_save(flags);
764         spin_lock(&dum->lock);
765         list_for_each_entry(req, &ep->queue, queue) {
766                 if (&req->req == _req) {
767                         list_del_init(&req->queue);
768                         _req->status = -ECONNRESET;
769                         retval = 0;
770                         break;
771                 }
772         }
773         spin_unlock(&dum->lock);
774
775         if (retval == 0) {
776                 dev_dbg(udc_dev(dum),
777                                 "dequeued req %p from %s, len %d buf %p\n",
778                                 req, _ep->name, _req->length, _req->buf);
779                 usb_gadget_giveback_request(_ep, _req);
780         }
781         local_irq_restore(flags);
782         return retval;
783 }
784
785 static int
786 dummy_set_halt_and_wedge(struct usb_ep *_ep, int value, int wedged)
787 {
788         struct dummy_ep         *ep;
789         struct dummy            *dum;
790
791         if (!_ep)
792                 return -EINVAL;
793         ep = usb_ep_to_dummy_ep(_ep);
794         dum = ep_to_dummy(ep);
795         if (!dum->driver)
796                 return -ESHUTDOWN;
797         if (!value)
798                 ep->halted = ep->wedged = 0;
799         else if (ep->desc && (ep->desc->bEndpointAddress & USB_DIR_IN) &&
800                         !list_empty(&ep->queue))
801                 return -EAGAIN;
802         else {
803                 ep->halted = 1;
804                 if (wedged)
805                         ep->wedged = 1;
806         }
807         /* FIXME clear emulated data toggle too */
808         return 0;
809 }
810
811 static int
812 dummy_set_halt(struct usb_ep *_ep, int value)
813 {
814         return dummy_set_halt_and_wedge(_ep, value, 0);
815 }
816
817 static int dummy_set_wedge(struct usb_ep *_ep)
818 {
819         if (!_ep || _ep->name == ep0name)
820                 return -EINVAL;
821         return dummy_set_halt_and_wedge(_ep, 1, 1);
822 }
823
824 static const struct usb_ep_ops dummy_ep_ops = {
825         .enable         = dummy_enable,
826         .disable        = dummy_disable,
827
828         .alloc_request  = dummy_alloc_request,
829         .free_request   = dummy_free_request,
830
831         .queue          = dummy_queue,
832         .dequeue        = dummy_dequeue,
833
834         .set_halt       = dummy_set_halt,
835         .set_wedge      = dummy_set_wedge,
836 };
837
838 /*-------------------------------------------------------------------------*/
839
840 /* there are both host and device side versions of this call ... */
841 static int dummy_g_get_frame(struct usb_gadget *_gadget)
842 {
843         struct timespec64 ts64;
844
845         ktime_get_ts64(&ts64);
846         return ts64.tv_nsec / NSEC_PER_MSEC;
847 }
848
849 static int dummy_wakeup(struct usb_gadget *_gadget)
850 {
851         struct dummy_hcd *dum_hcd;
852
853         dum_hcd = gadget_to_dummy_hcd(_gadget);
854         if (!(dum_hcd->dum->devstatus & ((1 << USB_DEVICE_B_HNP_ENABLE)
855                                 | (1 << USB_DEVICE_REMOTE_WAKEUP))))
856                 return -EINVAL;
857         if ((dum_hcd->port_status & USB_PORT_STAT_CONNECTION) == 0)
858                 return -ENOLINK;
859         if ((dum_hcd->port_status & USB_PORT_STAT_SUSPEND) == 0 &&
860                          dum_hcd->rh_state != DUMMY_RH_SUSPENDED)
861                 return -EIO;
862
863         /* FIXME: What if the root hub is suspended but the port isn't? */
864
865         /* hub notices our request, issues downstream resume, etc */
866         dum_hcd->resuming = 1;
867         dum_hcd->re_timeout = jiffies + msecs_to_jiffies(20);
868         mod_timer(&dummy_hcd_to_hcd(dum_hcd)->rh_timer, dum_hcd->re_timeout);
869         return 0;
870 }
871
872 static int dummy_set_selfpowered(struct usb_gadget *_gadget, int value)
873 {
874         struct dummy    *dum;
875
876         _gadget->is_selfpowered = (value != 0);
877         dum = gadget_to_dummy_hcd(_gadget)->dum;
878         if (value)
879                 dum->devstatus |= (1 << USB_DEVICE_SELF_POWERED);
880         else
881                 dum->devstatus &= ~(1 << USB_DEVICE_SELF_POWERED);
882         return 0;
883 }
884
885 static void dummy_udc_update_ep0(struct dummy *dum)
886 {
887         if (dum->gadget.speed == USB_SPEED_SUPER)
888                 dum->ep[0].ep.maxpacket = 9;
889         else
890                 dum->ep[0].ep.maxpacket = 64;
891 }
892
893 static int dummy_pullup(struct usb_gadget *_gadget, int value)
894 {
895         struct dummy_hcd *dum_hcd;
896         struct dummy    *dum;
897         unsigned long   flags;
898
899         dum = gadget_dev_to_dummy(&_gadget->dev);
900
901         if (value && dum->driver) {
902                 if (mod_data.is_super_speed)
903                         dum->gadget.speed = dum->driver->max_speed;
904                 else if (mod_data.is_high_speed)
905                         dum->gadget.speed = min_t(u8, USB_SPEED_HIGH,
906                                         dum->driver->max_speed);
907                 else
908                         dum->gadget.speed = USB_SPEED_FULL;
909                 dummy_udc_update_ep0(dum);
910
911                 if (dum->gadget.speed < dum->driver->max_speed)
912                         dev_dbg(udc_dev(dum), "This device can perform faster"
913                                 " if you connect it to a %s port...\n",
914                                 usb_speed_string(dum->driver->max_speed));
915         }
916         dum_hcd = gadget_to_dummy_hcd(_gadget);
917
918         spin_lock_irqsave(&dum->lock, flags);
919         dum->pullup = (value != 0);
920         set_link_state(dum_hcd);
921         if (value == 0) {
922                 /*
923                  * Emulate synchronize_irq(): wait for callbacks to finish.
924                  * This seems to be the best place to emulate the call to
925                  * synchronize_irq() that's in usb_gadget_remove_driver().
926                  * Doing it in dummy_udc_stop() would be too late since it
927                  * is called after the unbind callback and unbind shouldn't
928                  * be invoked until all the other callbacks are finished.
929                  */
930                 while (dum->callback_usage > 0) {
931                         spin_unlock_irqrestore(&dum->lock, flags);
932                         usleep_range(1000, 2000);
933                         spin_lock_irqsave(&dum->lock, flags);
934                 }
935         }
936         spin_unlock_irqrestore(&dum->lock, flags);
937
938         usb_hcd_poll_rh_status(dummy_hcd_to_hcd(dum_hcd));
939         return 0;
940 }
941
942 static int dummy_udc_start(struct usb_gadget *g,
943                 struct usb_gadget_driver *driver);
944 static int dummy_udc_stop(struct usb_gadget *g);
945
946 static const struct usb_gadget_ops dummy_ops = {
947         .get_frame      = dummy_g_get_frame,
948         .wakeup         = dummy_wakeup,
949         .set_selfpowered = dummy_set_selfpowered,
950         .pullup         = dummy_pullup,
951         .udc_start      = dummy_udc_start,
952         .udc_stop       = dummy_udc_stop,
953 };
954
955 /*-------------------------------------------------------------------------*/
956
957 /* "function" sysfs attribute */
958 static ssize_t function_show(struct device *dev, struct device_attribute *attr,
959                 char *buf)
960 {
961         struct dummy    *dum = gadget_dev_to_dummy(dev);
962
963         if (!dum->driver || !dum->driver->function)
964                 return 0;
965         return scnprintf(buf, PAGE_SIZE, "%s\n", dum->driver->function);
966 }
967 static DEVICE_ATTR_RO(function);
968
969 /*-------------------------------------------------------------------------*/
970
971 /*
972  * Driver registration/unregistration.
973  *
974  * This is basically hardware-specific; there's usually only one real USB
975  * device (not host) controller since that's how USB devices are intended
976  * to work.  So most implementations of these api calls will rely on the
977  * fact that only one driver will ever bind to the hardware.  But curious
978  * hardware can be built with discrete components, so the gadget API doesn't
979  * require that assumption.
980  *
981  * For this emulator, it might be convenient to create a usb slave device
982  * for each driver that registers:  just add to a big root hub.
983  */
984
985 static int dummy_udc_start(struct usb_gadget *g,
986                 struct usb_gadget_driver *driver)
987 {
988         struct dummy_hcd        *dum_hcd = gadget_to_dummy_hcd(g);
989         struct dummy            *dum = dum_hcd->dum;
990
991         if (driver->max_speed == USB_SPEED_UNKNOWN)
992                 return -EINVAL;
993
994         /*
995          * SLAVE side init ... the layer above hardware, which
996          * can't enumerate without help from the driver we're binding.
997          */
998
999         spin_lock_irq(&dum->lock);
1000         dum->devstatus = 0;
1001         dum->driver = driver;
1002         dum->ints_enabled = 1;
1003         spin_unlock_irq(&dum->lock);
1004
1005         return 0;
1006 }
1007
1008 static int dummy_udc_stop(struct usb_gadget *g)
1009 {
1010         struct dummy_hcd        *dum_hcd = gadget_to_dummy_hcd(g);
1011         struct dummy            *dum = dum_hcd->dum;
1012
1013         spin_lock_irq(&dum->lock);
1014         dum->ints_enabled = 0;
1015         stop_activity(dum);
1016         dum->driver = NULL;
1017         spin_unlock_irq(&dum->lock);
1018
1019         return 0;
1020 }
1021
1022 #undef is_enabled
1023
1024 /* The gadget structure is stored inside the hcd structure and will be
1025  * released along with it. */
1026 static void init_dummy_udc_hw(struct dummy *dum)
1027 {
1028         int i;
1029
1030         INIT_LIST_HEAD(&dum->gadget.ep_list);
1031         for (i = 0; i < DUMMY_ENDPOINTS; i++) {
1032                 struct dummy_ep *ep = &dum->ep[i];
1033
1034                 if (!ep_info[i].name)
1035                         break;
1036                 ep->ep.name = ep_info[i].name;
1037                 ep->ep.caps = ep_info[i].caps;
1038                 ep->ep.ops = &dummy_ep_ops;
1039                 list_add_tail(&ep->ep.ep_list, &dum->gadget.ep_list);
1040                 ep->halted = ep->wedged = ep->already_seen =
1041                                 ep->setup_stage = 0;
1042                 usb_ep_set_maxpacket_limit(&ep->ep, ~0);
1043                 ep->ep.max_streams = 16;
1044                 ep->last_io = jiffies;
1045                 ep->gadget = &dum->gadget;
1046                 ep->desc = NULL;
1047                 INIT_LIST_HEAD(&ep->queue);
1048         }
1049
1050         dum->gadget.ep0 = &dum->ep[0].ep;
1051         list_del_init(&dum->ep[0].ep.ep_list);
1052         INIT_LIST_HEAD(&dum->fifo_req.queue);
1053
1054 #ifdef CONFIG_USB_OTG
1055         dum->gadget.is_otg = 1;
1056 #endif
1057 }
1058
1059 static int dummy_udc_probe(struct platform_device *pdev)
1060 {
1061         struct dummy    *dum;
1062         int             rc;
1063
1064         dum = *((void **)dev_get_platdata(&pdev->dev));
1065         /* Clear usb_gadget region for new registration to udc-core */
1066         memzero_explicit(&dum->gadget, sizeof(struct usb_gadget));
1067         dum->gadget.name = gadget_name;
1068         dum->gadget.ops = &dummy_ops;
1069         if (mod_data.is_super_speed)
1070                 dum->gadget.max_speed = USB_SPEED_SUPER;
1071         else if (mod_data.is_high_speed)
1072                 dum->gadget.max_speed = USB_SPEED_HIGH;
1073         else
1074                 dum->gadget.max_speed = USB_SPEED_FULL;
1075
1076         dum->gadget.dev.parent = &pdev->dev;
1077         init_dummy_udc_hw(dum);
1078
1079         rc = usb_add_gadget_udc(&pdev->dev, &dum->gadget);
1080         if (rc < 0)
1081                 goto err_udc;
1082
1083         rc = device_create_file(&dum->gadget.dev, &dev_attr_function);
1084         if (rc < 0)
1085                 goto err_dev;
1086         platform_set_drvdata(pdev, dum);
1087         return rc;
1088
1089 err_dev:
1090         usb_del_gadget_udc(&dum->gadget);
1091 err_udc:
1092         return rc;
1093 }
1094
1095 static int dummy_udc_remove(struct platform_device *pdev)
1096 {
1097         struct dummy    *dum = platform_get_drvdata(pdev);
1098
1099         device_remove_file(&dum->gadget.dev, &dev_attr_function);
1100         usb_del_gadget_udc(&dum->gadget);
1101         return 0;
1102 }
1103
1104 static void dummy_udc_pm(struct dummy *dum, struct dummy_hcd *dum_hcd,
1105                 int suspend)
1106 {
1107         spin_lock_irq(&dum->lock);
1108         dum->udc_suspended = suspend;
1109         set_link_state(dum_hcd);
1110         spin_unlock_irq(&dum->lock);
1111 }
1112
1113 static int dummy_udc_suspend(struct platform_device *pdev, pm_message_t state)
1114 {
1115         struct dummy            *dum = platform_get_drvdata(pdev);
1116         struct dummy_hcd        *dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
1117
1118         dev_dbg(&pdev->dev, "%s\n", __func__);
1119         dummy_udc_pm(dum, dum_hcd, 1);
1120         usb_hcd_poll_rh_status(dummy_hcd_to_hcd(dum_hcd));
1121         return 0;
1122 }
1123
1124 static int dummy_udc_resume(struct platform_device *pdev)
1125 {
1126         struct dummy            *dum = platform_get_drvdata(pdev);
1127         struct dummy_hcd        *dum_hcd = gadget_to_dummy_hcd(&dum->gadget);
1128
1129         dev_dbg(&pdev->dev, "%s\n", __func__);
1130         dummy_udc_pm(dum, dum_hcd, 0);
1131         usb_hcd_poll_rh_status(dummy_hcd_to_hcd(dum_hcd));
1132         return 0;
1133 }
1134
1135 static struct platform_driver dummy_udc_driver = {
1136         .probe          = dummy_udc_probe,
1137         .remove         = dummy_udc_remove,
1138         .suspend        = dummy_udc_suspend,
1139         .resume         = dummy_udc_resume,
1140         .driver         = {
1141                 .name   = (char *) gadget_name,
1142         },
1143 };
1144
1145 /*-------------------------------------------------------------------------*/
1146
1147 static unsigned int dummy_get_ep_idx(const struct usb_endpoint_descriptor *desc)
1148 {
1149         unsigned int index;
1150
1151         index = usb_endpoint_num(desc) << 1;
1152         if (usb_endpoint_dir_in(desc))
1153                 index |= 1;
1154         return index;
1155 }
1156
1157 /* MASTER/HOST SIDE DRIVER
1158  *
1159  * this uses the hcd framework to hook up to host side drivers.
1160  * its root hub will only have one device, otherwise it acts like
1161  * a normal host controller.
1162  *
1163  * when urbs are queued, they're just stuck on a list that we
1164  * scan in a timer callback.  that callback connects writes from
1165  * the host with reads from the device, and so on, based on the
1166  * usb 2.0 rules.
1167  */
1168
1169 static int dummy_ep_stream_en(struct dummy_hcd *dum_hcd, struct urb *urb)
1170 {
1171         const struct usb_endpoint_descriptor *desc = &urb->ep->desc;
1172         u32 index;
1173
1174         if (!usb_endpoint_xfer_bulk(desc))
1175                 return 0;
1176
1177         index = dummy_get_ep_idx(desc);
1178         return (1 << index) & dum_hcd->stream_en_ep;
1179 }
1180
1181 /*
1182  * The max stream number is saved as a nibble so for the 30 possible endpoints
1183  * we only 15 bytes of memory. Therefore we are limited to max 16 streams (0
1184  * means we use only 1 stream). The maximum according to the spec is 16bit so
1185  * if the 16 stream limit is about to go, the array size should be incremented
1186  * to 30 elements of type u16.
1187  */
1188 static int get_max_streams_for_pipe(struct dummy_hcd *dum_hcd,
1189                 unsigned int pipe)
1190 {
1191         int max_streams;
1192
1193         max_streams = dum_hcd->num_stream[usb_pipeendpoint(pipe)];
1194         if (usb_pipeout(pipe))
1195                 max_streams >>= 4;
1196         else
1197                 max_streams &= 0xf;
1198         max_streams++;
1199         return max_streams;
1200 }
1201
1202 static void set_max_streams_for_pipe(struct dummy_hcd *dum_hcd,
1203                 unsigned int pipe, unsigned int streams)
1204 {
1205         int max_streams;
1206
1207         streams--;
1208         max_streams = dum_hcd->num_stream[usb_pipeendpoint(pipe)];
1209         if (usb_pipeout(pipe)) {
1210                 streams <<= 4;
1211                 max_streams &= 0xf;
1212         } else {
1213                 max_streams &= 0xf0;
1214         }
1215         max_streams |= streams;
1216         dum_hcd->num_stream[usb_pipeendpoint(pipe)] = max_streams;
1217 }
1218
1219 static int dummy_validate_stream(struct dummy_hcd *dum_hcd, struct urb *urb)
1220 {
1221         unsigned int max_streams;
1222         int enabled;
1223
1224         enabled = dummy_ep_stream_en(dum_hcd, urb);
1225         if (!urb->stream_id) {
1226                 if (enabled)
1227                         return -EINVAL;
1228                 return 0;
1229         }
1230         if (!enabled)
1231                 return -EINVAL;
1232
1233         max_streams = get_max_streams_for_pipe(dum_hcd,
1234                         usb_pipeendpoint(urb->pipe));
1235         if (urb->stream_id > max_streams) {
1236                 dev_err(dummy_dev(dum_hcd), "Stream id %d is out of range.\n",
1237                                 urb->stream_id);
1238                 BUG();
1239                 return -EINVAL;
1240         }
1241         return 0;
1242 }
1243
1244 static int dummy_urb_enqueue(
1245         struct usb_hcd                  *hcd,
1246         struct urb                      *urb,
1247         gfp_t                           mem_flags
1248 ) {
1249         struct dummy_hcd *dum_hcd;
1250         struct urbp     *urbp;
1251         unsigned long   flags;
1252         int             rc;
1253
1254         urbp = kmalloc(sizeof *urbp, mem_flags);
1255         if (!urbp)
1256                 return -ENOMEM;
1257         urbp->urb = urb;
1258         urbp->miter_started = 0;
1259
1260         dum_hcd = hcd_to_dummy_hcd(hcd);
1261         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
1262
1263         rc = dummy_validate_stream(dum_hcd, urb);
1264         if (rc) {
1265                 kfree(urbp);
1266                 goto done;
1267         }
1268
1269         rc = usb_hcd_link_urb_to_ep(hcd, urb);
1270         if (rc) {
1271                 kfree(urbp);
1272                 goto done;
1273         }
1274
1275         if (!dum_hcd->udev) {
1276                 dum_hcd->udev = urb->dev;
1277                 usb_get_dev(dum_hcd->udev);
1278         } else if (unlikely(dum_hcd->udev != urb->dev))
1279                 dev_err(dummy_dev(dum_hcd), "usb_device address has changed!\n");
1280
1281         list_add_tail(&urbp->urbp_list, &dum_hcd->urbp_list);
1282         urb->hcpriv = urbp;
1283         if (!dum_hcd->next_frame_urbp)
1284                 dum_hcd->next_frame_urbp = urbp;
1285         if (usb_pipetype(urb->pipe) == PIPE_CONTROL)
1286                 urb->error_count = 1;           /* mark as a new urb */
1287
1288         /* kick the scheduler, it'll do the rest */
1289         if (!timer_pending(&dum_hcd->timer))
1290                 mod_timer(&dum_hcd->timer, jiffies + 1);
1291
1292  done:
1293         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
1294         return rc;
1295 }
1296
1297 static int dummy_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
1298 {
1299         struct dummy_hcd *dum_hcd;
1300         unsigned long   flags;
1301         int             rc;
1302
1303         /* giveback happens automatically in timer callback,
1304          * so make sure the callback happens */
1305         dum_hcd = hcd_to_dummy_hcd(hcd);
1306         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
1307
1308         rc = usb_hcd_check_unlink_urb(hcd, urb, status);
1309         if (!rc && dum_hcd->rh_state != DUMMY_RH_RUNNING &&
1310                         !list_empty(&dum_hcd->urbp_list))
1311                 mod_timer(&dum_hcd->timer, jiffies);
1312
1313         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
1314         return rc;
1315 }
1316
1317 static int dummy_perform_transfer(struct urb *urb, struct dummy_request *req,
1318                 u32 len)
1319 {
1320         void *ubuf, *rbuf;
1321         struct urbp *urbp = urb->hcpriv;
1322         int to_host;
1323         struct sg_mapping_iter *miter = &urbp->miter;
1324         u32 trans = 0;
1325         u32 this_sg;
1326         bool next_sg;
1327
1328         to_host = usb_pipein(urb->pipe);
1329         rbuf = req->req.buf + req->req.actual;
1330
1331         if (!urb->num_sgs) {
1332                 ubuf = urb->transfer_buffer + urb->actual_length;
1333                 if (to_host)
1334                         memcpy(ubuf, rbuf, len);
1335                 else
1336                         memcpy(rbuf, ubuf, len);
1337                 return len;
1338         }
1339
1340         if (!urbp->miter_started) {
1341                 u32 flags = SG_MITER_ATOMIC;
1342
1343                 if (to_host)
1344                         flags |= SG_MITER_TO_SG;
1345                 else
1346                         flags |= SG_MITER_FROM_SG;
1347
1348                 sg_miter_start(miter, urb->sg, urb->num_sgs, flags);
1349                 urbp->miter_started = 1;
1350         }
1351         next_sg = sg_miter_next(miter);
1352         if (next_sg == false) {
1353                 WARN_ON_ONCE(1);
1354                 return -EINVAL;
1355         }
1356         do {
1357                 ubuf = miter->addr;
1358                 this_sg = min_t(u32, len, miter->length);
1359                 miter->consumed = this_sg;
1360                 trans += this_sg;
1361
1362                 if (to_host)
1363                         memcpy(ubuf, rbuf, this_sg);
1364                 else
1365                         memcpy(rbuf, ubuf, this_sg);
1366                 len -= this_sg;
1367
1368                 if (!len)
1369                         break;
1370                 next_sg = sg_miter_next(miter);
1371                 if (next_sg == false) {
1372                         WARN_ON_ONCE(1);
1373                         return -EINVAL;
1374                 }
1375
1376                 rbuf += this_sg;
1377         } while (1);
1378
1379         sg_miter_stop(miter);
1380         return trans;
1381 }
1382
1383 /* transfer up to a frame's worth; caller must own lock */
1384 static int transfer(struct dummy_hcd *dum_hcd, struct urb *urb,
1385                 struct dummy_ep *ep, int limit, int *status)
1386 {
1387         struct dummy            *dum = dum_hcd->dum;
1388         struct dummy_request    *req;
1389         int                     sent = 0;
1390
1391 top:
1392         /* if there's no request queued, the device is NAKing; return */
1393         list_for_each_entry(req, &ep->queue, queue) {
1394                 unsigned        host_len, dev_len, len;
1395                 int             is_short, to_host;
1396                 int             rescan = 0;
1397
1398                 if (dummy_ep_stream_en(dum_hcd, urb)) {
1399                         if ((urb->stream_id != req->req.stream_id))
1400                                 continue;
1401                 }
1402
1403                 /* 1..N packets of ep->ep.maxpacket each ... the last one
1404                  * may be short (including zero length).
1405                  *
1406                  * writer can send a zlp explicitly (length 0) or implicitly
1407                  * (length mod maxpacket zero, and 'zero' flag); they always
1408                  * terminate reads.
1409                  */
1410                 host_len = urb->transfer_buffer_length - urb->actual_length;
1411                 dev_len = req->req.length - req->req.actual;
1412                 len = min(host_len, dev_len);
1413
1414                 /* FIXME update emulated data toggle too */
1415
1416                 to_host = usb_pipein(urb->pipe);
1417                 if (unlikely(len == 0))
1418                         is_short = 1;
1419                 else {
1420                         /* not enough bandwidth left? */
1421                         if (limit < ep->ep.maxpacket && limit < len)
1422                                 break;
1423                         len = min_t(unsigned, len, limit);
1424                         if (len == 0)
1425                                 break;
1426
1427                         /* send multiple of maxpacket first, then remainder */
1428                         if (len >= ep->ep.maxpacket) {
1429                                 is_short = 0;
1430                                 if (len % ep->ep.maxpacket)
1431                                         rescan = 1;
1432                                 len -= len % ep->ep.maxpacket;
1433                         } else {
1434                                 is_short = 1;
1435                         }
1436
1437                         len = dummy_perform_transfer(urb, req, len);
1438
1439                         ep->last_io = jiffies;
1440                         if ((int)len < 0) {
1441                                 req->req.status = len;
1442                         } else {
1443                                 limit -= len;
1444                                 sent += len;
1445                                 urb->actual_length += len;
1446                                 req->req.actual += len;
1447                         }
1448                 }
1449
1450                 /* short packets terminate, maybe with overflow/underflow.
1451                  * it's only really an error to write too much.
1452                  *
1453                  * partially filling a buffer optionally blocks queue advances
1454                  * (so completion handlers can clean up the queue) but we don't
1455                  * need to emulate such data-in-flight.
1456                  */
1457                 if (is_short) {
1458                         if (host_len == dev_len) {
1459                                 req->req.status = 0;
1460                                 *status = 0;
1461                         } else if (to_host) {
1462                                 req->req.status = 0;
1463                                 if (dev_len > host_len)
1464                                         *status = -EOVERFLOW;
1465                                 else
1466                                         *status = 0;
1467                         } else {
1468                                 *status = 0;
1469                                 if (host_len > dev_len)
1470                                         req->req.status = -EOVERFLOW;
1471                                 else
1472                                         req->req.status = 0;
1473                         }
1474
1475                 /*
1476                  * many requests terminate without a short packet.
1477                  * send a zlp if demanded by flags.
1478                  */
1479                 } else {
1480                         if (req->req.length == req->req.actual) {
1481                                 if (req->req.zero && to_host)
1482                                         rescan = 1;
1483                                 else
1484                                         req->req.status = 0;
1485                         }
1486                         if (urb->transfer_buffer_length == urb->actual_length) {
1487                                 if (urb->transfer_flags & URB_ZERO_PACKET &&
1488                                     !to_host)
1489                                         rescan = 1;
1490                                 else
1491                                         *status = 0;
1492                         }
1493                 }
1494
1495                 /* device side completion --> continuable */
1496                 if (req->req.status != -EINPROGRESS) {
1497                         list_del_init(&req->queue);
1498
1499                         spin_unlock(&dum->lock);
1500                         usb_gadget_giveback_request(&ep->ep, &req->req);
1501                         spin_lock(&dum->lock);
1502
1503                         /* requests might have been unlinked... */
1504                         rescan = 1;
1505                 }
1506
1507                 /* host side completion --> terminate */
1508                 if (*status != -EINPROGRESS)
1509                         break;
1510
1511                 /* rescan to continue with any other queued i/o */
1512                 if (rescan)
1513                         goto top;
1514         }
1515         return sent;
1516 }
1517
1518 static int periodic_bytes(struct dummy *dum, struct dummy_ep *ep)
1519 {
1520         int     limit = ep->ep.maxpacket;
1521
1522         if (dum->gadget.speed == USB_SPEED_HIGH) {
1523                 int     tmp;
1524
1525                 /* high bandwidth mode */
1526                 tmp = usb_endpoint_maxp(ep->desc);
1527                 tmp = (tmp >> 11) & 0x03;
1528                 tmp *= 8 /* applies to entire frame */;
1529                 limit += limit * tmp;
1530         }
1531         if (dum->gadget.speed == USB_SPEED_SUPER) {
1532                 switch (usb_endpoint_type(ep->desc)) {
1533                 case USB_ENDPOINT_XFER_ISOC:
1534                         /* Sec. 4.4.8.2 USB3.0 Spec */
1535                         limit = 3 * 16 * 1024 * 8;
1536                         break;
1537                 case USB_ENDPOINT_XFER_INT:
1538                         /* Sec. 4.4.7.2 USB3.0 Spec */
1539                         limit = 3 * 1024 * 8;
1540                         break;
1541                 case USB_ENDPOINT_XFER_BULK:
1542                 default:
1543                         break;
1544                 }
1545         }
1546         return limit;
1547 }
1548
1549 #define is_active(dum_hcd)      ((dum_hcd->port_status & \
1550                 (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE | \
1551                         USB_PORT_STAT_SUSPEND)) \
1552                 == (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE))
1553
1554 static struct dummy_ep *find_endpoint(struct dummy *dum, u8 address)
1555 {
1556         int             i;
1557
1558         if (!is_active((dum->gadget.speed == USB_SPEED_SUPER ?
1559                         dum->ss_hcd : dum->hs_hcd)))
1560                 return NULL;
1561         if (!dum->ints_enabled)
1562                 return NULL;
1563         if ((address & ~USB_DIR_IN) == 0)
1564                 return &dum->ep[0];
1565         for (i = 1; i < DUMMY_ENDPOINTS; i++) {
1566                 struct dummy_ep *ep = &dum->ep[i];
1567
1568                 if (!ep->desc)
1569                         continue;
1570                 if (ep->desc->bEndpointAddress == address)
1571                         return ep;
1572         }
1573         return NULL;
1574 }
1575
1576 #undef is_active
1577
1578 #define Dev_Request     (USB_TYPE_STANDARD | USB_RECIP_DEVICE)
1579 #define Dev_InRequest   (Dev_Request | USB_DIR_IN)
1580 #define Intf_Request    (USB_TYPE_STANDARD | USB_RECIP_INTERFACE)
1581 #define Intf_InRequest  (Intf_Request | USB_DIR_IN)
1582 #define Ep_Request      (USB_TYPE_STANDARD | USB_RECIP_ENDPOINT)
1583 #define Ep_InRequest    (Ep_Request | USB_DIR_IN)
1584
1585
1586 /**
1587  * handle_control_request() - handles all control transfers
1588  * @dum: pointer to dummy (the_controller)
1589  * @urb: the urb request to handle
1590  * @setup: pointer to the setup data for a USB device control
1591  *       request
1592  * @status: pointer to request handling status
1593  *
1594  * Return 0 - if the request was handled
1595  *        1 - if the request wasn't handles
1596  *        error code on error
1597  */
1598 static int handle_control_request(struct dummy_hcd *dum_hcd, struct urb *urb,
1599                                   struct usb_ctrlrequest *setup,
1600                                   int *status)
1601 {
1602         struct dummy_ep         *ep2;
1603         struct dummy            *dum = dum_hcd->dum;
1604         int                     ret_val = 1;
1605         unsigned        w_index;
1606         unsigned        w_value;
1607
1608         w_index = le16_to_cpu(setup->wIndex);
1609         w_value = le16_to_cpu(setup->wValue);
1610         switch (setup->bRequest) {
1611         case USB_REQ_SET_ADDRESS:
1612                 if (setup->bRequestType != Dev_Request)
1613                         break;
1614                 dum->address = w_value;
1615                 *status = 0;
1616                 dev_dbg(udc_dev(dum), "set_address = %d\n",
1617                                 w_value);
1618                 ret_val = 0;
1619                 break;
1620         case USB_REQ_SET_FEATURE:
1621                 if (setup->bRequestType == Dev_Request) {
1622                         ret_val = 0;
1623                         switch (w_value) {
1624                         case USB_DEVICE_REMOTE_WAKEUP:
1625                                 break;
1626                         case USB_DEVICE_B_HNP_ENABLE:
1627                                 dum->gadget.b_hnp_enable = 1;
1628                                 break;
1629                         case USB_DEVICE_A_HNP_SUPPORT:
1630                                 dum->gadget.a_hnp_support = 1;
1631                                 break;
1632                         case USB_DEVICE_A_ALT_HNP_SUPPORT:
1633                                 dum->gadget.a_alt_hnp_support = 1;
1634                                 break;
1635                         case USB_DEVICE_U1_ENABLE:
1636                                 if (dummy_hcd_to_hcd(dum_hcd)->speed ==
1637                                     HCD_USB3)
1638                                         w_value = USB_DEV_STAT_U1_ENABLED;
1639                                 else
1640                                         ret_val = -EOPNOTSUPP;
1641                                 break;
1642                         case USB_DEVICE_U2_ENABLE:
1643                                 if (dummy_hcd_to_hcd(dum_hcd)->speed ==
1644                                     HCD_USB3)
1645                                         w_value = USB_DEV_STAT_U2_ENABLED;
1646                                 else
1647                                         ret_val = -EOPNOTSUPP;
1648                                 break;
1649                         case USB_DEVICE_LTM_ENABLE:
1650                                 if (dummy_hcd_to_hcd(dum_hcd)->speed ==
1651                                     HCD_USB3)
1652                                         w_value = USB_DEV_STAT_LTM_ENABLED;
1653                                 else
1654                                         ret_val = -EOPNOTSUPP;
1655                                 break;
1656                         default:
1657                                 ret_val = -EOPNOTSUPP;
1658                         }
1659                         if (ret_val == 0) {
1660                                 dum->devstatus |= (1 << w_value);
1661                                 *status = 0;
1662                         }
1663                 } else if (setup->bRequestType == Ep_Request) {
1664                         /* endpoint halt */
1665                         ep2 = find_endpoint(dum, w_index);
1666                         if (!ep2 || ep2->ep.name == ep0name) {
1667                                 ret_val = -EOPNOTSUPP;
1668                                 break;
1669                         }
1670                         ep2->halted = 1;
1671                         ret_val = 0;
1672                         *status = 0;
1673                 }
1674                 break;
1675         case USB_REQ_CLEAR_FEATURE:
1676                 if (setup->bRequestType == Dev_Request) {
1677                         ret_val = 0;
1678                         switch (w_value) {
1679                         case USB_DEVICE_REMOTE_WAKEUP:
1680                                 w_value = USB_DEVICE_REMOTE_WAKEUP;
1681                                 break;
1682                         case USB_DEVICE_U1_ENABLE:
1683                                 if (dummy_hcd_to_hcd(dum_hcd)->speed ==
1684                                     HCD_USB3)
1685                                         w_value = USB_DEV_STAT_U1_ENABLED;
1686                                 else
1687                                         ret_val = -EOPNOTSUPP;
1688                                 break;
1689                         case USB_DEVICE_U2_ENABLE:
1690                                 if (dummy_hcd_to_hcd(dum_hcd)->speed ==
1691                                     HCD_USB3)
1692                                         w_value = USB_DEV_STAT_U2_ENABLED;
1693                                 else
1694                                         ret_val = -EOPNOTSUPP;
1695                                 break;
1696                         case USB_DEVICE_LTM_ENABLE:
1697                                 if (dummy_hcd_to_hcd(dum_hcd)->speed ==
1698                                     HCD_USB3)
1699                                         w_value = USB_DEV_STAT_LTM_ENABLED;
1700                                 else
1701                                         ret_val = -EOPNOTSUPP;
1702                                 break;
1703                         default:
1704                                 ret_val = -EOPNOTSUPP;
1705                                 break;
1706                         }
1707                         if (ret_val == 0) {
1708                                 dum->devstatus &= ~(1 << w_value);
1709                                 *status = 0;
1710                         }
1711                 } else if (setup->bRequestType == Ep_Request) {
1712                         /* endpoint halt */
1713                         ep2 = find_endpoint(dum, w_index);
1714                         if (!ep2) {
1715                                 ret_val = -EOPNOTSUPP;
1716                                 break;
1717                         }
1718                         if (!ep2->wedged)
1719                                 ep2->halted = 0;
1720                         ret_val = 0;
1721                         *status = 0;
1722                 }
1723                 break;
1724         case USB_REQ_GET_STATUS:
1725                 if (setup->bRequestType == Dev_InRequest
1726                                 || setup->bRequestType == Intf_InRequest
1727                                 || setup->bRequestType == Ep_InRequest) {
1728                         char *buf;
1729                         /*
1730                          * device: remote wakeup, selfpowered
1731                          * interface: nothing
1732                          * endpoint: halt
1733                          */
1734                         buf = (char *)urb->transfer_buffer;
1735                         if (urb->transfer_buffer_length > 0) {
1736                                 if (setup->bRequestType == Ep_InRequest) {
1737                                         ep2 = find_endpoint(dum, w_index);
1738                                         if (!ep2) {
1739                                                 ret_val = -EOPNOTSUPP;
1740                                                 break;
1741                                         }
1742                                         buf[0] = ep2->halted;
1743                                 } else if (setup->bRequestType ==
1744                                            Dev_InRequest) {
1745                                         buf[0] = (u8)dum->devstatus;
1746                                 } else
1747                                         buf[0] = 0;
1748                         }
1749                         if (urb->transfer_buffer_length > 1)
1750                                 buf[1] = 0;
1751                         urb->actual_length = min_t(u32, 2,
1752                                 urb->transfer_buffer_length);
1753                         ret_val = 0;
1754                         *status = 0;
1755                 }
1756                 break;
1757         }
1758         return ret_val;
1759 }
1760
1761 /* drive both sides of the transfers; looks like irq handlers to
1762  * both drivers except the callbacks aren't in_irq().
1763  */
1764 static void dummy_timer(unsigned long _dum_hcd)
1765 {
1766         struct dummy_hcd        *dum_hcd = (struct dummy_hcd *) _dum_hcd;
1767         struct dummy            *dum = dum_hcd->dum;
1768         struct urbp             *urbp, *tmp;
1769         unsigned long           flags;
1770         int                     limit, total;
1771         int                     i;
1772
1773         /* simplistic model for one frame's bandwidth */
1774         switch (dum->gadget.speed) {
1775         case USB_SPEED_LOW:
1776                 total = 8/*bytes*/ * 12/*packets*/;
1777                 break;
1778         case USB_SPEED_FULL:
1779                 total = 64/*bytes*/ * 19/*packets*/;
1780                 break;
1781         case USB_SPEED_HIGH:
1782                 total = 512/*bytes*/ * 13/*packets*/ * 8/*uframes*/;
1783                 break;
1784         case USB_SPEED_SUPER:
1785                 /* Bus speed is 500000 bytes/ms, so use a little less */
1786                 total = 490000;
1787                 break;
1788         default:
1789                 dev_err(dummy_dev(dum_hcd), "bogus device speed\n");
1790                 return;
1791         }
1792
1793         /* FIXME if HZ != 1000 this will probably misbehave ... */
1794
1795         /* look at each urb queued by the host side driver */
1796         spin_lock_irqsave(&dum->lock, flags);
1797
1798         if (!dum_hcd->udev) {
1799                 dev_err(dummy_dev(dum_hcd),
1800                                 "timer fired with no URBs pending?\n");
1801                 spin_unlock_irqrestore(&dum->lock, flags);
1802                 return;
1803         }
1804         dum_hcd->next_frame_urbp = NULL;
1805
1806         for (i = 0; i < DUMMY_ENDPOINTS; i++) {
1807                 if (!ep_info[i].name)
1808                         break;
1809                 dum->ep[i].already_seen = 0;
1810         }
1811
1812 restart:
1813         list_for_each_entry_safe(urbp, tmp, &dum_hcd->urbp_list, urbp_list) {
1814                 struct urb              *urb;
1815                 struct dummy_request    *req;
1816                 u8                      address;
1817                 struct dummy_ep         *ep = NULL;
1818                 int                     type;
1819                 int                     status = -EINPROGRESS;
1820
1821                 /* stop when we reach URBs queued after the timer interrupt */
1822                 if (urbp == dum_hcd->next_frame_urbp)
1823                         break;
1824
1825                 urb = urbp->urb;
1826                 if (urb->unlinked)
1827                         goto return_urb;
1828                 else if (dum_hcd->rh_state != DUMMY_RH_RUNNING)
1829                         continue;
1830                 type = usb_pipetype(urb->pipe);
1831
1832                 /* used up this frame's non-periodic bandwidth?
1833                  * FIXME there's infinite bandwidth for control and
1834                  * periodic transfers ... unrealistic.
1835                  */
1836                 if (total <= 0 && type == PIPE_BULK)
1837                         continue;
1838
1839                 /* find the gadget's ep for this request (if configured) */
1840                 address = usb_pipeendpoint (urb->pipe);
1841                 if (usb_pipein(urb->pipe))
1842                         address |= USB_DIR_IN;
1843                 ep = find_endpoint(dum, address);
1844                 if (!ep) {
1845                         /* set_configuration() disagreement */
1846                         dev_dbg(dummy_dev(dum_hcd),
1847                                 "no ep configured for urb %p\n",
1848                                 urb);
1849                         status = -EPROTO;
1850                         goto return_urb;
1851                 }
1852
1853                 if (ep->already_seen)
1854                         continue;
1855                 ep->already_seen = 1;
1856                 if (ep == &dum->ep[0] && urb->error_count) {
1857                         ep->setup_stage = 1;    /* a new urb */
1858                         urb->error_count = 0;
1859                 }
1860                 if (ep->halted && !ep->setup_stage) {
1861                         /* NOTE: must not be iso! */
1862                         dev_dbg(dummy_dev(dum_hcd), "ep %s halted, urb %p\n",
1863                                         ep->ep.name, urb);
1864                         status = -EPIPE;
1865                         goto return_urb;
1866                 }
1867                 /* FIXME make sure both ends agree on maxpacket */
1868
1869                 /* handle control requests */
1870                 if (ep == &dum->ep[0] && ep->setup_stage) {
1871                         struct usb_ctrlrequest          setup;
1872                         int                             value = 1;
1873
1874                         setup = *(struct usb_ctrlrequest *) urb->setup_packet;
1875                         /* paranoia, in case of stale queued data */
1876                         list_for_each_entry(req, &ep->queue, queue) {
1877                                 list_del_init(&req->queue);
1878                                 req->req.status = -EOVERFLOW;
1879                                 dev_dbg(udc_dev(dum), "stale req = %p\n",
1880                                                 req);
1881
1882                                 spin_unlock(&dum->lock);
1883                                 usb_gadget_giveback_request(&ep->ep, &req->req);
1884                                 spin_lock(&dum->lock);
1885                                 ep->already_seen = 0;
1886                                 goto restart;
1887                         }
1888
1889                         /* gadget driver never sees set_address or operations
1890                          * on standard feature flags.  some hardware doesn't
1891                          * even expose them.
1892                          */
1893                         ep->last_io = jiffies;
1894                         ep->setup_stage = 0;
1895                         ep->halted = 0;
1896
1897                         value = handle_control_request(dum_hcd, urb, &setup,
1898                                                        &status);
1899
1900                         /* gadget driver handles all other requests.  block
1901                          * until setup() returns; no reentrancy issues etc.
1902                          */
1903                         if (value > 0) {
1904                                 ++dum->callback_usage;
1905                                 spin_unlock(&dum->lock);
1906                                 value = dum->driver->setup(&dum->gadget,
1907                                                 &setup);
1908                                 spin_lock(&dum->lock);
1909                                 --dum->callback_usage;
1910
1911                                 if (value >= 0) {
1912                                         /* no delays (max 64KB data stage) */
1913                                         limit = 64*1024;
1914                                         goto treat_control_like_bulk;
1915                                 }
1916                                 /* error, see below */
1917                         }
1918
1919                         if (value < 0) {
1920                                 if (value != -EOPNOTSUPP)
1921                                         dev_dbg(udc_dev(dum),
1922                                                 "setup --> %d\n",
1923                                                 value);
1924                                 status = -EPIPE;
1925                                 urb->actual_length = 0;
1926                         }
1927
1928                         goto return_urb;
1929                 }
1930
1931                 /* non-control requests */
1932                 limit = total;
1933                 switch (usb_pipetype(urb->pipe)) {
1934                 case PIPE_ISOCHRONOUS:
1935                         /* FIXME is it urb->interval since the last xfer?
1936                          * use urb->iso_frame_desc[i].
1937                          * complete whether or not ep has requests queued.
1938                          * report random errors, to debug drivers.
1939                          */
1940                         limit = max(limit, periodic_bytes(dum, ep));
1941                         status = -ENOSYS;
1942                         break;
1943
1944                 case PIPE_INTERRUPT:
1945                         /* FIXME is it urb->interval since the last xfer?
1946                          * this almost certainly polls too fast.
1947                          */
1948                         limit = max(limit, periodic_bytes(dum, ep));
1949                         /* FALLTHROUGH */
1950
1951                 default:
1952 treat_control_like_bulk:
1953                         ep->last_io = jiffies;
1954                         total -= transfer(dum_hcd, urb, ep, limit, &status);
1955                         break;
1956                 }
1957
1958                 /* incomplete transfer? */
1959                 if (status == -EINPROGRESS)
1960                         continue;
1961
1962 return_urb:
1963                 list_del(&urbp->urbp_list);
1964                 kfree(urbp);
1965                 if (ep)
1966                         ep->already_seen = ep->setup_stage = 0;
1967
1968                 usb_hcd_unlink_urb_from_ep(dummy_hcd_to_hcd(dum_hcd), urb);
1969                 spin_unlock(&dum->lock);
1970                 usb_hcd_giveback_urb(dummy_hcd_to_hcd(dum_hcd), urb, status);
1971                 spin_lock(&dum->lock);
1972
1973                 goto restart;
1974         }
1975
1976         if (list_empty(&dum_hcd->urbp_list)) {
1977                 usb_put_dev(dum_hcd->udev);
1978                 dum_hcd->udev = NULL;
1979         } else if (dum_hcd->rh_state == DUMMY_RH_RUNNING) {
1980                 /* want a 1 msec delay here */
1981                 mod_timer(&dum_hcd->timer, jiffies + msecs_to_jiffies(1));
1982         }
1983
1984         spin_unlock_irqrestore(&dum->lock, flags);
1985 }
1986
1987 /*-------------------------------------------------------------------------*/
1988
1989 #define PORT_C_MASK \
1990         ((USB_PORT_STAT_C_CONNECTION \
1991         | USB_PORT_STAT_C_ENABLE \
1992         | USB_PORT_STAT_C_SUSPEND \
1993         | USB_PORT_STAT_C_OVERCURRENT \
1994         | USB_PORT_STAT_C_RESET) << 16)
1995
1996 static int dummy_hub_status(struct usb_hcd *hcd, char *buf)
1997 {
1998         struct dummy_hcd        *dum_hcd;
1999         unsigned long           flags;
2000         int                     retval = 0;
2001
2002         dum_hcd = hcd_to_dummy_hcd(hcd);
2003
2004         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
2005         if (!HCD_HW_ACCESSIBLE(hcd))
2006                 goto done;
2007
2008         if (dum_hcd->resuming && time_after_eq(jiffies, dum_hcd->re_timeout)) {
2009                 dum_hcd->port_status |= (USB_PORT_STAT_C_SUSPEND << 16);
2010                 dum_hcd->port_status &= ~USB_PORT_STAT_SUSPEND;
2011                 set_link_state(dum_hcd);
2012         }
2013
2014         if ((dum_hcd->port_status & PORT_C_MASK) != 0) {
2015                 *buf = (1 << 1);
2016                 dev_dbg(dummy_dev(dum_hcd), "port status 0x%08x has changes\n",
2017                                 dum_hcd->port_status);
2018                 retval = 1;
2019                 if (dum_hcd->rh_state == DUMMY_RH_SUSPENDED)
2020                         usb_hcd_resume_root_hub(hcd);
2021         }
2022 done:
2023         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
2024         return retval;
2025 }
2026
2027 /* usb 3.0 root hub device descriptor */
2028 static struct {
2029         struct usb_bos_descriptor bos;
2030         struct usb_ss_cap_descriptor ss_cap;
2031 } __packed usb3_bos_desc = {
2032
2033         .bos = {
2034                 .bLength                = USB_DT_BOS_SIZE,
2035                 .bDescriptorType        = USB_DT_BOS,
2036                 .wTotalLength           = cpu_to_le16(sizeof(usb3_bos_desc)),
2037                 .bNumDeviceCaps         = 1,
2038         },
2039         .ss_cap = {
2040                 .bLength                = USB_DT_USB_SS_CAP_SIZE,
2041                 .bDescriptorType        = USB_DT_DEVICE_CAPABILITY,
2042                 .bDevCapabilityType     = USB_SS_CAP_TYPE,
2043                 .wSpeedSupported        = cpu_to_le16(USB_5GBPS_OPERATION),
2044                 .bFunctionalitySupport  = ilog2(USB_5GBPS_OPERATION),
2045         },
2046 };
2047
2048 static inline void
2049 ss_hub_descriptor(struct usb_hub_descriptor *desc)
2050 {
2051         memset(desc, 0, sizeof *desc);
2052         desc->bDescriptorType = USB_DT_SS_HUB;
2053         desc->bDescLength = 12;
2054         desc->wHubCharacteristics = cpu_to_le16(
2055                         HUB_CHAR_INDV_PORT_LPSM |
2056                         HUB_CHAR_COMMON_OCPM);
2057         desc->bNbrPorts = 1;
2058         desc->u.ss.bHubHdrDecLat = 0x04; /* Worst case: 0.4 micro sec*/
2059         desc->u.ss.DeviceRemovable = 0;
2060 }
2061
2062 static inline void hub_descriptor(struct usb_hub_descriptor *desc)
2063 {
2064         memset(desc, 0, sizeof *desc);
2065         desc->bDescriptorType = USB_DT_HUB;
2066         desc->bDescLength = 9;
2067         desc->wHubCharacteristics = cpu_to_le16(
2068                         HUB_CHAR_INDV_PORT_LPSM |
2069                         HUB_CHAR_COMMON_OCPM);
2070         desc->bNbrPorts = 1;
2071         desc->u.hs.DeviceRemovable[0] = 0;
2072         desc->u.hs.DeviceRemovable[1] = 0xff;   /* PortPwrCtrlMask */
2073 }
2074
2075 static int dummy_hub_control(
2076         struct usb_hcd  *hcd,
2077         u16             typeReq,
2078         u16             wValue,
2079         u16             wIndex,
2080         char            *buf,
2081         u16             wLength
2082 ) {
2083         struct dummy_hcd *dum_hcd;
2084         int             retval = 0;
2085         unsigned long   flags;
2086
2087         if (!HCD_HW_ACCESSIBLE(hcd))
2088                 return -ETIMEDOUT;
2089
2090         dum_hcd = hcd_to_dummy_hcd(hcd);
2091
2092         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
2093         switch (typeReq) {
2094         case ClearHubFeature:
2095                 break;
2096         case ClearPortFeature:
2097                 switch (wValue) {
2098                 case USB_PORT_FEAT_SUSPEND:
2099                         if (hcd->speed == HCD_USB3) {
2100                                 dev_dbg(dummy_dev(dum_hcd),
2101                                          "USB_PORT_FEAT_SUSPEND req not "
2102                                          "supported for USB 3.0 roothub\n");
2103                                 goto error;
2104                         }
2105                         if (dum_hcd->port_status & USB_PORT_STAT_SUSPEND) {
2106                                 /* 20msec resume signaling */
2107                                 dum_hcd->resuming = 1;
2108                                 dum_hcd->re_timeout = jiffies +
2109                                                 msecs_to_jiffies(20);
2110                         }
2111                         break;
2112                 case USB_PORT_FEAT_POWER:
2113                         dev_dbg(dummy_dev(dum_hcd), "power-off\n");
2114                         if (hcd->speed == HCD_USB3)
2115                                 dum_hcd->port_status &= ~USB_SS_PORT_STAT_POWER;
2116                         else
2117                                 dum_hcd->port_status &= ~USB_PORT_STAT_POWER;
2118                         set_link_state(dum_hcd);
2119                         break;
2120                 default:
2121                         dum_hcd->port_status &= ~(1 << wValue);
2122                         set_link_state(dum_hcd);
2123                 }
2124                 break;
2125         case GetHubDescriptor:
2126                 if (hcd->speed == HCD_USB3 &&
2127                                 (wLength < USB_DT_SS_HUB_SIZE ||
2128                                  wValue != (USB_DT_SS_HUB << 8))) {
2129                         dev_dbg(dummy_dev(dum_hcd),
2130                                 "Wrong hub descriptor type for "
2131                                 "USB 3.0 roothub.\n");
2132                         goto error;
2133                 }
2134                 if (hcd->speed == HCD_USB3)
2135                         ss_hub_descriptor((struct usb_hub_descriptor *) buf);
2136                 else
2137                         hub_descriptor((struct usb_hub_descriptor *) buf);
2138                 break;
2139
2140         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
2141                 if (hcd->speed != HCD_USB3)
2142                         goto error;
2143
2144                 if ((wValue >> 8) != USB_DT_BOS)
2145                         goto error;
2146
2147                 memcpy(buf, &usb3_bos_desc, sizeof(usb3_bos_desc));
2148                 retval = sizeof(usb3_bos_desc);
2149                 break;
2150
2151         case GetHubStatus:
2152                 *(__le32 *) buf = cpu_to_le32(0);
2153                 break;
2154         case GetPortStatus:
2155                 if (wIndex != 1)
2156                         retval = -EPIPE;
2157
2158                 /* whoever resets or resumes must GetPortStatus to
2159                  * complete it!!
2160                  */
2161                 if (dum_hcd->resuming &&
2162                                 time_after_eq(jiffies, dum_hcd->re_timeout)) {
2163                         dum_hcd->port_status |= (USB_PORT_STAT_C_SUSPEND << 16);
2164                         dum_hcd->port_status &= ~USB_PORT_STAT_SUSPEND;
2165                 }
2166                 if ((dum_hcd->port_status & USB_PORT_STAT_RESET) != 0 &&
2167                                 time_after_eq(jiffies, dum_hcd->re_timeout)) {
2168                         dum_hcd->port_status |= (USB_PORT_STAT_C_RESET << 16);
2169                         dum_hcd->port_status &= ~USB_PORT_STAT_RESET;
2170                         if (dum_hcd->dum->pullup) {
2171                                 dum_hcd->port_status |= USB_PORT_STAT_ENABLE;
2172
2173                                 if (hcd->speed < HCD_USB3) {
2174                                         switch (dum_hcd->dum->gadget.speed) {
2175                                         case USB_SPEED_HIGH:
2176                                                 dum_hcd->port_status |=
2177                                                       USB_PORT_STAT_HIGH_SPEED;
2178                                                 break;
2179                                         case USB_SPEED_LOW:
2180                                                 dum_hcd->dum->gadget.ep0->
2181                                                         maxpacket = 8;
2182                                                 dum_hcd->port_status |=
2183                                                         USB_PORT_STAT_LOW_SPEED;
2184                                                 break;
2185                                         default:
2186                                                 dum_hcd->dum->gadget.speed =
2187                                                         USB_SPEED_FULL;
2188                                                 break;
2189                                         }
2190                                 }
2191                         }
2192                 }
2193                 set_link_state(dum_hcd);
2194                 ((__le16 *) buf)[0] = cpu_to_le16(dum_hcd->port_status);
2195                 ((__le16 *) buf)[1] = cpu_to_le16(dum_hcd->port_status >> 16);
2196                 break;
2197         case SetHubFeature:
2198                 retval = -EPIPE;
2199                 break;
2200         case SetPortFeature:
2201                 switch (wValue) {
2202                 case USB_PORT_FEAT_LINK_STATE:
2203                         if (hcd->speed != HCD_USB3) {
2204                                 dev_dbg(dummy_dev(dum_hcd),
2205                                          "USB_PORT_FEAT_LINK_STATE req not "
2206                                          "supported for USB 2.0 roothub\n");
2207                                 goto error;
2208                         }
2209                         /*
2210                          * Since this is dummy we don't have an actual link so
2211                          * there is nothing to do for the SET_LINK_STATE cmd
2212                          */
2213                         break;
2214                 case USB_PORT_FEAT_U1_TIMEOUT:
2215                 case USB_PORT_FEAT_U2_TIMEOUT:
2216                         /* TODO: add suspend/resume support! */
2217                         if (hcd->speed != HCD_USB3) {
2218                                 dev_dbg(dummy_dev(dum_hcd),
2219                                          "USB_PORT_FEAT_U1/2_TIMEOUT req not "
2220                                          "supported for USB 2.0 roothub\n");
2221                                 goto error;
2222                         }
2223                         break;
2224                 case USB_PORT_FEAT_SUSPEND:
2225                         /* Applicable only for USB2.0 hub */
2226                         if (hcd->speed == HCD_USB3) {
2227                                 dev_dbg(dummy_dev(dum_hcd),
2228                                          "USB_PORT_FEAT_SUSPEND req not "
2229                                          "supported for USB 3.0 roothub\n");
2230                                 goto error;
2231                         }
2232                         if (dum_hcd->active) {
2233                                 dum_hcd->port_status |= USB_PORT_STAT_SUSPEND;
2234
2235                                 /* HNP would happen here; for now we
2236                                  * assume b_bus_req is always true.
2237                                  */
2238                                 set_link_state(dum_hcd);
2239                                 if (((1 << USB_DEVICE_B_HNP_ENABLE)
2240                                                 & dum_hcd->dum->devstatus) != 0)
2241                                         dev_dbg(dummy_dev(dum_hcd),
2242                                                         "no HNP yet!\n");
2243                         }
2244                         break;
2245                 case USB_PORT_FEAT_POWER:
2246                         if (hcd->speed == HCD_USB3)
2247                                 dum_hcd->port_status |= USB_SS_PORT_STAT_POWER;
2248                         else
2249                                 dum_hcd->port_status |= USB_PORT_STAT_POWER;
2250                         set_link_state(dum_hcd);
2251                         break;
2252                 case USB_PORT_FEAT_BH_PORT_RESET:
2253                         /* Applicable only for USB3.0 hub */
2254                         if (hcd->speed != HCD_USB3) {
2255                                 dev_dbg(dummy_dev(dum_hcd),
2256                                          "USB_PORT_FEAT_BH_PORT_RESET req not "
2257                                          "supported for USB 2.0 roothub\n");
2258                                 goto error;
2259                         }
2260                         /* FALLS THROUGH */
2261                 case USB_PORT_FEAT_RESET:
2262                         /* if it's already enabled, disable */
2263                         if (hcd->speed == HCD_USB3) {
2264                                 dum_hcd->port_status = 0;
2265                                 dum_hcd->port_status =
2266                                         (USB_SS_PORT_STAT_POWER |
2267                                          USB_PORT_STAT_CONNECTION |
2268                                          USB_PORT_STAT_RESET);
2269                         } else
2270                                 dum_hcd->port_status &= ~(USB_PORT_STAT_ENABLE
2271                                         | USB_PORT_STAT_LOW_SPEED
2272                                         | USB_PORT_STAT_HIGH_SPEED);
2273                         /*
2274                          * We want to reset device status. All but the
2275                          * Self powered feature
2276                          */
2277                         dum_hcd->dum->devstatus &=
2278                                 (1 << USB_DEVICE_SELF_POWERED);
2279                         /*
2280                          * FIXME USB3.0: what is the correct reset signaling
2281                          * interval? Is it still 50msec as for HS?
2282                          */
2283                         dum_hcd->re_timeout = jiffies + msecs_to_jiffies(50);
2284                         /* FALLS THROUGH */
2285                 default:
2286                         if (hcd->speed == HCD_USB3) {
2287                                 if ((dum_hcd->port_status &
2288                                      USB_SS_PORT_STAT_POWER) != 0) {
2289                                         dum_hcd->port_status |= (1 << wValue);
2290                                 }
2291                         } else
2292                                 if ((dum_hcd->port_status &
2293                                      USB_PORT_STAT_POWER) != 0) {
2294                                         dum_hcd->port_status |= (1 << wValue);
2295                                 }
2296                         set_link_state(dum_hcd);
2297                 }
2298                 break;
2299         case GetPortErrorCount:
2300                 if (hcd->speed != HCD_USB3) {
2301                         dev_dbg(dummy_dev(dum_hcd),
2302                                  "GetPortErrorCount req not "
2303                                  "supported for USB 2.0 roothub\n");
2304                         goto error;
2305                 }
2306                 /* We'll always return 0 since this is a dummy hub */
2307                 *(__le32 *) buf = cpu_to_le32(0);
2308                 break;
2309         case SetHubDepth:
2310                 if (hcd->speed != HCD_USB3) {
2311                         dev_dbg(dummy_dev(dum_hcd),
2312                                  "SetHubDepth req not supported for "
2313                                  "USB 2.0 roothub\n");
2314                         goto error;
2315                 }
2316                 break;
2317         default:
2318                 dev_dbg(dummy_dev(dum_hcd),
2319                         "hub control req%04x v%04x i%04x l%d\n",
2320                         typeReq, wValue, wIndex, wLength);
2321 error:
2322                 /* "protocol stall" on error */
2323                 retval = -EPIPE;
2324         }
2325         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
2326
2327         if ((dum_hcd->port_status & PORT_C_MASK) != 0)
2328                 usb_hcd_poll_rh_status(hcd);
2329         return retval;
2330 }
2331
2332 static int dummy_bus_suspend(struct usb_hcd *hcd)
2333 {
2334         struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
2335
2336         dev_dbg(&hcd->self.root_hub->dev, "%s\n", __func__);
2337
2338         spin_lock_irq(&dum_hcd->dum->lock);
2339         dum_hcd->rh_state = DUMMY_RH_SUSPENDED;
2340         set_link_state(dum_hcd);
2341         hcd->state = HC_STATE_SUSPENDED;
2342         spin_unlock_irq(&dum_hcd->dum->lock);
2343         return 0;
2344 }
2345
2346 static int dummy_bus_resume(struct usb_hcd *hcd)
2347 {
2348         struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
2349         int rc = 0;
2350
2351         dev_dbg(&hcd->self.root_hub->dev, "%s\n", __func__);
2352
2353         spin_lock_irq(&dum_hcd->dum->lock);
2354         if (!HCD_HW_ACCESSIBLE(hcd)) {
2355                 rc = -ESHUTDOWN;
2356         } else {
2357                 dum_hcd->rh_state = DUMMY_RH_RUNNING;
2358                 set_link_state(dum_hcd);
2359                 if (!list_empty(&dum_hcd->urbp_list))
2360                         mod_timer(&dum_hcd->timer, jiffies);
2361                 hcd->state = HC_STATE_RUNNING;
2362         }
2363         spin_unlock_irq(&dum_hcd->dum->lock);
2364         return rc;
2365 }
2366
2367 /*-------------------------------------------------------------------------*/
2368
2369 static inline ssize_t show_urb(char *buf, size_t size, struct urb *urb)
2370 {
2371         int ep = usb_pipeendpoint(urb->pipe);
2372
2373         return snprintf(buf, size,
2374                 "urb/%p %s ep%d%s%s len %d/%d\n",
2375                 urb,
2376                 ({ char *s;
2377                 switch (urb->dev->speed) {
2378                 case USB_SPEED_LOW:
2379                         s = "ls";
2380                         break;
2381                 case USB_SPEED_FULL:
2382                         s = "fs";
2383                         break;
2384                 case USB_SPEED_HIGH:
2385                         s = "hs";
2386                         break;
2387                 case USB_SPEED_SUPER:
2388                         s = "ss";
2389                         break;
2390                 default:
2391                         s = "?";
2392                         break;
2393                  } s; }),
2394                 ep, ep ? (usb_pipein(urb->pipe) ? "in" : "out") : "",
2395                 ({ char *s; \
2396                 switch (usb_pipetype(urb->pipe)) { \
2397                 case PIPE_CONTROL: \
2398                         s = ""; \
2399                         break; \
2400                 case PIPE_BULK: \
2401                         s = "-bulk"; \
2402                         break; \
2403                 case PIPE_INTERRUPT: \
2404                         s = "-int"; \
2405                         break; \
2406                 default: \
2407                         s = "-iso"; \
2408                         break; \
2409                 } s; }),
2410                 urb->actual_length, urb->transfer_buffer_length);
2411 }
2412
2413 static ssize_t urbs_show(struct device *dev, struct device_attribute *attr,
2414                 char *buf)
2415 {
2416         struct usb_hcd          *hcd = dev_get_drvdata(dev);
2417         struct dummy_hcd        *dum_hcd = hcd_to_dummy_hcd(hcd);
2418         struct urbp             *urbp;
2419         size_t                  size = 0;
2420         unsigned long           flags;
2421
2422         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
2423         list_for_each_entry(urbp, &dum_hcd->urbp_list, urbp_list) {
2424                 size_t          temp;
2425
2426                 temp = show_urb(buf, PAGE_SIZE - size, urbp->urb);
2427                 buf += temp;
2428                 size += temp;
2429         }
2430         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
2431
2432         return size;
2433 }
2434 static DEVICE_ATTR_RO(urbs);
2435
2436 static int dummy_start_ss(struct dummy_hcd *dum_hcd)
2437 {
2438         init_timer(&dum_hcd->timer);
2439         dum_hcd->timer.function = dummy_timer;
2440         dum_hcd->timer.data = (unsigned long)dum_hcd;
2441         dum_hcd->rh_state = DUMMY_RH_RUNNING;
2442         dum_hcd->stream_en_ep = 0;
2443         INIT_LIST_HEAD(&dum_hcd->urbp_list);
2444         dummy_hcd_to_hcd(dum_hcd)->power_budget = POWER_BUDGET_3;
2445         dummy_hcd_to_hcd(dum_hcd)->state = HC_STATE_RUNNING;
2446         dummy_hcd_to_hcd(dum_hcd)->uses_new_polling = 1;
2447 #ifdef CONFIG_USB_OTG
2448         dummy_hcd_to_hcd(dum_hcd)->self.otg_port = 1;
2449 #endif
2450         return 0;
2451
2452         /* FIXME 'urbs' should be a per-device thing, maybe in usbcore */
2453         return device_create_file(dummy_dev(dum_hcd), &dev_attr_urbs);
2454 }
2455
2456 static int dummy_start(struct usb_hcd *hcd)
2457 {
2458         struct dummy_hcd        *dum_hcd = hcd_to_dummy_hcd(hcd);
2459
2460         /*
2461          * MASTER side init ... we emulate a root hub that'll only ever
2462          * talk to one device (the slave side).  Also appears in sysfs,
2463          * just like more familiar pci-based HCDs.
2464          */
2465         if (!usb_hcd_is_primary_hcd(hcd))
2466                 return dummy_start_ss(dum_hcd);
2467
2468         spin_lock_init(&dum_hcd->dum->lock);
2469         init_timer(&dum_hcd->timer);
2470         dum_hcd->timer.function = dummy_timer;
2471         dum_hcd->timer.data = (unsigned long)dum_hcd;
2472         dum_hcd->rh_state = DUMMY_RH_RUNNING;
2473
2474         INIT_LIST_HEAD(&dum_hcd->urbp_list);
2475
2476         hcd->power_budget = POWER_BUDGET;
2477         hcd->state = HC_STATE_RUNNING;
2478         hcd->uses_new_polling = 1;
2479
2480 #ifdef CONFIG_USB_OTG
2481         hcd->self.otg_port = 1;
2482 #endif
2483
2484         /* FIXME 'urbs' should be a per-device thing, maybe in usbcore */
2485         return device_create_file(dummy_dev(dum_hcd), &dev_attr_urbs);
2486 }
2487
2488 static void dummy_stop(struct usb_hcd *hcd)
2489 {
2490         device_remove_file(dummy_dev(hcd_to_dummy_hcd(hcd)), &dev_attr_urbs);
2491         dev_info(dummy_dev(hcd_to_dummy_hcd(hcd)), "stopped\n");
2492 }
2493
2494 /*-------------------------------------------------------------------------*/
2495
2496 static int dummy_h_get_frame(struct usb_hcd *hcd)
2497 {
2498         return dummy_g_get_frame(NULL);
2499 }
2500
2501 static int dummy_setup(struct usb_hcd *hcd)
2502 {
2503         struct dummy *dum;
2504
2505         dum = *((void **)dev_get_platdata(hcd->self.controller));
2506         hcd->self.sg_tablesize = ~0;
2507         if (usb_hcd_is_primary_hcd(hcd)) {
2508                 dum->hs_hcd = hcd_to_dummy_hcd(hcd);
2509                 dum->hs_hcd->dum = dum;
2510                 /*
2511                  * Mark the first roothub as being USB 2.0.
2512                  * The USB 3.0 roothub will be registered later by
2513                  * dummy_hcd_probe()
2514                  */
2515                 hcd->speed = HCD_USB2;
2516                 hcd->self.root_hub->speed = USB_SPEED_HIGH;
2517         } else {
2518                 dum->ss_hcd = hcd_to_dummy_hcd(hcd);
2519                 dum->ss_hcd->dum = dum;
2520                 hcd->speed = HCD_USB3;
2521                 hcd->self.root_hub->speed = USB_SPEED_SUPER;
2522         }
2523         return 0;
2524 }
2525
2526 /* Change a group of bulk endpoints to support multiple stream IDs */
2527 static int dummy_alloc_streams(struct usb_hcd *hcd, struct usb_device *udev,
2528         struct usb_host_endpoint **eps, unsigned int num_eps,
2529         unsigned int num_streams, gfp_t mem_flags)
2530 {
2531         struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
2532         unsigned long flags;
2533         int max_stream;
2534         int ret_streams = num_streams;
2535         unsigned int index;
2536         unsigned int i;
2537
2538         if (!num_eps)
2539                 return -EINVAL;
2540
2541         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
2542         for (i = 0; i < num_eps; i++) {
2543                 index = dummy_get_ep_idx(&eps[i]->desc);
2544                 if ((1 << index) & dum_hcd->stream_en_ep) {
2545                         ret_streams = -EINVAL;
2546                         goto out;
2547                 }
2548                 max_stream = usb_ss_max_streams(&eps[i]->ss_ep_comp);
2549                 if (!max_stream) {
2550                         ret_streams = -EINVAL;
2551                         goto out;
2552                 }
2553                 if (max_stream < ret_streams) {
2554                         dev_dbg(dummy_dev(dum_hcd), "Ep 0x%x only supports %u "
2555                                         "stream IDs.\n",
2556                                         eps[i]->desc.bEndpointAddress,
2557                                         max_stream);
2558                         ret_streams = max_stream;
2559                 }
2560         }
2561
2562         for (i = 0; i < num_eps; i++) {
2563                 index = dummy_get_ep_idx(&eps[i]->desc);
2564                 dum_hcd->stream_en_ep |= 1 << index;
2565                 set_max_streams_for_pipe(dum_hcd,
2566                                 usb_endpoint_num(&eps[i]->desc), ret_streams);
2567         }
2568 out:
2569         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
2570         return ret_streams;
2571 }
2572
2573 /* Reverts a group of bulk endpoints back to not using stream IDs. */
2574 static int dummy_free_streams(struct usb_hcd *hcd, struct usb_device *udev,
2575         struct usb_host_endpoint **eps, unsigned int num_eps,
2576         gfp_t mem_flags)
2577 {
2578         struct dummy_hcd *dum_hcd = hcd_to_dummy_hcd(hcd);
2579         unsigned long flags;
2580         int ret;
2581         unsigned int index;
2582         unsigned int i;
2583
2584         spin_lock_irqsave(&dum_hcd->dum->lock, flags);
2585         for (i = 0; i < num_eps; i++) {
2586                 index = dummy_get_ep_idx(&eps[i]->desc);
2587                 if (!((1 << index) & dum_hcd->stream_en_ep)) {
2588                         ret = -EINVAL;
2589                         goto out;
2590                 }
2591         }
2592
2593         for (i = 0; i < num_eps; i++) {
2594                 index = dummy_get_ep_idx(&eps[i]->desc);
2595                 dum_hcd->stream_en_ep &= ~(1 << index);
2596                 set_max_streams_for_pipe(dum_hcd,
2597                                 usb_endpoint_num(&eps[i]->desc), 0);
2598         }
2599         ret = 0;
2600 out:
2601         spin_unlock_irqrestore(&dum_hcd->dum->lock, flags);
2602         return ret;
2603 }
2604
2605 static struct hc_driver dummy_hcd = {
2606         .description =          (char *) driver_name,
2607         .product_desc =         "Dummy host controller",
2608         .hcd_priv_size =        sizeof(struct dummy_hcd),
2609
2610         .reset =                dummy_setup,
2611         .start =                dummy_start,
2612         .stop =                 dummy_stop,
2613
2614         .urb_enqueue =          dummy_urb_enqueue,
2615         .urb_dequeue =          dummy_urb_dequeue,
2616
2617         .get_frame_number =     dummy_h_get_frame,
2618
2619         .hub_status_data =      dummy_hub_status,
2620         .hub_control =          dummy_hub_control,
2621         .bus_suspend =          dummy_bus_suspend,
2622         .bus_resume =           dummy_bus_resume,
2623
2624         .alloc_streams =        dummy_alloc_streams,
2625         .free_streams =         dummy_free_streams,
2626 };
2627
2628 static int dummy_hcd_probe(struct platform_device *pdev)
2629 {
2630         struct dummy            *dum;
2631         struct usb_hcd          *hs_hcd;
2632         struct usb_hcd          *ss_hcd;
2633         int                     retval;
2634
2635         dev_info(&pdev->dev, "%s, driver " DRIVER_VERSION "\n", driver_desc);
2636         dum = *((void **)dev_get_platdata(&pdev->dev));
2637
2638         if (mod_data.is_super_speed)
2639                 dummy_hcd.flags = HCD_USB3 | HCD_SHARED;
2640         else if (mod_data.is_high_speed)
2641                 dummy_hcd.flags = HCD_USB2;
2642         else
2643                 dummy_hcd.flags = HCD_USB11;
2644         hs_hcd = usb_create_hcd(&dummy_hcd, &pdev->dev, dev_name(&pdev->dev));
2645         if (!hs_hcd)
2646                 return -ENOMEM;
2647         hs_hcd->has_tt = 1;
2648
2649         retval = usb_add_hcd(hs_hcd, 0, 0);
2650         if (retval)
2651                 goto put_usb2_hcd;
2652
2653         if (mod_data.is_super_speed) {
2654                 ss_hcd = usb_create_shared_hcd(&dummy_hcd, &pdev->dev,
2655                                         dev_name(&pdev->dev), hs_hcd);
2656                 if (!ss_hcd) {
2657                         retval = -ENOMEM;
2658                         goto dealloc_usb2_hcd;
2659                 }
2660
2661                 retval = usb_add_hcd(ss_hcd, 0, 0);
2662                 if (retval)
2663                         goto put_usb3_hcd;
2664         }
2665         return 0;
2666
2667 put_usb3_hcd:
2668         usb_put_hcd(ss_hcd);
2669 dealloc_usb2_hcd:
2670         usb_remove_hcd(hs_hcd);
2671 put_usb2_hcd:
2672         usb_put_hcd(hs_hcd);
2673         dum->hs_hcd = dum->ss_hcd = NULL;
2674         return retval;
2675 }
2676
2677 static int dummy_hcd_remove(struct platform_device *pdev)
2678 {
2679         struct dummy            *dum;
2680
2681         dum = hcd_to_dummy_hcd(platform_get_drvdata(pdev))->dum;
2682
2683         if (dum->ss_hcd) {
2684                 usb_remove_hcd(dummy_hcd_to_hcd(dum->ss_hcd));
2685                 usb_put_hcd(dummy_hcd_to_hcd(dum->ss_hcd));
2686         }
2687
2688         usb_remove_hcd(dummy_hcd_to_hcd(dum->hs_hcd));
2689         usb_put_hcd(dummy_hcd_to_hcd(dum->hs_hcd));
2690
2691         dum->hs_hcd = NULL;
2692         dum->ss_hcd = NULL;
2693
2694         return 0;
2695 }
2696
2697 static int dummy_hcd_suspend(struct platform_device *pdev, pm_message_t state)
2698 {
2699         struct usb_hcd          *hcd;
2700         struct dummy_hcd        *dum_hcd;
2701         int                     rc = 0;
2702
2703         dev_dbg(&pdev->dev, "%s\n", __func__);
2704
2705         hcd = platform_get_drvdata(pdev);
2706         dum_hcd = hcd_to_dummy_hcd(hcd);
2707         if (dum_hcd->rh_state == DUMMY_RH_RUNNING) {
2708                 dev_warn(&pdev->dev, "Root hub isn't suspended!\n");
2709                 rc = -EBUSY;
2710         } else
2711                 clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2712         return rc;
2713 }
2714
2715 static int dummy_hcd_resume(struct platform_device *pdev)
2716 {
2717         struct usb_hcd          *hcd;
2718
2719         dev_dbg(&pdev->dev, "%s\n", __func__);
2720
2721         hcd = platform_get_drvdata(pdev);
2722         set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2723         usb_hcd_poll_rh_status(hcd);
2724         return 0;
2725 }
2726
2727 static struct platform_driver dummy_hcd_driver = {
2728         .probe          = dummy_hcd_probe,
2729         .remove         = dummy_hcd_remove,
2730         .suspend        = dummy_hcd_suspend,
2731         .resume         = dummy_hcd_resume,
2732         .driver         = {
2733                 .name   = (char *) driver_name,
2734         },
2735 };
2736
2737 /*-------------------------------------------------------------------------*/
2738 #define MAX_NUM_UDC     2
2739 static struct platform_device *the_udc_pdev[MAX_NUM_UDC];
2740 static struct platform_device *the_hcd_pdev[MAX_NUM_UDC];
2741
2742 static int __init init(void)
2743 {
2744         int     retval = -ENOMEM;
2745         int     i;
2746         struct  dummy *dum[MAX_NUM_UDC] = {};
2747
2748         if (usb_disabled())
2749                 return -ENODEV;
2750
2751         if (!mod_data.is_high_speed && mod_data.is_super_speed)
2752                 return -EINVAL;
2753
2754         if (mod_data.num < 1 || mod_data.num > MAX_NUM_UDC) {
2755                 pr_err("Number of emulated UDC must be in range of 1...%d\n",
2756                                 MAX_NUM_UDC);
2757                 return -EINVAL;
2758         }
2759
2760         for (i = 0; i < mod_data.num; i++) {
2761                 the_hcd_pdev[i] = platform_device_alloc(driver_name, i);
2762                 if (!the_hcd_pdev[i]) {
2763                         i--;
2764                         while (i >= 0)
2765                                 platform_device_put(the_hcd_pdev[i--]);
2766                         return retval;
2767                 }
2768         }
2769         for (i = 0; i < mod_data.num; i++) {
2770                 the_udc_pdev[i] = platform_device_alloc(gadget_name, i);
2771                 if (!the_udc_pdev[i]) {
2772                         i--;
2773                         while (i >= 0)
2774                                 platform_device_put(the_udc_pdev[i--]);
2775                         goto err_alloc_udc;
2776                 }
2777         }
2778         for (i = 0; i < mod_data.num; i++) {
2779                 dum[i] = kzalloc(sizeof(struct dummy), GFP_KERNEL);
2780                 if (!dum[i]) {
2781                         retval = -ENOMEM;
2782                         goto err_add_pdata;
2783                 }
2784                 retval = platform_device_add_data(the_hcd_pdev[i], &dum[i],
2785                                 sizeof(void *));
2786                 if (retval)
2787                         goto err_add_pdata;
2788                 retval = platform_device_add_data(the_udc_pdev[i], &dum[i],
2789                                 sizeof(void *));
2790                 if (retval)
2791                         goto err_add_pdata;
2792         }
2793
2794         retval = platform_driver_register(&dummy_hcd_driver);
2795         if (retval < 0)
2796                 goto err_add_pdata;
2797         retval = platform_driver_register(&dummy_udc_driver);
2798         if (retval < 0)
2799                 goto err_register_udc_driver;
2800
2801         for (i = 0; i < mod_data.num; i++) {
2802                 retval = platform_device_add(the_hcd_pdev[i]);
2803                 if (retval < 0) {
2804                         i--;
2805                         while (i >= 0)
2806                                 platform_device_del(the_hcd_pdev[i--]);
2807                         goto err_add_hcd;
2808                 }
2809         }
2810         for (i = 0; i < mod_data.num; i++) {
2811                 if (!dum[i]->hs_hcd ||
2812                                 (!dum[i]->ss_hcd && mod_data.is_super_speed)) {
2813                         /*
2814                          * The hcd was added successfully but its probe
2815                          * function failed for some reason.
2816                          */
2817                         retval = -EINVAL;
2818                         goto err_add_udc;
2819                 }
2820         }
2821
2822         for (i = 0; i < mod_data.num; i++) {
2823                 retval = platform_device_add(the_udc_pdev[i]);
2824                 if (retval < 0) {
2825                         i--;
2826                         while (i >= 0)
2827                                 platform_device_del(the_udc_pdev[i]);
2828                         goto err_add_udc;
2829                 }
2830         }
2831
2832         for (i = 0; i < mod_data.num; i++) {
2833                 if (!platform_get_drvdata(the_udc_pdev[i])) {
2834                         /*
2835                          * The udc was added successfully but its probe
2836                          * function failed for some reason.
2837                          */
2838                         retval = -EINVAL;
2839                         goto err_probe_udc;
2840                 }
2841         }
2842         return retval;
2843
2844 err_probe_udc:
2845         for (i = 0; i < mod_data.num; i++)
2846                 platform_device_del(the_udc_pdev[i]);
2847 err_add_udc:
2848         for (i = 0; i < mod_data.num; i++)
2849                 platform_device_del(the_hcd_pdev[i]);
2850 err_add_hcd:
2851         platform_driver_unregister(&dummy_udc_driver);
2852 err_register_udc_driver:
2853         platform_driver_unregister(&dummy_hcd_driver);
2854 err_add_pdata:
2855         for (i = 0; i < mod_data.num; i++)
2856                 kfree(dum[i]);
2857         for (i = 0; i < mod_data.num; i++)
2858                 platform_device_put(the_udc_pdev[i]);
2859 err_alloc_udc:
2860         for (i = 0; i < mod_data.num; i++)
2861                 platform_device_put(the_hcd_pdev[i]);
2862         return retval;
2863 }
2864 module_init(init);
2865
2866 static void __exit cleanup(void)
2867 {
2868         int i;
2869
2870         for (i = 0; i < mod_data.num; i++) {
2871                 struct dummy *dum;
2872
2873                 dum = *((void **)dev_get_platdata(&the_udc_pdev[i]->dev));
2874
2875                 platform_device_unregister(the_udc_pdev[i]);
2876                 platform_device_unregister(the_hcd_pdev[i]);
2877                 kfree(dum);
2878         }
2879         platform_driver_unregister(&dummy_udc_driver);
2880         platform_driver_unregister(&dummy_hcd_driver);
2881 }
2882 module_exit(cleanup);