]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - drivers/usb/dwc3/gadget.c
10c6d1711ef75586a5746b88ed01ae16df4f6e52
[mirror_ubuntu-hirsute-kernel.git] / drivers / usb / dwc3 / gadget.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
4 *
5 * Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com
6 *
7 * Authors: Felipe Balbi <balbi@ti.com>,
8 * Sebastian Andrzej Siewior <bigeasy@linutronix.de>
9 */
10
11 #include <linux/kernel.h>
12 #include <linux/delay.h>
13 #include <linux/slab.h>
14 #include <linux/spinlock.h>
15 #include <linux/platform_device.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/interrupt.h>
18 #include <linux/io.h>
19 #include <linux/list.h>
20 #include <linux/dma-mapping.h>
21
22 #include <linux/usb/ch9.h>
23 #include <linux/usb/gadget.h>
24
25 #include "debug.h"
26 #include "core.h"
27 #include "gadget.h"
28 #include "io.h"
29
30 #define DWC3_ALIGN_FRAME(d, n) (((d)->frame_number + ((d)->interval * (n))) \
31 & ~((d)->interval - 1))
32
33 /**
34 * dwc3_gadget_set_test_mode - enables usb2 test modes
35 * @dwc: pointer to our context structure
36 * @mode: the mode to set (J, K SE0 NAK, Force Enable)
37 *
38 * Caller should take care of locking. This function will return 0 on
39 * success or -EINVAL if wrong Test Selector is passed.
40 */
41 int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
42 {
43 u32 reg;
44
45 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
46 reg &= ~DWC3_DCTL_TSTCTRL_MASK;
47
48 switch (mode) {
49 case USB_TEST_J:
50 case USB_TEST_K:
51 case USB_TEST_SE0_NAK:
52 case USB_TEST_PACKET:
53 case USB_TEST_FORCE_ENABLE:
54 reg |= mode << 1;
55 break;
56 default:
57 return -EINVAL;
58 }
59
60 dwc3_gadget_dctl_write_safe(dwc, reg);
61
62 return 0;
63 }
64
65 /**
66 * dwc3_gadget_get_link_state - gets current state of usb link
67 * @dwc: pointer to our context structure
68 *
69 * Caller should take care of locking. This function will
70 * return the link state on success (>= 0) or -ETIMEDOUT.
71 */
72 int dwc3_gadget_get_link_state(struct dwc3 *dwc)
73 {
74 u32 reg;
75
76 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
77
78 return DWC3_DSTS_USBLNKST(reg);
79 }
80
81 /**
82 * dwc3_gadget_set_link_state - sets usb link to a particular state
83 * @dwc: pointer to our context structure
84 * @state: the state to put link into
85 *
86 * Caller should take care of locking. This function will
87 * return 0 on success or -ETIMEDOUT.
88 */
89 int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
90 {
91 int retries = 10000;
92 u32 reg;
93
94 /*
95 * Wait until device controller is ready. Only applies to 1.94a and
96 * later RTL.
97 */
98 if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) {
99 while (--retries) {
100 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
101 if (reg & DWC3_DSTS_DCNRD)
102 udelay(5);
103 else
104 break;
105 }
106
107 if (retries <= 0)
108 return -ETIMEDOUT;
109 }
110
111 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
112 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
113
114 /* set no action before sending new link state change */
115 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
116
117 /* set requested state */
118 reg |= DWC3_DCTL_ULSTCHNGREQ(state);
119 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
120
121 /*
122 * The following code is racy when called from dwc3_gadget_wakeup,
123 * and is not needed, at least on newer versions
124 */
125 if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
126 return 0;
127
128 /* wait for a change in DSTS */
129 retries = 10000;
130 while (--retries) {
131 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
132
133 if (DWC3_DSTS_USBLNKST(reg) == state)
134 return 0;
135
136 udelay(5);
137 }
138
139 return -ETIMEDOUT;
140 }
141
142 /**
143 * dwc3_ep_inc_trb - increment a trb index.
144 * @index: Pointer to the TRB index to increment.
145 *
146 * The index should never point to the link TRB. After incrementing,
147 * if it is point to the link TRB, wrap around to the beginning. The
148 * link TRB is always at the last TRB entry.
149 */
150 static void dwc3_ep_inc_trb(u8 *index)
151 {
152 (*index)++;
153 if (*index == (DWC3_TRB_NUM - 1))
154 *index = 0;
155 }
156
157 /**
158 * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
159 * @dep: The endpoint whose enqueue pointer we're incrementing
160 */
161 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
162 {
163 dwc3_ep_inc_trb(&dep->trb_enqueue);
164 }
165
166 /**
167 * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
168 * @dep: The endpoint whose enqueue pointer we're incrementing
169 */
170 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
171 {
172 dwc3_ep_inc_trb(&dep->trb_dequeue);
173 }
174
175 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
176 struct dwc3_request *req, int status)
177 {
178 struct dwc3 *dwc = dep->dwc;
179
180 list_del(&req->list);
181 req->remaining = 0;
182 req->needs_extra_trb = false;
183
184 if (req->request.status == -EINPROGRESS)
185 req->request.status = status;
186
187 if (req->trb)
188 usb_gadget_unmap_request_by_dev(dwc->sysdev,
189 &req->request, req->direction);
190
191 req->trb = NULL;
192 trace_dwc3_gadget_giveback(req);
193
194 if (dep->number > 1)
195 pm_runtime_put(dwc->dev);
196 }
197
198 /**
199 * dwc3_gadget_giveback - call struct usb_request's ->complete callback
200 * @dep: The endpoint to whom the request belongs to
201 * @req: The request we're giving back
202 * @status: completion code for the request
203 *
204 * Must be called with controller's lock held and interrupts disabled. This
205 * function will unmap @req and call its ->complete() callback to notify upper
206 * layers that it has completed.
207 */
208 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
209 int status)
210 {
211 struct dwc3 *dwc = dep->dwc;
212
213 dwc3_gadget_del_and_unmap_request(dep, req, status);
214 req->status = DWC3_REQUEST_STATUS_COMPLETED;
215
216 spin_unlock(&dwc->lock);
217 usb_gadget_giveback_request(&dep->endpoint, &req->request);
218 spin_lock(&dwc->lock);
219 }
220
221 /**
222 * dwc3_send_gadget_generic_command - issue a generic command for the controller
223 * @dwc: pointer to the controller context
224 * @cmd: the command to be issued
225 * @param: command parameter
226 *
227 * Caller should take care of locking. Issue @cmd with a given @param to @dwc
228 * and wait for its completion.
229 */
230 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
231 u32 param)
232 {
233 u32 timeout = 500;
234 int status = 0;
235 int ret = 0;
236 u32 reg;
237
238 dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
239 dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
240
241 do {
242 reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
243 if (!(reg & DWC3_DGCMD_CMDACT)) {
244 status = DWC3_DGCMD_STATUS(reg);
245 if (status)
246 ret = -EINVAL;
247 break;
248 }
249 } while (--timeout);
250
251 if (!timeout) {
252 ret = -ETIMEDOUT;
253 status = -ETIMEDOUT;
254 }
255
256 trace_dwc3_gadget_generic_cmd(cmd, param, status);
257
258 return ret;
259 }
260
261 static int __dwc3_gadget_wakeup(struct dwc3 *dwc);
262
263 /**
264 * dwc3_send_gadget_ep_cmd - issue an endpoint command
265 * @dep: the endpoint to which the command is going to be issued
266 * @cmd: the command to be issued
267 * @params: parameters to the command
268 *
269 * Caller should handle locking. This function will issue @cmd with given
270 * @params to @dep and wait for its completion.
271 */
272 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd,
273 struct dwc3_gadget_ep_cmd_params *params)
274 {
275 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
276 struct dwc3 *dwc = dep->dwc;
277 u32 timeout = 5000;
278 u32 saved_config = 0;
279 u32 reg;
280
281 int cmd_status = 0;
282 int ret = -EINVAL;
283
284 /*
285 * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or
286 * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an
287 * endpoint command.
288 *
289 * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY
290 * settings. Restore them after the command is completed.
291 *
292 * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2
293 */
294 if (dwc->gadget->speed <= USB_SPEED_HIGH) {
295 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
296 if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
297 saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
298 reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
299 }
300
301 if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
302 saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
303 reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
304 }
305
306 if (saved_config)
307 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
308 }
309
310 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
311 int link_state;
312
313 link_state = dwc3_gadget_get_link_state(dwc);
314 if (link_state == DWC3_LINK_STATE_U1 ||
315 link_state == DWC3_LINK_STATE_U2 ||
316 link_state == DWC3_LINK_STATE_U3) {
317 ret = __dwc3_gadget_wakeup(dwc);
318 dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
319 ret);
320 }
321 }
322
323 dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
324 dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
325 dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
326
327 /*
328 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
329 * not relying on XferNotReady, we can make use of a special "No
330 * Response Update Transfer" command where we should clear both CmdAct
331 * and CmdIOC bits.
332 *
333 * With this, we don't need to wait for command completion and can
334 * straight away issue further commands to the endpoint.
335 *
336 * NOTICE: We're making an assumption that control endpoints will never
337 * make use of Update Transfer command. This is a safe assumption
338 * because we can never have more than one request at a time with
339 * Control Endpoints. If anybody changes that assumption, this chunk
340 * needs to be updated accordingly.
341 */
342 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
343 !usb_endpoint_xfer_isoc(desc))
344 cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
345 else
346 cmd |= DWC3_DEPCMD_CMDACT;
347
348 dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
349 do {
350 reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
351 if (!(reg & DWC3_DEPCMD_CMDACT)) {
352 cmd_status = DWC3_DEPCMD_STATUS(reg);
353
354 switch (cmd_status) {
355 case 0:
356 ret = 0;
357 break;
358 case DEPEVT_TRANSFER_NO_RESOURCE:
359 dev_WARN(dwc->dev, "No resource for %s\n",
360 dep->name);
361 ret = -EINVAL;
362 break;
363 case DEPEVT_TRANSFER_BUS_EXPIRY:
364 /*
365 * SW issues START TRANSFER command to
366 * isochronous ep with future frame interval. If
367 * future interval time has already passed when
368 * core receives the command, it will respond
369 * with an error status of 'Bus Expiry'.
370 *
371 * Instead of always returning -EINVAL, let's
372 * give a hint to the gadget driver that this is
373 * the case by returning -EAGAIN.
374 */
375 ret = -EAGAIN;
376 break;
377 default:
378 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
379 }
380
381 break;
382 }
383 } while (--timeout);
384
385 if (timeout == 0) {
386 ret = -ETIMEDOUT;
387 cmd_status = -ETIMEDOUT;
388 }
389
390 trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
391
392 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
393 if (ret == 0)
394 dep->flags |= DWC3_EP_TRANSFER_STARTED;
395
396 if (ret != -ETIMEDOUT)
397 dwc3_gadget_ep_get_transfer_index(dep);
398 }
399
400 if (saved_config) {
401 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
402 reg |= saved_config;
403 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
404 }
405
406 return ret;
407 }
408
409 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
410 {
411 struct dwc3 *dwc = dep->dwc;
412 struct dwc3_gadget_ep_cmd_params params;
413 u32 cmd = DWC3_DEPCMD_CLEARSTALL;
414
415 /*
416 * As of core revision 2.60a the recommended programming model
417 * is to set the ClearPendIN bit when issuing a Clear Stall EP
418 * command for IN endpoints. This is to prevent an issue where
419 * some (non-compliant) hosts may not send ACK TPs for pending
420 * IN transfers due to a mishandled error condition. Synopsys
421 * STAR 9000614252.
422 */
423 if (dep->direction &&
424 !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
425 (dwc->gadget->speed >= USB_SPEED_SUPER))
426 cmd |= DWC3_DEPCMD_CLEARPENDIN;
427
428 memset(&params, 0, sizeof(params));
429
430 return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
431 }
432
433 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
434 struct dwc3_trb *trb)
435 {
436 u32 offset = (char *) trb - (char *) dep->trb_pool;
437
438 return dep->trb_pool_dma + offset;
439 }
440
441 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
442 {
443 struct dwc3 *dwc = dep->dwc;
444
445 if (dep->trb_pool)
446 return 0;
447
448 dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
449 sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
450 &dep->trb_pool_dma, GFP_KERNEL);
451 if (!dep->trb_pool) {
452 dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
453 dep->name);
454 return -ENOMEM;
455 }
456
457 return 0;
458 }
459
460 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
461 {
462 struct dwc3 *dwc = dep->dwc;
463
464 dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
465 dep->trb_pool, dep->trb_pool_dma);
466
467 dep->trb_pool = NULL;
468 dep->trb_pool_dma = 0;
469 }
470
471 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
472 {
473 struct dwc3_gadget_ep_cmd_params params;
474
475 memset(&params, 0x00, sizeof(params));
476
477 params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
478
479 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
480 &params);
481 }
482
483 /**
484 * dwc3_gadget_start_config - configure ep resources
485 * @dep: endpoint that is being enabled
486 *
487 * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
488 * completion, it will set Transfer Resource for all available endpoints.
489 *
490 * The assignment of transfer resources cannot perfectly follow the data book
491 * due to the fact that the controller driver does not have all knowledge of the
492 * configuration in advance. It is given this information piecemeal by the
493 * composite gadget framework after every SET_CONFIGURATION and
494 * SET_INTERFACE. Trying to follow the databook programming model in this
495 * scenario can cause errors. For two reasons:
496 *
497 * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
498 * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
499 * incorrect in the scenario of multiple interfaces.
500 *
501 * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
502 * endpoint on alt setting (8.1.6).
503 *
504 * The following simplified method is used instead:
505 *
506 * All hardware endpoints can be assigned a transfer resource and this setting
507 * will stay persistent until either a core reset or hibernation. So whenever we
508 * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
509 * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
510 * guaranteed that there are as many transfer resources as endpoints.
511 *
512 * This function is called for each endpoint when it is being enabled but is
513 * triggered only when called for EP0-out, which always happens first, and which
514 * should only happen in one of the above conditions.
515 */
516 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
517 {
518 struct dwc3_gadget_ep_cmd_params params;
519 struct dwc3 *dwc;
520 u32 cmd;
521 int i;
522 int ret;
523
524 if (dep->number)
525 return 0;
526
527 memset(&params, 0x00, sizeof(params));
528 cmd = DWC3_DEPCMD_DEPSTARTCFG;
529 dwc = dep->dwc;
530
531 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
532 if (ret)
533 return ret;
534
535 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
536 struct dwc3_ep *dep = dwc->eps[i];
537
538 if (!dep)
539 continue;
540
541 ret = dwc3_gadget_set_xfer_resource(dep);
542 if (ret)
543 return ret;
544 }
545
546 return 0;
547 }
548
549 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
550 {
551 const struct usb_ss_ep_comp_descriptor *comp_desc;
552 const struct usb_endpoint_descriptor *desc;
553 struct dwc3_gadget_ep_cmd_params params;
554 struct dwc3 *dwc = dep->dwc;
555
556 comp_desc = dep->endpoint.comp_desc;
557 desc = dep->endpoint.desc;
558
559 memset(&params, 0x00, sizeof(params));
560
561 params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
562 | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
563
564 /* Burst size is only needed in SuperSpeed mode */
565 if (dwc->gadget->speed >= USB_SPEED_SUPER) {
566 u32 burst = dep->endpoint.maxburst;
567
568 params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
569 }
570
571 params.param0 |= action;
572 if (action == DWC3_DEPCFG_ACTION_RESTORE)
573 params.param2 |= dep->saved_state;
574
575 if (usb_endpoint_xfer_control(desc))
576 params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
577
578 if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
579 params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
580
581 if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
582 params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
583 | DWC3_DEPCFG_XFER_COMPLETE_EN
584 | DWC3_DEPCFG_STREAM_EVENT_EN;
585 dep->stream_capable = true;
586 }
587
588 if (!usb_endpoint_xfer_control(desc))
589 params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
590
591 /*
592 * We are doing 1:1 mapping for endpoints, meaning
593 * Physical Endpoints 2 maps to Logical Endpoint 2 and
594 * so on. We consider the direction bit as part of the physical
595 * endpoint number. So USB endpoint 0x81 is 0x03.
596 */
597 params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
598
599 /*
600 * We must use the lower 16 TX FIFOs even though
601 * HW might have more
602 */
603 if (dep->direction)
604 params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
605
606 if (desc->bInterval) {
607 u8 bInterval_m1;
608
609 /*
610 * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
611 *
612 * NOTE: The programming guide incorrectly stated bInterval_m1
613 * must be set to 0 when operating in fullspeed. Internally the
614 * controller does not have this limitation. See DWC_usb3x
615 * programming guide section 3.2.2.1.
616 */
617 bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
618
619 if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
620 dwc->gadget->speed == USB_SPEED_FULL)
621 dep->interval = desc->bInterval;
622 else
623 dep->interval = 1 << (desc->bInterval - 1);
624
625 params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
626 }
627
628 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
629 }
630
631 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
632 bool interrupt);
633
634 /**
635 * __dwc3_gadget_ep_enable - initializes a hw endpoint
636 * @dep: endpoint to be initialized
637 * @action: one of INIT, MODIFY or RESTORE
638 *
639 * Caller should take care of locking. Execute all necessary commands to
640 * initialize a HW endpoint so it can be used by a gadget driver.
641 */
642 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
643 {
644 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
645 struct dwc3 *dwc = dep->dwc;
646
647 u32 reg;
648 int ret;
649
650 if (!(dep->flags & DWC3_EP_ENABLED)) {
651 ret = dwc3_gadget_start_config(dep);
652 if (ret)
653 return ret;
654 }
655
656 ret = dwc3_gadget_set_ep_config(dep, action);
657 if (ret)
658 return ret;
659
660 if (!(dep->flags & DWC3_EP_ENABLED)) {
661 struct dwc3_trb *trb_st_hw;
662 struct dwc3_trb *trb_link;
663
664 dep->type = usb_endpoint_type(desc);
665 dep->flags |= DWC3_EP_ENABLED;
666
667 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
668 reg |= DWC3_DALEPENA_EP(dep->number);
669 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
670
671 if (usb_endpoint_xfer_control(desc))
672 goto out;
673
674 /* Initialize the TRB ring */
675 dep->trb_dequeue = 0;
676 dep->trb_enqueue = 0;
677 memset(dep->trb_pool, 0,
678 sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
679
680 /* Link TRB. The HWO bit is never reset */
681 trb_st_hw = &dep->trb_pool[0];
682
683 trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
684 trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
685 trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
686 trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
687 trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
688 }
689
690 /*
691 * Issue StartTransfer here with no-op TRB so we can always rely on No
692 * Response Update Transfer command.
693 */
694 if (usb_endpoint_xfer_bulk(desc) ||
695 usb_endpoint_xfer_int(desc)) {
696 struct dwc3_gadget_ep_cmd_params params;
697 struct dwc3_trb *trb;
698 dma_addr_t trb_dma;
699 u32 cmd;
700
701 memset(&params, 0, sizeof(params));
702 trb = &dep->trb_pool[0];
703 trb_dma = dwc3_trb_dma_offset(dep, trb);
704
705 params.param0 = upper_32_bits(trb_dma);
706 params.param1 = lower_32_bits(trb_dma);
707
708 cmd = DWC3_DEPCMD_STARTTRANSFER;
709
710 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
711 if (ret < 0)
712 return ret;
713
714 if (dep->stream_capable) {
715 /*
716 * For streams, at start, there maybe a race where the
717 * host primes the endpoint before the function driver
718 * queues a request to initiate a stream. In that case,
719 * the controller will not see the prime to generate the
720 * ERDY and start stream. To workaround this, issue a
721 * no-op TRB as normal, but end it immediately. As a
722 * result, when the function driver queues the request,
723 * the next START_TRANSFER command will cause the
724 * controller to generate an ERDY to initiate the
725 * stream.
726 */
727 dwc3_stop_active_transfer(dep, true, true);
728
729 /*
730 * All stream eps will reinitiate stream on NoStream
731 * rejection until we can determine that the host can
732 * prime after the first transfer.
733 */
734 dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
735 }
736 }
737
738 out:
739 trace_dwc3_gadget_ep_enable(dep);
740
741 return 0;
742 }
743
744 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
745 {
746 struct dwc3_request *req;
747
748 dwc3_stop_active_transfer(dep, true, false);
749
750 /* - giveback all requests to gadget driver */
751 while (!list_empty(&dep->started_list)) {
752 req = next_request(&dep->started_list);
753
754 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
755 }
756
757 while (!list_empty(&dep->pending_list)) {
758 req = next_request(&dep->pending_list);
759
760 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
761 }
762
763 while (!list_empty(&dep->cancelled_list)) {
764 req = next_request(&dep->cancelled_list);
765
766 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
767 }
768 }
769
770 /**
771 * __dwc3_gadget_ep_disable - disables a hw endpoint
772 * @dep: the endpoint to disable
773 *
774 * This function undoes what __dwc3_gadget_ep_enable did and also removes
775 * requests which are currently being processed by the hardware and those which
776 * are not yet scheduled.
777 *
778 * Caller should take care of locking.
779 */
780 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
781 {
782 struct dwc3 *dwc = dep->dwc;
783 u32 reg;
784
785 trace_dwc3_gadget_ep_disable(dep);
786
787 /* make sure HW endpoint isn't stalled */
788 if (dep->flags & DWC3_EP_STALL)
789 __dwc3_gadget_ep_set_halt(dep, 0, false);
790
791 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
792 reg &= ~DWC3_DALEPENA_EP(dep->number);
793 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
794
795 /* Clear out the ep descriptors for non-ep0 */
796 if (dep->number > 1) {
797 dep->endpoint.comp_desc = NULL;
798 dep->endpoint.desc = NULL;
799 }
800
801 dwc3_remove_requests(dwc, dep);
802
803 dep->stream_capable = false;
804 dep->type = 0;
805 dep->flags = 0;
806
807 return 0;
808 }
809
810 /* -------------------------------------------------------------------------- */
811
812 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
813 const struct usb_endpoint_descriptor *desc)
814 {
815 return -EINVAL;
816 }
817
818 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
819 {
820 return -EINVAL;
821 }
822
823 /* -------------------------------------------------------------------------- */
824
825 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
826 const struct usb_endpoint_descriptor *desc)
827 {
828 struct dwc3_ep *dep;
829 struct dwc3 *dwc;
830 unsigned long flags;
831 int ret;
832
833 if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
834 pr_debug("dwc3: invalid parameters\n");
835 return -EINVAL;
836 }
837
838 if (!desc->wMaxPacketSize) {
839 pr_debug("dwc3: missing wMaxPacketSize\n");
840 return -EINVAL;
841 }
842
843 dep = to_dwc3_ep(ep);
844 dwc = dep->dwc;
845
846 if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
847 "%s is already enabled\n",
848 dep->name))
849 return 0;
850
851 spin_lock_irqsave(&dwc->lock, flags);
852 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
853 spin_unlock_irqrestore(&dwc->lock, flags);
854
855 return ret;
856 }
857
858 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
859 {
860 struct dwc3_ep *dep;
861 struct dwc3 *dwc;
862 unsigned long flags;
863 int ret;
864
865 if (!ep) {
866 pr_debug("dwc3: invalid parameters\n");
867 return -EINVAL;
868 }
869
870 dep = to_dwc3_ep(ep);
871 dwc = dep->dwc;
872
873 if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
874 "%s is already disabled\n",
875 dep->name))
876 return 0;
877
878 spin_lock_irqsave(&dwc->lock, flags);
879 ret = __dwc3_gadget_ep_disable(dep);
880 spin_unlock_irqrestore(&dwc->lock, flags);
881
882 return ret;
883 }
884
885 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
886 gfp_t gfp_flags)
887 {
888 struct dwc3_request *req;
889 struct dwc3_ep *dep = to_dwc3_ep(ep);
890
891 req = kzalloc(sizeof(*req), gfp_flags);
892 if (!req)
893 return NULL;
894
895 req->direction = dep->direction;
896 req->epnum = dep->number;
897 req->dep = dep;
898 req->status = DWC3_REQUEST_STATUS_UNKNOWN;
899
900 trace_dwc3_alloc_request(req);
901
902 return &req->request;
903 }
904
905 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
906 struct usb_request *request)
907 {
908 struct dwc3_request *req = to_dwc3_request(request);
909
910 trace_dwc3_free_request(req);
911 kfree(req);
912 }
913
914 /**
915 * dwc3_ep_prev_trb - returns the previous TRB in the ring
916 * @dep: The endpoint with the TRB ring
917 * @index: The index of the current TRB in the ring
918 *
919 * Returns the TRB prior to the one pointed to by the index. If the
920 * index is 0, we will wrap backwards, skip the link TRB, and return
921 * the one just before that.
922 */
923 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
924 {
925 u8 tmp = index;
926
927 if (!tmp)
928 tmp = DWC3_TRB_NUM - 1;
929
930 return &dep->trb_pool[tmp - 1];
931 }
932
933 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
934 {
935 struct dwc3_trb *tmp;
936 u8 trbs_left;
937
938 /*
939 * If enqueue & dequeue are equal than it is either full or empty.
940 *
941 * One way to know for sure is if the TRB right before us has HWO bit
942 * set or not. If it has, then we're definitely full and can't fit any
943 * more transfers in our ring.
944 */
945 if (dep->trb_enqueue == dep->trb_dequeue) {
946 tmp = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
947 if (tmp->ctrl & DWC3_TRB_CTRL_HWO)
948 return 0;
949
950 return DWC3_TRB_NUM - 1;
951 }
952
953 trbs_left = dep->trb_dequeue - dep->trb_enqueue;
954 trbs_left &= (DWC3_TRB_NUM - 1);
955
956 if (dep->trb_dequeue < dep->trb_enqueue)
957 trbs_left--;
958
959 return trbs_left;
960 }
961
962 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
963 dma_addr_t dma, unsigned int length, unsigned int chain,
964 unsigned int node, unsigned int stream_id,
965 unsigned int short_not_ok, unsigned int no_interrupt,
966 unsigned int is_last, bool must_interrupt)
967 {
968 struct dwc3 *dwc = dep->dwc;
969 struct usb_gadget *gadget = dwc->gadget;
970 enum usb_device_speed speed = gadget->speed;
971
972 trb->size = DWC3_TRB_SIZE_LENGTH(length);
973 trb->bpl = lower_32_bits(dma);
974 trb->bph = upper_32_bits(dma);
975
976 switch (usb_endpoint_type(dep->endpoint.desc)) {
977 case USB_ENDPOINT_XFER_CONTROL:
978 trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
979 break;
980
981 case USB_ENDPOINT_XFER_ISOC:
982 if (!node) {
983 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
984
985 /*
986 * USB Specification 2.0 Section 5.9.2 states that: "If
987 * there is only a single transaction in the microframe,
988 * only a DATA0 data packet PID is used. If there are
989 * two transactions per microframe, DATA1 is used for
990 * the first transaction data packet and DATA0 is used
991 * for the second transaction data packet. If there are
992 * three transactions per microframe, DATA2 is used for
993 * the first transaction data packet, DATA1 is used for
994 * the second, and DATA0 is used for the third."
995 *
996 * IOW, we should satisfy the following cases:
997 *
998 * 1) length <= maxpacket
999 * - DATA0
1000 *
1001 * 2) maxpacket < length <= (2 * maxpacket)
1002 * - DATA1, DATA0
1003 *
1004 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1005 * - DATA2, DATA1, DATA0
1006 */
1007 if (speed == USB_SPEED_HIGH) {
1008 struct usb_ep *ep = &dep->endpoint;
1009 unsigned int mult = 2;
1010 unsigned int maxp = usb_endpoint_maxp(ep->desc);
1011
1012 if (length <= (2 * maxp))
1013 mult--;
1014
1015 if (length <= maxp)
1016 mult--;
1017
1018 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1019 }
1020 } else {
1021 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1022 }
1023
1024 /* always enable Interrupt on Missed ISOC */
1025 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1026 break;
1027
1028 case USB_ENDPOINT_XFER_BULK:
1029 case USB_ENDPOINT_XFER_INT:
1030 trb->ctrl = DWC3_TRBCTL_NORMAL;
1031 break;
1032 default:
1033 /*
1034 * This is only possible with faulty memory because we
1035 * checked it already :)
1036 */
1037 dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1038 usb_endpoint_type(dep->endpoint.desc));
1039 }
1040
1041 /*
1042 * Enable Continue on Short Packet
1043 * when endpoint is not a stream capable
1044 */
1045 if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1046 if (!dep->stream_capable)
1047 trb->ctrl |= DWC3_TRB_CTRL_CSP;
1048
1049 if (short_not_ok)
1050 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1051 }
1052
1053 if ((!no_interrupt && !chain) || must_interrupt)
1054 trb->ctrl |= DWC3_TRB_CTRL_IOC;
1055
1056 if (chain)
1057 trb->ctrl |= DWC3_TRB_CTRL_CHN;
1058 else if (dep->stream_capable && is_last)
1059 trb->ctrl |= DWC3_TRB_CTRL_LST;
1060
1061 if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1062 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1063
1064 trb->ctrl |= DWC3_TRB_CTRL_HWO;
1065
1066 dwc3_ep_inc_enq(dep);
1067
1068 trace_dwc3_prepare_trb(dep, trb);
1069 }
1070
1071 /**
1072 * dwc3_prepare_one_trb - setup one TRB from one request
1073 * @dep: endpoint for which this request is prepared
1074 * @req: dwc3_request pointer
1075 * @trb_length: buffer size of the TRB
1076 * @chain: should this TRB be chained to the next?
1077 * @node: only for isochronous endpoints. First TRB needs different type.
1078 * @use_bounce_buffer: set to use bounce buffer
1079 * @must_interrupt: set to interrupt on TRB completion
1080 */
1081 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1082 struct dwc3_request *req, unsigned int trb_length,
1083 unsigned int chain, unsigned int node, bool use_bounce_buffer,
1084 bool must_interrupt)
1085 {
1086 struct dwc3_trb *trb;
1087 dma_addr_t dma;
1088 unsigned int stream_id = req->request.stream_id;
1089 unsigned int short_not_ok = req->request.short_not_ok;
1090 unsigned int no_interrupt = req->request.no_interrupt;
1091 unsigned int is_last = req->request.is_last;
1092
1093 if (use_bounce_buffer)
1094 dma = dep->dwc->bounce_addr;
1095 else if (req->request.num_sgs > 0)
1096 dma = sg_dma_address(req->start_sg);
1097 else
1098 dma = req->request.dma;
1099
1100 trb = &dep->trb_pool[dep->trb_enqueue];
1101
1102 if (!req->trb) {
1103 dwc3_gadget_move_started_request(req);
1104 req->trb = trb;
1105 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1106 }
1107
1108 req->num_trbs++;
1109
1110 __dwc3_prepare_one_trb(dep, trb, dma, trb_length, chain, node,
1111 stream_id, short_not_ok, no_interrupt, is_last,
1112 must_interrupt);
1113 }
1114
1115 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1116 {
1117 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1118 unsigned int rem = req->request.length % maxp;
1119
1120 if ((req->request.length && req->request.zero && !rem &&
1121 !usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1122 (!req->direction && rem))
1123 return true;
1124
1125 return false;
1126 }
1127
1128 /**
1129 * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1130 * @dep: The endpoint that the request belongs to
1131 * @req: The request to prepare
1132 * @entry_length: The last SG entry size
1133 * @node: Indicates whether this is not the first entry (for isoc only)
1134 *
1135 * Return the number of TRBs prepared.
1136 */
1137 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1138 struct dwc3_request *req, unsigned int entry_length,
1139 unsigned int node)
1140 {
1141 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1142 unsigned int rem = req->request.length % maxp;
1143 unsigned int num_trbs = 1;
1144
1145 if (dwc3_needs_extra_trb(dep, req))
1146 num_trbs++;
1147
1148 if (dwc3_calc_trbs_left(dep) < num_trbs)
1149 return 0;
1150
1151 req->needs_extra_trb = num_trbs > 1;
1152
1153 /* Prepare a normal TRB */
1154 if (req->direction || req->request.length)
1155 dwc3_prepare_one_trb(dep, req, entry_length,
1156 req->needs_extra_trb, node, false, false);
1157
1158 /* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1159 if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1160 dwc3_prepare_one_trb(dep, req,
1161 req->direction ? 0 : maxp - rem,
1162 false, 1, true, false);
1163
1164 return num_trbs;
1165 }
1166
1167 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1168 struct dwc3_request *req)
1169 {
1170 struct scatterlist *sg = req->start_sg;
1171 struct scatterlist *s;
1172 int i;
1173 unsigned int length = req->request.length;
1174 unsigned int remaining = req->request.num_mapped_sgs
1175 - req->num_queued_sgs;
1176 unsigned int num_trbs = req->num_trbs;
1177 bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1178
1179 /*
1180 * If we resume preparing the request, then get the remaining length of
1181 * the request and resume where we left off.
1182 */
1183 for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1184 length -= sg_dma_len(s);
1185
1186 for_each_sg(sg, s, remaining, i) {
1187 unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1188 unsigned int trb_length;
1189 bool must_interrupt = false;
1190 bool last_sg = false;
1191
1192 trb_length = min_t(unsigned int, length, sg_dma_len(s));
1193
1194 length -= trb_length;
1195
1196 /*
1197 * IOMMU driver is coalescing the list of sgs which shares a
1198 * page boundary into one and giving it to USB driver. With
1199 * this the number of sgs mapped is not equal to the number of
1200 * sgs passed. So mark the chain bit to false if it isthe last
1201 * mapped sg.
1202 */
1203 if ((i == remaining - 1) || !length)
1204 last_sg = true;
1205
1206 if (!num_trbs_left)
1207 break;
1208
1209 if (last_sg) {
1210 if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1211 break;
1212 } else {
1213 /*
1214 * Look ahead to check if we have enough TRBs for the
1215 * next SG entry. If not, set interrupt on this TRB to
1216 * resume preparing the next SG entry when more TRBs are
1217 * free.
1218 */
1219 if (num_trbs_left == 1 || (needs_extra_trb &&
1220 num_trbs_left <= 2 &&
1221 sg_dma_len(sg_next(s)) >= length))
1222 must_interrupt = true;
1223
1224 dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1225 must_interrupt);
1226 }
1227
1228 /*
1229 * There can be a situation where all sgs in sglist are not
1230 * queued because of insufficient trb number. To handle this
1231 * case, update start_sg to next sg to be queued, so that
1232 * we have free trbs we can continue queuing from where we
1233 * previously stopped
1234 */
1235 if (!last_sg)
1236 req->start_sg = sg_next(s);
1237
1238 req->num_queued_sgs++;
1239 req->num_pending_sgs--;
1240
1241 /*
1242 * The number of pending SG entries may not correspond to the
1243 * number of mapped SG entries. If all the data are queued, then
1244 * don't include unused SG entries.
1245 */
1246 if (length == 0) {
1247 req->num_pending_sgs = 0;
1248 break;
1249 }
1250
1251 if (must_interrupt)
1252 break;
1253 }
1254
1255 return req->num_trbs - num_trbs;
1256 }
1257
1258 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1259 struct dwc3_request *req)
1260 {
1261 return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1262 }
1263
1264 /*
1265 * dwc3_prepare_trbs - setup TRBs from requests
1266 * @dep: endpoint for which requests are being prepared
1267 *
1268 * The function goes through the requests list and sets up TRBs for the
1269 * transfers. The function returns once there are no more TRBs available or
1270 * it runs out of requests.
1271 *
1272 * Returns the number of TRBs prepared or negative errno.
1273 */
1274 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1275 {
1276 struct dwc3_request *req, *n;
1277 int ret = 0;
1278
1279 BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1280
1281 /*
1282 * We can get in a situation where there's a request in the started list
1283 * but there weren't enough TRBs to fully kick it in the first time
1284 * around, so it has been waiting for more TRBs to be freed up.
1285 *
1286 * In that case, we should check if we have a request with pending_sgs
1287 * in the started list and prepare TRBs for that request first,
1288 * otherwise we will prepare TRBs completely out of order and that will
1289 * break things.
1290 */
1291 list_for_each_entry(req, &dep->started_list, list) {
1292 if (req->num_pending_sgs > 0) {
1293 ret = dwc3_prepare_trbs_sg(dep, req);
1294 if (!ret || req->num_pending_sgs)
1295 return ret;
1296 }
1297
1298 if (!dwc3_calc_trbs_left(dep))
1299 return ret;
1300
1301 /*
1302 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1303 * burst capability may try to read and use TRBs beyond the
1304 * active transfer instead of stopping.
1305 */
1306 if (dep->stream_capable && req->request.is_last)
1307 return ret;
1308 }
1309
1310 list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1311 struct dwc3 *dwc = dep->dwc;
1312
1313 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1314 dep->direction);
1315 if (ret)
1316 return ret;
1317
1318 req->sg = req->request.sg;
1319 req->start_sg = req->sg;
1320 req->num_queued_sgs = 0;
1321 req->num_pending_sgs = req->request.num_mapped_sgs;
1322
1323 if (req->num_pending_sgs > 0) {
1324 ret = dwc3_prepare_trbs_sg(dep, req);
1325 if (req->num_pending_sgs)
1326 return ret;
1327 } else {
1328 ret = dwc3_prepare_trbs_linear(dep, req);
1329 }
1330
1331 if (!ret || !dwc3_calc_trbs_left(dep))
1332 return ret;
1333
1334 /*
1335 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1336 * burst capability may try to read and use TRBs beyond the
1337 * active transfer instead of stopping.
1338 */
1339 if (dep->stream_capable && req->request.is_last)
1340 return ret;
1341 }
1342
1343 return ret;
1344 }
1345
1346 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1347
1348 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1349 {
1350 struct dwc3_gadget_ep_cmd_params params;
1351 struct dwc3_request *req;
1352 int starting;
1353 int ret;
1354 u32 cmd;
1355
1356 /*
1357 * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1358 * This happens when we need to stop and restart a transfer such as in
1359 * the case of reinitiating a stream or retrying an isoc transfer.
1360 */
1361 ret = dwc3_prepare_trbs(dep);
1362 if (ret < 0)
1363 return ret;
1364
1365 starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1366
1367 /*
1368 * If there's no new TRB prepared and we don't need to restart a
1369 * transfer, there's no need to update the transfer.
1370 */
1371 if (!ret && !starting)
1372 return ret;
1373
1374 req = next_request(&dep->started_list);
1375 if (!req) {
1376 dep->flags |= DWC3_EP_PENDING_REQUEST;
1377 return 0;
1378 }
1379
1380 memset(&params, 0, sizeof(params));
1381
1382 if (starting) {
1383 params.param0 = upper_32_bits(req->trb_dma);
1384 params.param1 = lower_32_bits(req->trb_dma);
1385 cmd = DWC3_DEPCMD_STARTTRANSFER;
1386
1387 if (dep->stream_capable)
1388 cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1389
1390 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1391 cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1392 } else {
1393 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1394 DWC3_DEPCMD_PARAM(dep->resource_index);
1395 }
1396
1397 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1398 if (ret < 0) {
1399 struct dwc3_request *tmp;
1400
1401 if (ret == -EAGAIN)
1402 return ret;
1403
1404 dwc3_stop_active_transfer(dep, true, true);
1405
1406 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1407 dwc3_gadget_move_cancelled_request(req);
1408
1409 /* If ep isn't started, then there's no end transfer pending */
1410 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1411 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1412
1413 return ret;
1414 }
1415
1416 if (dep->stream_capable && req->request.is_last)
1417 dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1418
1419 return 0;
1420 }
1421
1422 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1423 {
1424 u32 reg;
1425
1426 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1427 return DWC3_DSTS_SOFFN(reg);
1428 }
1429
1430 /**
1431 * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1432 * @dep: isoc endpoint
1433 *
1434 * This function tests for the correct combination of BIT[15:14] from the 16-bit
1435 * microframe number reported by the XferNotReady event for the future frame
1436 * number to start the isoc transfer.
1437 *
1438 * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1439 * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1440 * XferNotReady event are invalid. The driver uses this number to schedule the
1441 * isochronous transfer and passes it to the START TRANSFER command. Because
1442 * this number is invalid, the command may fail. If BIT[15:14] matches the
1443 * internal 16-bit microframe, the START TRANSFER command will pass and the
1444 * transfer will start at the scheduled time, if it is off by 1, the command
1445 * will still pass, but the transfer will start 2 seconds in the future. For all
1446 * other conditions, the START TRANSFER command will fail with bus-expiry.
1447 *
1448 * In order to workaround this issue, we can test for the correct combination of
1449 * BIT[15:14] by sending START TRANSFER commands with different values of
1450 * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1451 * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1452 * As the result, within the 4 possible combinations for BIT[15:14], there will
1453 * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1454 * command status will result in a 2-second delay start. The smaller BIT[15:14]
1455 * value is the correct combination.
1456 *
1457 * Since there are only 4 outcomes and the results are ordered, we can simply
1458 * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1459 * deduce the smaller successful combination.
1460 *
1461 * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1462 * of BIT[15:14]. The correct combination is as follow:
1463 *
1464 * if test0 fails and test1 passes, BIT[15:14] is 'b01
1465 * if test0 fails and test1 fails, BIT[15:14] is 'b10
1466 * if test0 passes and test1 fails, BIT[15:14] is 'b11
1467 * if test0 passes and test1 passes, BIT[15:14] is 'b00
1468 *
1469 * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1470 * endpoints.
1471 */
1472 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1473 {
1474 int cmd_status = 0;
1475 bool test0;
1476 bool test1;
1477
1478 while (dep->combo_num < 2) {
1479 struct dwc3_gadget_ep_cmd_params params;
1480 u32 test_frame_number;
1481 u32 cmd;
1482
1483 /*
1484 * Check if we can start isoc transfer on the next interval or
1485 * 4 uframes in the future with BIT[15:14] as dep->combo_num
1486 */
1487 test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1488 test_frame_number |= dep->combo_num << 14;
1489 test_frame_number += max_t(u32, 4, dep->interval);
1490
1491 params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1492 params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1493
1494 cmd = DWC3_DEPCMD_STARTTRANSFER;
1495 cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1496 cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1497
1498 /* Redo if some other failure beside bus-expiry is received */
1499 if (cmd_status && cmd_status != -EAGAIN) {
1500 dep->start_cmd_status = 0;
1501 dep->combo_num = 0;
1502 return 0;
1503 }
1504
1505 /* Store the first test status */
1506 if (dep->combo_num == 0)
1507 dep->start_cmd_status = cmd_status;
1508
1509 dep->combo_num++;
1510
1511 /*
1512 * End the transfer if the START_TRANSFER command is successful
1513 * to wait for the next XferNotReady to test the command again
1514 */
1515 if (cmd_status == 0) {
1516 dwc3_stop_active_transfer(dep, true, true);
1517 return 0;
1518 }
1519 }
1520
1521 /* test0 and test1 are both completed at this point */
1522 test0 = (dep->start_cmd_status == 0);
1523 test1 = (cmd_status == 0);
1524
1525 if (!test0 && test1)
1526 dep->combo_num = 1;
1527 else if (!test0 && !test1)
1528 dep->combo_num = 2;
1529 else if (test0 && !test1)
1530 dep->combo_num = 3;
1531 else if (test0 && test1)
1532 dep->combo_num = 0;
1533
1534 dep->frame_number &= DWC3_FRNUMBER_MASK;
1535 dep->frame_number |= dep->combo_num << 14;
1536 dep->frame_number += max_t(u32, 4, dep->interval);
1537
1538 /* Reinitialize test variables */
1539 dep->start_cmd_status = 0;
1540 dep->combo_num = 0;
1541
1542 return __dwc3_gadget_kick_transfer(dep);
1543 }
1544
1545 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1546 {
1547 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1548 struct dwc3 *dwc = dep->dwc;
1549 int ret;
1550 int i;
1551
1552 if (list_empty(&dep->pending_list) &&
1553 list_empty(&dep->started_list)) {
1554 dep->flags |= DWC3_EP_PENDING_REQUEST;
1555 return -EAGAIN;
1556 }
1557
1558 if (!dwc->dis_start_transfer_quirk &&
1559 (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1560 DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1561 if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1562 return dwc3_gadget_start_isoc_quirk(dep);
1563 }
1564
1565 if (desc->bInterval <= 14 &&
1566 dwc->gadget->speed >= USB_SPEED_HIGH) {
1567 u32 frame = __dwc3_gadget_get_frame(dwc);
1568 bool rollover = frame <
1569 (dep->frame_number & DWC3_FRNUMBER_MASK);
1570
1571 /*
1572 * frame_number is set from XferNotReady and may be already
1573 * out of date. DSTS only provides the lower 14 bit of the
1574 * current frame number. So add the upper two bits of
1575 * frame_number and handle a possible rollover.
1576 * This will provide the correct frame_number unless more than
1577 * rollover has happened since XferNotReady.
1578 */
1579
1580 dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1581 frame;
1582 if (rollover)
1583 dep->frame_number += BIT(14);
1584 }
1585
1586 for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1587 dep->frame_number = DWC3_ALIGN_FRAME(dep, i + 1);
1588
1589 ret = __dwc3_gadget_kick_transfer(dep);
1590 if (ret != -EAGAIN)
1591 break;
1592 }
1593
1594 /*
1595 * After a number of unsuccessful start attempts due to bus-expiry
1596 * status, issue END_TRANSFER command and retry on the next XferNotReady
1597 * event.
1598 */
1599 if (ret == -EAGAIN) {
1600 struct dwc3_gadget_ep_cmd_params params;
1601 u32 cmd;
1602
1603 cmd = DWC3_DEPCMD_ENDTRANSFER |
1604 DWC3_DEPCMD_CMDIOC |
1605 DWC3_DEPCMD_PARAM(dep->resource_index);
1606
1607 dep->resource_index = 0;
1608 memset(&params, 0, sizeof(params));
1609
1610 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1611 if (!ret)
1612 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1613 }
1614
1615 return ret;
1616 }
1617
1618 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1619 {
1620 struct dwc3 *dwc = dep->dwc;
1621
1622 if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1623 dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n",
1624 dep->name);
1625 return -ESHUTDOWN;
1626 }
1627
1628 if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1629 &req->request, req->dep->name))
1630 return -EINVAL;
1631
1632 if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1633 "%s: request %pK already in flight\n",
1634 dep->name, &req->request))
1635 return -EINVAL;
1636
1637 pm_runtime_get(dwc->dev);
1638
1639 req->request.actual = 0;
1640 req->request.status = -EINPROGRESS;
1641
1642 trace_dwc3_ep_queue(req);
1643
1644 list_add_tail(&req->list, &dep->pending_list);
1645 req->status = DWC3_REQUEST_STATUS_QUEUED;
1646
1647 if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1648 return 0;
1649
1650 /*
1651 * Start the transfer only after the END_TRANSFER is completed
1652 * and endpoint STALL is cleared.
1653 */
1654 if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1655 (dep->flags & DWC3_EP_WEDGE) ||
1656 (dep->flags & DWC3_EP_STALL)) {
1657 dep->flags |= DWC3_EP_DELAY_START;
1658 return 0;
1659 }
1660
1661 /*
1662 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1663 * wait for a XferNotReady event so we will know what's the current
1664 * (micro-)frame number.
1665 *
1666 * Without this trick, we are very, very likely gonna get Bus Expiry
1667 * errors which will force us issue EndTransfer command.
1668 */
1669 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1670 if (!(dep->flags & DWC3_EP_PENDING_REQUEST) &&
1671 !(dep->flags & DWC3_EP_TRANSFER_STARTED))
1672 return 0;
1673
1674 if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1675 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
1676 return __dwc3_gadget_start_isoc(dep);
1677 }
1678 }
1679
1680 __dwc3_gadget_kick_transfer(dep);
1681
1682 return 0;
1683 }
1684
1685 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1686 gfp_t gfp_flags)
1687 {
1688 struct dwc3_request *req = to_dwc3_request(request);
1689 struct dwc3_ep *dep = to_dwc3_ep(ep);
1690 struct dwc3 *dwc = dep->dwc;
1691
1692 unsigned long flags;
1693
1694 int ret;
1695
1696 spin_lock_irqsave(&dwc->lock, flags);
1697 ret = __dwc3_gadget_ep_queue(dep, req);
1698 spin_unlock_irqrestore(&dwc->lock, flags);
1699
1700 return ret;
1701 }
1702
1703 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
1704 {
1705 int i;
1706
1707 /* If req->trb is not set, then the request has not started */
1708 if (!req->trb)
1709 return;
1710
1711 /*
1712 * If request was already started, this means we had to
1713 * stop the transfer. With that we also need to ignore
1714 * all TRBs used by the request, however TRBs can only
1715 * be modified after completion of END_TRANSFER
1716 * command. So what we do here is that we wait for
1717 * END_TRANSFER completion and only after that, we jump
1718 * over TRBs by clearing HWO and incrementing dequeue
1719 * pointer.
1720 */
1721 for (i = 0; i < req->num_trbs; i++) {
1722 struct dwc3_trb *trb;
1723
1724 trb = &dep->trb_pool[dep->trb_dequeue];
1725 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1726 dwc3_ep_inc_deq(dep);
1727 }
1728
1729 req->num_trbs = 0;
1730 }
1731
1732 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
1733 {
1734 struct dwc3_request *req;
1735 struct dwc3_request *tmp;
1736
1737 list_for_each_entry_safe(req, tmp, &dep->cancelled_list, list) {
1738 dwc3_gadget_ep_skip_trbs(dep, req);
1739 dwc3_gadget_giveback(dep, req, -ECONNRESET);
1740 }
1741 }
1742
1743 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1744 struct usb_request *request)
1745 {
1746 struct dwc3_request *req = to_dwc3_request(request);
1747 struct dwc3_request *r = NULL;
1748
1749 struct dwc3_ep *dep = to_dwc3_ep(ep);
1750 struct dwc3 *dwc = dep->dwc;
1751
1752 unsigned long flags;
1753 int ret = 0;
1754
1755 trace_dwc3_ep_dequeue(req);
1756
1757 spin_lock_irqsave(&dwc->lock, flags);
1758
1759 list_for_each_entry(r, &dep->cancelled_list, list) {
1760 if (r == req)
1761 goto out;
1762 }
1763
1764 list_for_each_entry(r, &dep->pending_list, list) {
1765 if (r == req) {
1766 dwc3_gadget_giveback(dep, req, -ECONNRESET);
1767 goto out;
1768 }
1769 }
1770
1771 list_for_each_entry(r, &dep->started_list, list) {
1772 if (r == req) {
1773 struct dwc3_request *t;
1774
1775 /* wait until it is processed */
1776 dwc3_stop_active_transfer(dep, true, true);
1777
1778 /*
1779 * Remove any started request if the transfer is
1780 * cancelled.
1781 */
1782 list_for_each_entry_safe(r, t, &dep->started_list, list)
1783 dwc3_gadget_move_cancelled_request(r);
1784
1785 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
1786
1787 goto out;
1788 }
1789 }
1790
1791 dev_err(dwc->dev, "request %pK was not queued to %s\n",
1792 request, ep->name);
1793 ret = -EINVAL;
1794 out:
1795 spin_unlock_irqrestore(&dwc->lock, flags);
1796
1797 return ret;
1798 }
1799
1800 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1801 {
1802 struct dwc3_gadget_ep_cmd_params params;
1803 struct dwc3 *dwc = dep->dwc;
1804 struct dwc3_request *req;
1805 struct dwc3_request *tmp;
1806 int ret;
1807
1808 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1809 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1810 return -EINVAL;
1811 }
1812
1813 memset(&params, 0x00, sizeof(params));
1814
1815 if (value) {
1816 struct dwc3_trb *trb;
1817
1818 unsigned int transfer_in_flight;
1819 unsigned int started;
1820
1821 if (dep->number > 1)
1822 trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1823 else
1824 trb = &dwc->ep0_trb[dep->trb_enqueue];
1825
1826 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
1827 started = !list_empty(&dep->started_list);
1828
1829 if (!protocol && ((dep->direction && transfer_in_flight) ||
1830 (!dep->direction && started))) {
1831 return -EAGAIN;
1832 }
1833
1834 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
1835 &params);
1836 if (ret)
1837 dev_err(dwc->dev, "failed to set STALL on %s\n",
1838 dep->name);
1839 else
1840 dep->flags |= DWC3_EP_STALL;
1841 } else {
1842 /*
1843 * Don't issue CLEAR_STALL command to control endpoints. The
1844 * controller automatically clears the STALL when it receives
1845 * the SETUP token.
1846 */
1847 if (dep->number <= 1) {
1848 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1849 return 0;
1850 }
1851
1852 dwc3_stop_active_transfer(dep, true, true);
1853
1854 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1855 dwc3_gadget_move_cancelled_request(req);
1856
1857 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) {
1858 dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
1859 return 0;
1860 }
1861
1862 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1863
1864 ret = dwc3_send_clear_stall_ep_cmd(dep);
1865 if (ret) {
1866 dev_err(dwc->dev, "failed to clear STALL on %s\n",
1867 dep->name);
1868 return ret;
1869 }
1870
1871 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1872
1873 if ((dep->flags & DWC3_EP_DELAY_START) &&
1874 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
1875 __dwc3_gadget_kick_transfer(dep);
1876
1877 dep->flags &= ~DWC3_EP_DELAY_START;
1878 }
1879
1880 return ret;
1881 }
1882
1883 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1884 {
1885 struct dwc3_ep *dep = to_dwc3_ep(ep);
1886 struct dwc3 *dwc = dep->dwc;
1887
1888 unsigned long flags;
1889
1890 int ret;
1891
1892 spin_lock_irqsave(&dwc->lock, flags);
1893 ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1894 spin_unlock_irqrestore(&dwc->lock, flags);
1895
1896 return ret;
1897 }
1898
1899 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1900 {
1901 struct dwc3_ep *dep = to_dwc3_ep(ep);
1902 struct dwc3 *dwc = dep->dwc;
1903 unsigned long flags;
1904 int ret;
1905
1906 spin_lock_irqsave(&dwc->lock, flags);
1907 dep->flags |= DWC3_EP_WEDGE;
1908
1909 if (dep->number == 0 || dep->number == 1)
1910 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1911 else
1912 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1913 spin_unlock_irqrestore(&dwc->lock, flags);
1914
1915 return ret;
1916 }
1917
1918 /* -------------------------------------------------------------------------- */
1919
1920 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1921 .bLength = USB_DT_ENDPOINT_SIZE,
1922 .bDescriptorType = USB_DT_ENDPOINT,
1923 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
1924 };
1925
1926 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1927 .enable = dwc3_gadget_ep0_enable,
1928 .disable = dwc3_gadget_ep0_disable,
1929 .alloc_request = dwc3_gadget_ep_alloc_request,
1930 .free_request = dwc3_gadget_ep_free_request,
1931 .queue = dwc3_gadget_ep0_queue,
1932 .dequeue = dwc3_gadget_ep_dequeue,
1933 .set_halt = dwc3_gadget_ep0_set_halt,
1934 .set_wedge = dwc3_gadget_ep_set_wedge,
1935 };
1936
1937 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1938 .enable = dwc3_gadget_ep_enable,
1939 .disable = dwc3_gadget_ep_disable,
1940 .alloc_request = dwc3_gadget_ep_alloc_request,
1941 .free_request = dwc3_gadget_ep_free_request,
1942 .queue = dwc3_gadget_ep_queue,
1943 .dequeue = dwc3_gadget_ep_dequeue,
1944 .set_halt = dwc3_gadget_ep_set_halt,
1945 .set_wedge = dwc3_gadget_ep_set_wedge,
1946 };
1947
1948 /* -------------------------------------------------------------------------- */
1949
1950 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1951 {
1952 struct dwc3 *dwc = gadget_to_dwc(g);
1953
1954 return __dwc3_gadget_get_frame(dwc);
1955 }
1956
1957 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
1958 {
1959 int retries;
1960
1961 int ret;
1962 u32 reg;
1963
1964 u8 link_state;
1965
1966 /*
1967 * According to the Databook Remote wakeup request should
1968 * be issued only when the device is in early suspend state.
1969 *
1970 * We can check that via USB Link State bits in DSTS register.
1971 */
1972 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1973
1974 link_state = DWC3_DSTS_USBLNKST(reg);
1975
1976 switch (link_state) {
1977 case DWC3_LINK_STATE_RESET:
1978 case DWC3_LINK_STATE_RX_DET: /* in HS, means Early Suspend */
1979 case DWC3_LINK_STATE_U3: /* in HS, means SUSPEND */
1980 case DWC3_LINK_STATE_U2: /* in HS, means Sleep (L1) */
1981 case DWC3_LINK_STATE_U1:
1982 case DWC3_LINK_STATE_RESUME:
1983 break;
1984 default:
1985 return -EINVAL;
1986 }
1987
1988 ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1989 if (ret < 0) {
1990 dev_err(dwc->dev, "failed to put link in Recovery\n");
1991 return ret;
1992 }
1993
1994 /* Recent versions do this automatically */
1995 if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
1996 /* write zeroes to Link Change Request */
1997 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1998 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1999 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2000 }
2001
2002 /* poll until Link State changes to ON */
2003 retries = 20000;
2004
2005 while (retries--) {
2006 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2007
2008 /* in HS, means ON */
2009 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2010 break;
2011 }
2012
2013 if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2014 dev_err(dwc->dev, "failed to send remote wakeup\n");
2015 return -EINVAL;
2016 }
2017
2018 return 0;
2019 }
2020
2021 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2022 {
2023 struct dwc3 *dwc = gadget_to_dwc(g);
2024 unsigned long flags;
2025 int ret;
2026
2027 spin_lock_irqsave(&dwc->lock, flags);
2028 ret = __dwc3_gadget_wakeup(dwc);
2029 spin_unlock_irqrestore(&dwc->lock, flags);
2030
2031 return ret;
2032 }
2033
2034 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2035 int is_selfpowered)
2036 {
2037 struct dwc3 *dwc = gadget_to_dwc(g);
2038 unsigned long flags;
2039
2040 spin_lock_irqsave(&dwc->lock, flags);
2041 g->is_selfpowered = !!is_selfpowered;
2042 spin_unlock_irqrestore(&dwc->lock, flags);
2043
2044 return 0;
2045 }
2046
2047 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2048 {
2049 u32 epnum;
2050
2051 for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2052 struct dwc3_ep *dep;
2053
2054 dep = dwc->eps[epnum];
2055 if (!dep)
2056 continue;
2057
2058 dwc3_remove_requests(dwc, dep);
2059 }
2060 }
2061
2062 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
2063 {
2064 u32 reg;
2065 u32 timeout = 500;
2066
2067 if (pm_runtime_suspended(dwc->dev))
2068 return 0;
2069
2070 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2071 if (is_on) {
2072 if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2073 reg &= ~DWC3_DCTL_TRGTULST_MASK;
2074 reg |= DWC3_DCTL_TRGTULST_RX_DET;
2075 }
2076
2077 if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2078 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2079 reg |= DWC3_DCTL_RUN_STOP;
2080
2081 if (dwc->has_hibernation)
2082 reg |= DWC3_DCTL_KEEP_CONNECT;
2083
2084 dwc->pullups_connected = true;
2085 } else {
2086 reg &= ~DWC3_DCTL_RUN_STOP;
2087
2088 if (dwc->has_hibernation && !suspend)
2089 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2090
2091 dwc->pullups_connected = false;
2092 }
2093
2094 dwc3_gadget_dctl_write_safe(dwc, reg);
2095
2096 do {
2097 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2098 reg &= DWC3_DSTS_DEVCTRLHLT;
2099 } while (--timeout && !(!is_on ^ !reg));
2100
2101 if (!timeout)
2102 return -ETIMEDOUT;
2103
2104 return 0;
2105 }
2106
2107 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2108 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2109 static int __dwc3_gadget_start(struct dwc3 *dwc);
2110
2111 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2112 {
2113 struct dwc3 *dwc = gadget_to_dwc(g);
2114 unsigned long flags;
2115 int ret;
2116
2117 is_on = !!is_on;
2118
2119 /*
2120 * Per databook, when we want to stop the gadget, if a control transfer
2121 * is still in process, complete it and get the core into setup phase.
2122 */
2123 if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
2124 reinit_completion(&dwc->ep0_in_setup);
2125
2126 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2127 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2128 if (ret == 0) {
2129 dev_err(dwc->dev, "timed out waiting for SETUP phase\n");
2130 return -ETIMEDOUT;
2131 }
2132 }
2133
2134 /*
2135 * Check the return value for successful resume, or error. For a
2136 * successful resume, the DWC3 runtime PM resume routine will handle
2137 * the run stop sequence, so avoid duplicate operations here.
2138 */
2139 ret = pm_runtime_get_sync(dwc->dev);
2140 if (!ret || ret < 0) {
2141 pm_runtime_put(dwc->dev);
2142 return 0;
2143 }
2144
2145 /*
2146 * Synchronize any pending event handling before executing the controller
2147 * halt routine.
2148 */
2149 if (!is_on) {
2150 dwc3_gadget_disable_irq(dwc);
2151 synchronize_irq(dwc->irq_gadget);
2152 }
2153
2154 spin_lock_irqsave(&dwc->lock, flags);
2155
2156 if (!is_on) {
2157 u32 count;
2158
2159 dwc->connected = false;
2160 /*
2161 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2162 * Section 4.1.8 Table 4-7, it states that for a device-initiated
2163 * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2164 * command for any active transfers" before clearing the RunStop
2165 * bit.
2166 */
2167 dwc3_stop_active_transfers(dwc);
2168 __dwc3_gadget_stop(dwc);
2169
2170 /*
2171 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2172 * Section 1.3.4, it mentions that for the DEVCTRLHLT bit, the
2173 * "software needs to acknowledge the events that are generated
2174 * (by writing to GEVNTCOUNTn) while it is waiting for this bit
2175 * to be set to '1'."
2176 */
2177 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
2178 count &= DWC3_GEVNTCOUNT_MASK;
2179 if (count > 0) {
2180 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
2181 dwc->ev_buf->lpos = (dwc->ev_buf->lpos + count) %
2182 dwc->ev_buf->length;
2183 }
2184 } else {
2185 __dwc3_gadget_start(dwc);
2186 }
2187
2188 ret = dwc3_gadget_run_stop(dwc, is_on, false);
2189 spin_unlock_irqrestore(&dwc->lock, flags);
2190 pm_runtime_put(dwc->dev);
2191
2192 return ret;
2193 }
2194
2195 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2196 {
2197 u32 reg;
2198
2199 /* Enable all but Start and End of Frame IRQs */
2200 reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
2201 DWC3_DEVTEN_EVNTOVERFLOWEN |
2202 DWC3_DEVTEN_CMDCMPLTEN |
2203 DWC3_DEVTEN_ERRTICERREN |
2204 DWC3_DEVTEN_WKUPEVTEN |
2205 DWC3_DEVTEN_CONNECTDONEEN |
2206 DWC3_DEVTEN_USBRSTEN |
2207 DWC3_DEVTEN_DISCONNEVTEN);
2208
2209 if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2210 reg |= DWC3_DEVTEN_ULSTCNGEN;
2211
2212 /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2213 if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2214 reg |= DWC3_DEVTEN_EOPFEN;
2215
2216 dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2217 }
2218
2219 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2220 {
2221 /* mask all interrupts */
2222 dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2223 }
2224
2225 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2226 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2227
2228 /**
2229 * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2230 * @dwc: pointer to our context structure
2231 *
2232 * The following looks like complex but it's actually very simple. In order to
2233 * calculate the number of packets we can burst at once on OUT transfers, we're
2234 * gonna use RxFIFO size.
2235 *
2236 * To calculate RxFIFO size we need two numbers:
2237 * MDWIDTH = size, in bits, of the internal memory bus
2238 * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2239 *
2240 * Given these two numbers, the formula is simple:
2241 *
2242 * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2243 *
2244 * 24 bytes is for 3x SETUP packets
2245 * 16 bytes is a clock domain crossing tolerance
2246 *
2247 * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2248 */
2249 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2250 {
2251 u32 ram2_depth;
2252 u32 mdwidth;
2253 u32 nump;
2254 u32 reg;
2255
2256 ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2257 mdwidth = DWC3_GHWPARAMS0_MDWIDTH(dwc->hwparams.hwparams0);
2258 if (DWC3_IP_IS(DWC32))
2259 mdwidth += DWC3_GHWPARAMS6_MDWIDTH(dwc->hwparams.hwparams6);
2260
2261 nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2262 nump = min_t(u32, nump, 16);
2263
2264 /* update NumP */
2265 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2266 reg &= ~DWC3_DCFG_NUMP_MASK;
2267 reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2268 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2269 }
2270
2271 static int __dwc3_gadget_start(struct dwc3 *dwc)
2272 {
2273 struct dwc3_ep *dep;
2274 int ret = 0;
2275 u32 reg;
2276
2277 /*
2278 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2279 * the core supports IMOD, disable it.
2280 */
2281 if (dwc->imod_interval) {
2282 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2283 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2284 } else if (dwc3_has_imod(dwc)) {
2285 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2286 }
2287
2288 /*
2289 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2290 * field instead of letting dwc3 itself calculate that automatically.
2291 *
2292 * This way, we maximize the chances that we'll be able to get several
2293 * bursts of data without going through any sort of endpoint throttling.
2294 */
2295 reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2296 if (DWC3_IP_IS(DWC3))
2297 reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2298 else
2299 reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2300
2301 dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2302
2303 dwc3_gadget_setup_nump(dwc);
2304
2305 /* Start with SuperSpeed Default */
2306 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2307
2308 dep = dwc->eps[0];
2309 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2310 if (ret) {
2311 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2312 goto err0;
2313 }
2314
2315 dep = dwc->eps[1];
2316 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2317 if (ret) {
2318 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2319 goto err1;
2320 }
2321
2322 /* begin to receive SETUP packets */
2323 dwc->ep0state = EP0_SETUP_PHASE;
2324 dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2325 dwc3_ep0_out_start(dwc);
2326
2327 dwc3_gadget_enable_irq(dwc);
2328
2329 return 0;
2330
2331 err1:
2332 __dwc3_gadget_ep_disable(dwc->eps[0]);
2333
2334 err0:
2335 return ret;
2336 }
2337
2338 static int dwc3_gadget_start(struct usb_gadget *g,
2339 struct usb_gadget_driver *driver)
2340 {
2341 struct dwc3 *dwc = gadget_to_dwc(g);
2342 unsigned long flags;
2343 int ret = 0;
2344 int irq;
2345
2346 irq = dwc->irq_gadget;
2347 ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2348 IRQF_SHARED, "dwc3", dwc->ev_buf);
2349 if (ret) {
2350 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2351 irq, ret);
2352 goto err0;
2353 }
2354
2355 spin_lock_irqsave(&dwc->lock, flags);
2356 if (dwc->gadget_driver) {
2357 dev_err(dwc->dev, "%s is already bound to %s\n",
2358 dwc->gadget->name,
2359 dwc->gadget_driver->driver.name);
2360 ret = -EBUSY;
2361 goto err1;
2362 }
2363
2364 dwc->gadget_driver = driver;
2365 spin_unlock_irqrestore(&dwc->lock, flags);
2366
2367 return 0;
2368
2369 err1:
2370 spin_unlock_irqrestore(&dwc->lock, flags);
2371 free_irq(irq, dwc);
2372
2373 err0:
2374 return ret;
2375 }
2376
2377 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2378 {
2379 dwc3_gadget_disable_irq(dwc);
2380 __dwc3_gadget_ep_disable(dwc->eps[0]);
2381 __dwc3_gadget_ep_disable(dwc->eps[1]);
2382 }
2383
2384 static int dwc3_gadget_stop(struct usb_gadget *g)
2385 {
2386 struct dwc3 *dwc = gadget_to_dwc(g);
2387 unsigned long flags;
2388
2389 spin_lock_irqsave(&dwc->lock, flags);
2390 dwc->gadget_driver = NULL;
2391 spin_unlock_irqrestore(&dwc->lock, flags);
2392
2393 free_irq(dwc->irq_gadget, dwc->ev_buf);
2394
2395 return 0;
2396 }
2397
2398 static void dwc3_gadget_config_params(struct usb_gadget *g,
2399 struct usb_dcd_config_params *params)
2400 {
2401 struct dwc3 *dwc = gadget_to_dwc(g);
2402
2403 params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2404 params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2405
2406 /* Recommended BESL */
2407 if (!dwc->dis_enblslpm_quirk) {
2408 /*
2409 * If the recommended BESL baseline is 0 or if the BESL deep is
2410 * less than 2, Microsoft's Windows 10 host usb stack will issue
2411 * a usb reset immediately after it receives the extended BOS
2412 * descriptor and the enumeration will fail. To maintain
2413 * compatibility with the Windows' usb stack, let's set the
2414 * recommended BESL baseline to 1 and clamp the BESL deep to be
2415 * within 2 to 15.
2416 */
2417 params->besl_baseline = 1;
2418 if (dwc->is_utmi_l1_suspend)
2419 params->besl_deep =
2420 clamp_t(u8, dwc->hird_threshold, 2, 15);
2421 }
2422
2423 /* U1 Device exit Latency */
2424 if (dwc->dis_u1_entry_quirk)
2425 params->bU1devExitLat = 0;
2426 else
2427 params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
2428
2429 /* U2 Device exit Latency */
2430 if (dwc->dis_u2_entry_quirk)
2431 params->bU2DevExitLat = 0;
2432 else
2433 params->bU2DevExitLat =
2434 cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
2435 }
2436
2437 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2438 enum usb_device_speed speed)
2439 {
2440 struct dwc3 *dwc = gadget_to_dwc(g);
2441 unsigned long flags;
2442 u32 reg;
2443
2444 spin_lock_irqsave(&dwc->lock, flags);
2445 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2446 reg &= ~(DWC3_DCFG_SPEED_MASK);
2447
2448 /*
2449 * WORKAROUND: DWC3 revision < 2.20a have an issue
2450 * which would cause metastability state on Run/Stop
2451 * bit if we try to force the IP to USB2-only mode.
2452 *
2453 * Because of that, we cannot configure the IP to any
2454 * speed other than the SuperSpeed
2455 *
2456 * Refers to:
2457 *
2458 * STAR#9000525659: Clock Domain Crossing on DCTL in
2459 * USB 2.0 Mode
2460 */
2461 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2462 !dwc->dis_metastability_quirk) {
2463 reg |= DWC3_DCFG_SUPERSPEED;
2464 } else {
2465 switch (speed) {
2466 case USB_SPEED_LOW:
2467 reg |= DWC3_DCFG_LOWSPEED;
2468 break;
2469 case USB_SPEED_FULL:
2470 reg |= DWC3_DCFG_FULLSPEED;
2471 break;
2472 case USB_SPEED_HIGH:
2473 reg |= DWC3_DCFG_HIGHSPEED;
2474 break;
2475 case USB_SPEED_SUPER:
2476 reg |= DWC3_DCFG_SUPERSPEED;
2477 break;
2478 case USB_SPEED_SUPER_PLUS:
2479 if (DWC3_IP_IS(DWC3))
2480 reg |= DWC3_DCFG_SUPERSPEED;
2481 else
2482 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2483 break;
2484 default:
2485 dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2486
2487 if (DWC3_IP_IS(DWC3))
2488 reg |= DWC3_DCFG_SUPERSPEED;
2489 else
2490 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2491 }
2492 }
2493 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2494
2495 spin_unlock_irqrestore(&dwc->lock, flags);
2496 }
2497
2498 static const struct usb_gadget_ops dwc3_gadget_ops = {
2499 .get_frame = dwc3_gadget_get_frame,
2500 .wakeup = dwc3_gadget_wakeup,
2501 .set_selfpowered = dwc3_gadget_set_selfpowered,
2502 .pullup = dwc3_gadget_pullup,
2503 .udc_start = dwc3_gadget_start,
2504 .udc_stop = dwc3_gadget_stop,
2505 .udc_set_speed = dwc3_gadget_set_speed,
2506 .get_config_params = dwc3_gadget_config_params,
2507 };
2508
2509 /* -------------------------------------------------------------------------- */
2510
2511 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2512 {
2513 struct dwc3 *dwc = dep->dwc;
2514
2515 usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2516 dep->endpoint.maxburst = 1;
2517 dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2518 if (!dep->direction)
2519 dwc->gadget->ep0 = &dep->endpoint;
2520
2521 dep->endpoint.caps.type_control = true;
2522
2523 return 0;
2524 }
2525
2526 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2527 {
2528 struct dwc3 *dwc = dep->dwc;
2529 int mdwidth;
2530 int size;
2531
2532 mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2533 if (DWC3_IP_IS(DWC32))
2534 mdwidth += DWC3_GHWPARAMS6_MDWIDTH(dwc->hwparams.hwparams6);
2535
2536 /* MDWIDTH is represented in bits, we need it in bytes */
2537 mdwidth /= 8;
2538
2539 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2540 if (DWC3_IP_IS(DWC3))
2541 size = DWC3_GTXFIFOSIZ_TXFDEP(size);
2542 else
2543 size = DWC31_GTXFIFOSIZ_TXFDEP(size);
2544
2545 /* FIFO Depth is in MDWDITH bytes. Multiply */
2546 size *= mdwidth;
2547
2548 /*
2549 * To meet performance requirement, a minimum TxFIFO size of 3x
2550 * MaxPacketSize is recommended for endpoints that support burst and a
2551 * minimum TxFIFO size of 2x MaxPacketSize for endpoints that don't
2552 * support burst. Use those numbers and we can calculate the max packet
2553 * limit as below.
2554 */
2555 if (dwc->maximum_speed >= USB_SPEED_SUPER)
2556 size /= 3;
2557 else
2558 size /= 2;
2559
2560 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2561
2562 dep->endpoint.max_streams = 16;
2563 dep->endpoint.ops = &dwc3_gadget_ep_ops;
2564 list_add_tail(&dep->endpoint.ep_list,
2565 &dwc->gadget->ep_list);
2566 dep->endpoint.caps.type_iso = true;
2567 dep->endpoint.caps.type_bulk = true;
2568 dep->endpoint.caps.type_int = true;
2569
2570 return dwc3_alloc_trb_pool(dep);
2571 }
2572
2573 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
2574 {
2575 struct dwc3 *dwc = dep->dwc;
2576 int mdwidth;
2577 int size;
2578
2579 mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2580 if (DWC3_IP_IS(DWC32))
2581 mdwidth += DWC3_GHWPARAMS6_MDWIDTH(dwc->hwparams.hwparams6);
2582
2583 /* MDWIDTH is represented in bits, convert to bytes */
2584 mdwidth /= 8;
2585
2586 /* All OUT endpoints share a single RxFIFO space */
2587 size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
2588 if (DWC3_IP_IS(DWC3))
2589 size = DWC3_GRXFIFOSIZ_RXFDEP(size);
2590 else
2591 size = DWC31_GRXFIFOSIZ_RXFDEP(size);
2592
2593 /* FIFO depth is in MDWDITH bytes */
2594 size *= mdwidth;
2595
2596 /*
2597 * To meet performance requirement, a minimum recommended RxFIFO size
2598 * is defined as follow:
2599 * RxFIFO size >= (3 x MaxPacketSize) +
2600 * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
2601 *
2602 * Then calculate the max packet limit as below.
2603 */
2604 size -= (3 * 8) + 16;
2605 if (size < 0)
2606 size = 0;
2607 else
2608 size /= 3;
2609
2610 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2611 dep->endpoint.max_streams = 16;
2612 dep->endpoint.ops = &dwc3_gadget_ep_ops;
2613 list_add_tail(&dep->endpoint.ep_list,
2614 &dwc->gadget->ep_list);
2615 dep->endpoint.caps.type_iso = true;
2616 dep->endpoint.caps.type_bulk = true;
2617 dep->endpoint.caps.type_int = true;
2618
2619 return dwc3_alloc_trb_pool(dep);
2620 }
2621
2622 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
2623 {
2624 struct dwc3_ep *dep;
2625 bool direction = epnum & 1;
2626 int ret;
2627 u8 num = epnum >> 1;
2628
2629 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2630 if (!dep)
2631 return -ENOMEM;
2632
2633 dep->dwc = dwc;
2634 dep->number = epnum;
2635 dep->direction = direction;
2636 dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
2637 dwc->eps[epnum] = dep;
2638 dep->combo_num = 0;
2639 dep->start_cmd_status = 0;
2640
2641 snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
2642 direction ? "in" : "out");
2643
2644 dep->endpoint.name = dep->name;
2645
2646 if (!(dep->number > 1)) {
2647 dep->endpoint.desc = &dwc3_gadget_ep0_desc;
2648 dep->endpoint.comp_desc = NULL;
2649 }
2650
2651 if (num == 0)
2652 ret = dwc3_gadget_init_control_endpoint(dep);
2653 else if (direction)
2654 ret = dwc3_gadget_init_in_endpoint(dep);
2655 else
2656 ret = dwc3_gadget_init_out_endpoint(dep);
2657
2658 if (ret)
2659 return ret;
2660
2661 dep->endpoint.caps.dir_in = direction;
2662 dep->endpoint.caps.dir_out = !direction;
2663
2664 INIT_LIST_HEAD(&dep->pending_list);
2665 INIT_LIST_HEAD(&dep->started_list);
2666 INIT_LIST_HEAD(&dep->cancelled_list);
2667
2668 return 0;
2669 }
2670
2671 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
2672 {
2673 u8 epnum;
2674
2675 INIT_LIST_HEAD(&dwc->gadget->ep_list);
2676
2677 for (epnum = 0; epnum < total; epnum++) {
2678 int ret;
2679
2680 ret = dwc3_gadget_init_endpoint(dwc, epnum);
2681 if (ret)
2682 return ret;
2683 }
2684
2685 return 0;
2686 }
2687
2688 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
2689 {
2690 struct dwc3_ep *dep;
2691 u8 epnum;
2692
2693 for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2694 dep = dwc->eps[epnum];
2695 if (!dep)
2696 continue;
2697 /*
2698 * Physical endpoints 0 and 1 are special; they form the
2699 * bi-directional USB endpoint 0.
2700 *
2701 * For those two physical endpoints, we don't allocate a TRB
2702 * pool nor do we add them the endpoints list. Due to that, we
2703 * shouldn't do these two operations otherwise we would end up
2704 * with all sorts of bugs when removing dwc3.ko.
2705 */
2706 if (epnum != 0 && epnum != 1) {
2707 dwc3_free_trb_pool(dep);
2708 list_del(&dep->endpoint.ep_list);
2709 }
2710
2711 kfree(dep);
2712 }
2713 }
2714
2715 /* -------------------------------------------------------------------------- */
2716
2717 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
2718 struct dwc3_request *req, struct dwc3_trb *trb,
2719 const struct dwc3_event_depevt *event, int status, int chain)
2720 {
2721 unsigned int count;
2722
2723 dwc3_ep_inc_deq(dep);
2724
2725 trace_dwc3_complete_trb(dep, trb);
2726 req->num_trbs--;
2727
2728 /*
2729 * If we're in the middle of series of chained TRBs and we
2730 * receive a short transfer along the way, DWC3 will skip
2731 * through all TRBs including the last TRB in the chain (the
2732 * where CHN bit is zero. DWC3 will also avoid clearing HWO
2733 * bit and SW has to do it manually.
2734 *
2735 * We're going to do that here to avoid problems of HW trying
2736 * to use bogus TRBs for transfers.
2737 */
2738 if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
2739 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2740
2741 /*
2742 * For isochronous transfers, the first TRB in a service interval must
2743 * have the Isoc-First type. Track and report its interval frame number.
2744 */
2745 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2746 (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
2747 unsigned int frame_number;
2748
2749 frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
2750 frame_number &= ~(dep->interval - 1);
2751 req->request.frame_number = frame_number;
2752 }
2753
2754 /*
2755 * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
2756 * this TRB points to the bounce buffer address, it's a MPS alignment
2757 * TRB. Don't add it to req->remaining calculation.
2758 */
2759 if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
2760 trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
2761 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2762 return 1;
2763 }
2764
2765 count = trb->size & DWC3_TRB_SIZE_MASK;
2766 req->remaining += count;
2767
2768 if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
2769 return 1;
2770
2771 if (event->status & DEPEVT_STATUS_SHORT && !chain)
2772 return 1;
2773
2774 if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
2775 (trb->ctrl & DWC3_TRB_CTRL_LST))
2776 return 1;
2777
2778 return 0;
2779 }
2780
2781 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
2782 struct dwc3_request *req, const struct dwc3_event_depevt *event,
2783 int status)
2784 {
2785 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2786 struct scatterlist *sg = req->sg;
2787 struct scatterlist *s;
2788 unsigned int num_queued = req->num_queued_sgs;
2789 unsigned int i;
2790 int ret = 0;
2791
2792 for_each_sg(sg, s, num_queued, i) {
2793 trb = &dep->trb_pool[dep->trb_dequeue];
2794
2795 req->sg = sg_next(s);
2796 req->num_queued_sgs--;
2797
2798 ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
2799 trb, event, status, true);
2800 if (ret)
2801 break;
2802 }
2803
2804 return ret;
2805 }
2806
2807 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
2808 struct dwc3_request *req, const struct dwc3_event_depevt *event,
2809 int status)
2810 {
2811 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2812
2813 return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
2814 event, status, false);
2815 }
2816
2817 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
2818 {
2819 return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
2820 }
2821
2822 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
2823 const struct dwc3_event_depevt *event,
2824 struct dwc3_request *req, int status)
2825 {
2826 int ret;
2827
2828 if (req->request.num_mapped_sgs)
2829 ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
2830 status);
2831 else
2832 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2833 status);
2834
2835 req->request.actual = req->request.length - req->remaining;
2836
2837 if (!dwc3_gadget_ep_request_completed(req))
2838 goto out;
2839
2840 if (req->needs_extra_trb) {
2841 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2842 status);
2843 req->needs_extra_trb = false;
2844 }
2845
2846 dwc3_gadget_giveback(dep, req, status);
2847
2848 out:
2849 return ret;
2850 }
2851
2852 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
2853 const struct dwc3_event_depevt *event, int status)
2854 {
2855 struct dwc3_request *req;
2856 struct dwc3_request *tmp;
2857
2858 list_for_each_entry_safe(req, tmp, &dep->started_list, list) {
2859 int ret;
2860
2861 ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
2862 req, status);
2863 if (ret)
2864 break;
2865 }
2866 }
2867
2868 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
2869 {
2870 struct dwc3_request *req;
2871
2872 if (!list_empty(&dep->pending_list))
2873 return true;
2874
2875 /*
2876 * We only need to check the first entry of the started list. We can
2877 * assume the completed requests are removed from the started list.
2878 */
2879 req = next_request(&dep->started_list);
2880 if (!req)
2881 return false;
2882
2883 return !dwc3_gadget_ep_request_completed(req);
2884 }
2885
2886 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
2887 const struct dwc3_event_depevt *event)
2888 {
2889 dep->frame_number = event->parameters;
2890 }
2891
2892 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
2893 const struct dwc3_event_depevt *event, int status)
2894 {
2895 struct dwc3 *dwc = dep->dwc;
2896 bool no_started_trb = true;
2897
2898 dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
2899
2900 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
2901 goto out;
2902
2903 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2904 list_empty(&dep->started_list) &&
2905 (list_empty(&dep->pending_list) || status == -EXDEV))
2906 dwc3_stop_active_transfer(dep, true, true);
2907 else if (dwc3_gadget_ep_should_continue(dep))
2908 if (__dwc3_gadget_kick_transfer(dep) == 0)
2909 no_started_trb = false;
2910
2911 out:
2912 /*
2913 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2914 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2915 */
2916 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
2917 u32 reg;
2918 int i;
2919
2920 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2921 dep = dwc->eps[i];
2922
2923 if (!(dep->flags & DWC3_EP_ENABLED))
2924 continue;
2925
2926 if (!list_empty(&dep->started_list))
2927 return no_started_trb;
2928 }
2929
2930 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2931 reg |= dwc->u1u2;
2932 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2933
2934 dwc->u1u2 = 0;
2935 }
2936
2937 return no_started_trb;
2938 }
2939
2940 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
2941 const struct dwc3_event_depevt *event)
2942 {
2943 int status = 0;
2944
2945 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
2946 dwc3_gadget_endpoint_frame_from_event(dep, event);
2947
2948 if (event->status & DEPEVT_STATUS_BUSERR)
2949 status = -ECONNRESET;
2950
2951 if (event->status & DEPEVT_STATUS_MISSED_ISOC)
2952 status = -EXDEV;
2953
2954 dwc3_gadget_endpoint_trbs_complete(dep, event, status);
2955 }
2956
2957 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
2958 const struct dwc3_event_depevt *event)
2959 {
2960 int status = 0;
2961
2962 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
2963
2964 if (event->status & DEPEVT_STATUS_BUSERR)
2965 status = -ECONNRESET;
2966
2967 if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
2968 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2969 }
2970
2971 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
2972 const struct dwc3_event_depevt *event)
2973 {
2974 dwc3_gadget_endpoint_frame_from_event(dep, event);
2975
2976 /*
2977 * The XferNotReady event is generated only once before the endpoint
2978 * starts. It will be generated again when END_TRANSFER command is
2979 * issued. For some controller versions, the XferNotReady event may be
2980 * generated while the END_TRANSFER command is still in process. Ignore
2981 * it and wait for the next XferNotReady event after the command is
2982 * completed.
2983 */
2984 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
2985 return;
2986
2987 (void) __dwc3_gadget_start_isoc(dep);
2988 }
2989
2990 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
2991 const struct dwc3_event_depevt *event)
2992 {
2993 u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
2994
2995 if (cmd != DWC3_DEPCMD_ENDTRANSFER)
2996 return;
2997
2998 dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
2999 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3000 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3001
3002 if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3003 struct dwc3 *dwc = dep->dwc;
3004
3005 dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3006 if (dwc3_send_clear_stall_ep_cmd(dep)) {
3007 struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3008
3009 dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3010 if (dwc->delayed_status)
3011 __dwc3_gadget_ep0_set_halt(ep0, 1);
3012 return;
3013 }
3014
3015 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3016 if (dwc->delayed_status)
3017 dwc3_ep0_send_delayed_status(dwc);
3018 }
3019
3020 if ((dep->flags & DWC3_EP_DELAY_START) &&
3021 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3022 __dwc3_gadget_kick_transfer(dep);
3023
3024 dep->flags &= ~DWC3_EP_DELAY_START;
3025 }
3026
3027 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3028 const struct dwc3_event_depevt *event)
3029 {
3030 struct dwc3 *dwc = dep->dwc;
3031
3032 if (event->status == DEPEVT_STREAMEVT_FOUND) {
3033 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3034 goto out;
3035 }
3036
3037 /* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3038 switch (event->parameters) {
3039 case DEPEVT_STREAM_PRIME:
3040 /*
3041 * If the host can properly transition the endpoint state from
3042 * idle to prime after a NoStream rejection, there's no need to
3043 * force restarting the endpoint to reinitiate the stream. To
3044 * simplify the check, assume the host follows the USB spec if
3045 * it primed the endpoint more than once.
3046 */
3047 if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3048 if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3049 dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3050 else
3051 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3052 }
3053
3054 break;
3055 case DEPEVT_STREAM_NOSTREAM:
3056 if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3057 !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3058 !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE))
3059 break;
3060
3061 /*
3062 * If the host rejects a stream due to no active stream, by the
3063 * USB and xHCI spec, the endpoint will be put back to idle
3064 * state. When the host is ready (buffer added/updated), it will
3065 * prime the endpoint to inform the usb device controller. This
3066 * triggers the device controller to issue ERDY to restart the
3067 * stream. However, some hosts don't follow this and keep the
3068 * endpoint in the idle state. No prime will come despite host
3069 * streams are updated, and the device controller will not be
3070 * triggered to generate ERDY to move the next stream data. To
3071 * workaround this and maintain compatibility with various
3072 * hosts, force to reinitate the stream until the host is ready
3073 * instead of waiting for the host to prime the endpoint.
3074 */
3075 if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3076 unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3077
3078 dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3079 } else {
3080 dep->flags |= DWC3_EP_DELAY_START;
3081 dwc3_stop_active_transfer(dep, true, true);
3082 return;
3083 }
3084 break;
3085 }
3086
3087 out:
3088 dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3089 }
3090
3091 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3092 const struct dwc3_event_depevt *event)
3093 {
3094 struct dwc3_ep *dep;
3095 u8 epnum = event->endpoint_number;
3096
3097 dep = dwc->eps[epnum];
3098
3099 if (!(dep->flags & DWC3_EP_ENABLED)) {
3100 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
3101 return;
3102
3103 /* Handle only EPCMDCMPLT when EP disabled */
3104 if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
3105 return;
3106 }
3107
3108 if (epnum == 0 || epnum == 1) {
3109 dwc3_ep0_interrupt(dwc, event);
3110 return;
3111 }
3112
3113 switch (event->endpoint_event) {
3114 case DWC3_DEPEVT_XFERINPROGRESS:
3115 dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3116 break;
3117 case DWC3_DEPEVT_XFERNOTREADY:
3118 dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3119 break;
3120 case DWC3_DEPEVT_EPCMDCMPLT:
3121 dwc3_gadget_endpoint_command_complete(dep, event);
3122 break;
3123 case DWC3_DEPEVT_XFERCOMPLETE:
3124 dwc3_gadget_endpoint_transfer_complete(dep, event);
3125 break;
3126 case DWC3_DEPEVT_STREAMEVT:
3127 dwc3_gadget_endpoint_stream_event(dep, event);
3128 break;
3129 case DWC3_DEPEVT_RXTXFIFOEVT:
3130 break;
3131 }
3132 }
3133
3134 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3135 {
3136 if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
3137 spin_unlock(&dwc->lock);
3138 dwc->gadget_driver->disconnect(dwc->gadget);
3139 spin_lock(&dwc->lock);
3140 }
3141 }
3142
3143 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3144 {
3145 if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
3146 spin_unlock(&dwc->lock);
3147 dwc->gadget_driver->suspend(dwc->gadget);
3148 spin_lock(&dwc->lock);
3149 }
3150 }
3151
3152 static void dwc3_resume_gadget(struct dwc3 *dwc)
3153 {
3154 if (dwc->gadget_driver && dwc->gadget_driver->resume) {
3155 spin_unlock(&dwc->lock);
3156 dwc->gadget_driver->resume(dwc->gadget);
3157 spin_lock(&dwc->lock);
3158 }
3159 }
3160
3161 static void dwc3_reset_gadget(struct dwc3 *dwc)
3162 {
3163 if (!dwc->gadget_driver)
3164 return;
3165
3166 if (dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3167 spin_unlock(&dwc->lock);
3168 usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3169 spin_lock(&dwc->lock);
3170 }
3171 }
3172
3173 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3174 bool interrupt)
3175 {
3176 struct dwc3_gadget_ep_cmd_params params;
3177 u32 cmd;
3178 int ret;
3179
3180 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3181 (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3182 return;
3183
3184 /*
3185 * NOTICE: We are violating what the Databook says about the
3186 * EndTransfer command. Ideally we would _always_ wait for the
3187 * EndTransfer Command Completion IRQ, but that's causing too
3188 * much trouble synchronizing between us and gadget driver.
3189 *
3190 * We have discussed this with the IP Provider and it was
3191 * suggested to giveback all requests here.
3192 *
3193 * Note also that a similar handling was tested by Synopsys
3194 * (thanks a lot Paul) and nothing bad has come out of it.
3195 * In short, what we're doing is issuing EndTransfer with
3196 * CMDIOC bit set and delay kicking transfer until the
3197 * EndTransfer command had completed.
3198 *
3199 * As of IP version 3.10a of the DWC_usb3 IP, the controller
3200 * supports a mode to work around the above limitation. The
3201 * software can poll the CMDACT bit in the DEPCMD register
3202 * after issuing a EndTransfer command. This mode is enabled
3203 * by writing GUCTL2[14]. This polling is already done in the
3204 * dwc3_send_gadget_ep_cmd() function so if the mode is
3205 * enabled, the EndTransfer command will have completed upon
3206 * returning from this function.
3207 *
3208 * This mode is NOT available on the DWC_usb31 IP.
3209 */
3210
3211 cmd = DWC3_DEPCMD_ENDTRANSFER;
3212 cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
3213 cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
3214 cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
3215 memset(&params, 0, sizeof(params));
3216 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
3217 WARN_ON_ONCE(ret);
3218 dep->resource_index = 0;
3219
3220 /*
3221 * The END_TRANSFER command will cause the controller to generate a
3222 * NoStream Event, and it's not due to the host DP NoStream rejection.
3223 * Ignore the next NoStream event.
3224 */
3225 if (dep->stream_capable)
3226 dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3227
3228 if (!interrupt)
3229 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3230 else
3231 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
3232 }
3233
3234 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3235 {
3236 u32 epnum;
3237
3238 for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3239 struct dwc3_ep *dep;
3240 int ret;
3241
3242 dep = dwc->eps[epnum];
3243 if (!dep)
3244 continue;
3245
3246 if (!(dep->flags & DWC3_EP_STALL))
3247 continue;
3248
3249 dep->flags &= ~DWC3_EP_STALL;
3250
3251 ret = dwc3_send_clear_stall_ep_cmd(dep);
3252 WARN_ON_ONCE(ret);
3253 }
3254 }
3255
3256 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3257 {
3258 int reg;
3259
3260 dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3261
3262 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3263 reg &= ~DWC3_DCTL_INITU1ENA;
3264 reg &= ~DWC3_DCTL_INITU2ENA;
3265 dwc3_gadget_dctl_write_safe(dwc, reg);
3266
3267 dwc3_disconnect_gadget(dwc);
3268
3269 dwc->gadget->speed = USB_SPEED_UNKNOWN;
3270 dwc->setup_packet_pending = false;
3271 usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3272
3273 dwc->connected = false;
3274 }
3275
3276 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
3277 {
3278 u32 reg;
3279
3280 /*
3281 * Ideally, dwc3_reset_gadget() would trigger the function
3282 * drivers to stop any active transfers through ep disable.
3283 * However, for functions which defer ep disable, such as mass
3284 * storage, we will need to rely on the call to stop active
3285 * transfers here, and avoid allowing of request queuing.
3286 */
3287 dwc->connected = false;
3288
3289 /*
3290 * WORKAROUND: DWC3 revisions <1.88a have an issue which
3291 * would cause a missing Disconnect Event if there's a
3292 * pending Setup Packet in the FIFO.
3293 *
3294 * There's no suggested workaround on the official Bug
3295 * report, which states that "unless the driver/application
3296 * is doing any special handling of a disconnect event,
3297 * there is no functional issue".
3298 *
3299 * Unfortunately, it turns out that we _do_ some special
3300 * handling of a disconnect event, namely complete all
3301 * pending transfers, notify gadget driver of the
3302 * disconnection, and so on.
3303 *
3304 * Our suggested workaround is to follow the Disconnect
3305 * Event steps here, instead, based on a setup_packet_pending
3306 * flag. Such flag gets set whenever we have a SETUP_PENDING
3307 * status for EP0 TRBs and gets cleared on XferComplete for the
3308 * same endpoint.
3309 *
3310 * Refers to:
3311 *
3312 * STAR#9000466709: RTL: Device : Disconnect event not
3313 * generated if setup packet pending in FIFO
3314 */
3315 if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
3316 if (dwc->setup_packet_pending)
3317 dwc3_gadget_disconnect_interrupt(dwc);
3318 }
3319
3320 dwc3_reset_gadget(dwc);
3321 /*
3322 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
3323 * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
3324 * needs to ensure that it sends "a DEPENDXFER command for any active
3325 * transfers."
3326 */
3327 dwc3_stop_active_transfers(dwc);
3328 dwc->connected = true;
3329
3330 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3331 reg &= ~DWC3_DCTL_TSTCTRL_MASK;
3332 dwc3_gadget_dctl_write_safe(dwc, reg);
3333 dwc->test_mode = false;
3334 dwc3_clear_stall_all_ep(dwc);
3335
3336 /* Reset device address to zero */
3337 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3338 reg &= ~(DWC3_DCFG_DEVADDR_MASK);
3339 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3340 }
3341
3342 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
3343 {
3344 struct dwc3_ep *dep;
3345 int ret;
3346 u32 reg;
3347 u8 speed;
3348
3349 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
3350 speed = reg & DWC3_DSTS_CONNECTSPD;
3351 dwc->speed = speed;
3352
3353 /*
3354 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
3355 * each time on Connect Done.
3356 *
3357 * Currently we always use the reset value. If any platform
3358 * wants to set this to a different value, we need to add a
3359 * setting and update GCTL.RAMCLKSEL here.
3360 */
3361
3362 switch (speed) {
3363 case DWC3_DSTS_SUPERSPEED_PLUS:
3364 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3365 dwc->gadget->ep0->maxpacket = 512;
3366 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3367 break;
3368 case DWC3_DSTS_SUPERSPEED:
3369 /*
3370 * WORKAROUND: DWC3 revisions <1.90a have an issue which
3371 * would cause a missing USB3 Reset event.
3372 *
3373 * In such situations, we should force a USB3 Reset
3374 * event by calling our dwc3_gadget_reset_interrupt()
3375 * routine.
3376 *
3377 * Refers to:
3378 *
3379 * STAR#9000483510: RTL: SS : USB3 reset event may
3380 * not be generated always when the link enters poll
3381 */
3382 if (DWC3_VER_IS_PRIOR(DWC3, 190A))
3383 dwc3_gadget_reset_interrupt(dwc);
3384
3385 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3386 dwc->gadget->ep0->maxpacket = 512;
3387 dwc->gadget->speed = USB_SPEED_SUPER;
3388 break;
3389 case DWC3_DSTS_HIGHSPEED:
3390 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3391 dwc->gadget->ep0->maxpacket = 64;
3392 dwc->gadget->speed = USB_SPEED_HIGH;
3393 break;
3394 case DWC3_DSTS_FULLSPEED:
3395 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3396 dwc->gadget->ep0->maxpacket = 64;
3397 dwc->gadget->speed = USB_SPEED_FULL;
3398 break;
3399 case DWC3_DSTS_LOWSPEED:
3400 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
3401 dwc->gadget->ep0->maxpacket = 8;
3402 dwc->gadget->speed = USB_SPEED_LOW;
3403 break;
3404 }
3405
3406 dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
3407
3408 /* Enable USB2 LPM Capability */
3409
3410 if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
3411 !dwc->usb2_gadget_lpm_disable &&
3412 (speed != DWC3_DSTS_SUPERSPEED) &&
3413 (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
3414 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3415 reg |= DWC3_DCFG_LPM_CAP;
3416 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3417
3418 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3419 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
3420
3421 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
3422 (dwc->is_utmi_l1_suspend << 4));
3423
3424 /*
3425 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
3426 * DCFG.LPMCap is set, core responses with an ACK and the
3427 * BESL value in the LPM token is less than or equal to LPM
3428 * NYET threshold.
3429 */
3430 WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
3431 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
3432
3433 if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
3434 reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
3435
3436 dwc3_gadget_dctl_write_safe(dwc, reg);
3437 } else {
3438 if (dwc->usb2_gadget_lpm_disable) {
3439 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3440 reg &= ~DWC3_DCFG_LPM_CAP;
3441 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3442 }
3443
3444 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3445 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
3446 dwc3_gadget_dctl_write_safe(dwc, reg);
3447 }
3448
3449 dep = dwc->eps[0];
3450 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3451 if (ret) {
3452 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3453 return;
3454 }
3455
3456 dep = dwc->eps[1];
3457 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3458 if (ret) {
3459 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3460 return;
3461 }
3462
3463 /*
3464 * Configure PHY via GUSB3PIPECTLn if required.
3465 *
3466 * Update GTXFIFOSIZn
3467 *
3468 * In both cases reset values should be sufficient.
3469 */
3470 }
3471
3472 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
3473 {
3474 /*
3475 * TODO take core out of low power mode when that's
3476 * implemented.
3477 */
3478
3479 if (dwc->gadget_driver && dwc->gadget_driver->resume) {
3480 spin_unlock(&dwc->lock);
3481 dwc->gadget_driver->resume(dwc->gadget);
3482 spin_lock(&dwc->lock);
3483 }
3484 }
3485
3486 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
3487 unsigned int evtinfo)
3488 {
3489 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3490 unsigned int pwropt;
3491
3492 /*
3493 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
3494 * Hibernation mode enabled which would show up when device detects
3495 * host-initiated U3 exit.
3496 *
3497 * In that case, device will generate a Link State Change Interrupt
3498 * from U3 to RESUME which is only necessary if Hibernation is
3499 * configured in.
3500 *
3501 * There are no functional changes due to such spurious event and we
3502 * just need to ignore it.
3503 *
3504 * Refers to:
3505 *
3506 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
3507 * operational mode
3508 */
3509 pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
3510 if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
3511 (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
3512 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
3513 (next == DWC3_LINK_STATE_RESUME)) {
3514 return;
3515 }
3516 }
3517
3518 /*
3519 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
3520 * on the link partner, the USB session might do multiple entry/exit
3521 * of low power states before a transfer takes place.
3522 *
3523 * Due to this problem, we might experience lower throughput. The
3524 * suggested workaround is to disable DCTL[12:9] bits if we're
3525 * transitioning from U1/U2 to U0 and enable those bits again
3526 * after a transfer completes and there are no pending transfers
3527 * on any of the enabled endpoints.
3528 *
3529 * This is the first half of that workaround.
3530 *
3531 * Refers to:
3532 *
3533 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
3534 * core send LGO_Ux entering U0
3535 */
3536 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3537 if (next == DWC3_LINK_STATE_U0) {
3538 u32 u1u2;
3539 u32 reg;
3540
3541 switch (dwc->link_state) {
3542 case DWC3_LINK_STATE_U1:
3543 case DWC3_LINK_STATE_U2:
3544 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3545 u1u2 = reg & (DWC3_DCTL_INITU2ENA
3546 | DWC3_DCTL_ACCEPTU2ENA
3547 | DWC3_DCTL_INITU1ENA
3548 | DWC3_DCTL_ACCEPTU1ENA);
3549
3550 if (!dwc->u1u2)
3551 dwc->u1u2 = reg & u1u2;
3552
3553 reg &= ~u1u2;
3554
3555 dwc3_gadget_dctl_write_safe(dwc, reg);
3556 break;
3557 default:
3558 /* do nothing */
3559 break;
3560 }
3561 }
3562 }
3563
3564 switch (next) {
3565 case DWC3_LINK_STATE_U1:
3566 if (dwc->speed == USB_SPEED_SUPER)
3567 dwc3_suspend_gadget(dwc);
3568 break;
3569 case DWC3_LINK_STATE_U2:
3570 case DWC3_LINK_STATE_U3:
3571 dwc3_suspend_gadget(dwc);
3572 break;
3573 case DWC3_LINK_STATE_RESUME:
3574 dwc3_resume_gadget(dwc);
3575 break;
3576 default:
3577 /* do nothing */
3578 break;
3579 }
3580
3581 dwc->link_state = next;
3582 }
3583
3584 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
3585 unsigned int evtinfo)
3586 {
3587 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3588
3589 if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
3590 dwc3_suspend_gadget(dwc);
3591
3592 dwc->link_state = next;
3593 }
3594
3595 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
3596 unsigned int evtinfo)
3597 {
3598 unsigned int is_ss = evtinfo & BIT(4);
3599
3600 /*
3601 * WORKAROUND: DWC3 revison 2.20a with hibernation support
3602 * have a known issue which can cause USB CV TD.9.23 to fail
3603 * randomly.
3604 *
3605 * Because of this issue, core could generate bogus hibernation
3606 * events which SW needs to ignore.
3607 *
3608 * Refers to:
3609 *
3610 * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
3611 * Device Fallback from SuperSpeed
3612 */
3613 if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
3614 return;
3615
3616 /* enter hibernation here */
3617 }
3618
3619 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
3620 const struct dwc3_event_devt *event)
3621 {
3622 switch (event->type) {
3623 case DWC3_DEVICE_EVENT_DISCONNECT:
3624 dwc3_gadget_disconnect_interrupt(dwc);
3625 break;
3626 case DWC3_DEVICE_EVENT_RESET:
3627 dwc3_gadget_reset_interrupt(dwc);
3628 break;
3629 case DWC3_DEVICE_EVENT_CONNECT_DONE:
3630 dwc3_gadget_conndone_interrupt(dwc);
3631 break;
3632 case DWC3_DEVICE_EVENT_WAKEUP:
3633 dwc3_gadget_wakeup_interrupt(dwc);
3634 break;
3635 case DWC3_DEVICE_EVENT_HIBER_REQ:
3636 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
3637 "unexpected hibernation event\n"))
3638 break;
3639
3640 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
3641 break;
3642 case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
3643 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
3644 break;
3645 case DWC3_DEVICE_EVENT_EOPF:
3646 /* It changed to be suspend event for version 2.30a and above */
3647 if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) {
3648 /*
3649 * Ignore suspend event until the gadget enters into
3650 * USB_STATE_CONFIGURED state.
3651 */
3652 if (dwc->gadget->state >= USB_STATE_CONFIGURED)
3653 dwc3_gadget_suspend_interrupt(dwc,
3654 event->event_info);
3655 }
3656 break;
3657 case DWC3_DEVICE_EVENT_SOF:
3658 case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
3659 case DWC3_DEVICE_EVENT_CMD_CMPL:
3660 case DWC3_DEVICE_EVENT_OVERFLOW:
3661 break;
3662 default:
3663 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
3664 }
3665 }
3666
3667 static void dwc3_process_event_entry(struct dwc3 *dwc,
3668 const union dwc3_event *event)
3669 {
3670 trace_dwc3_event(event->raw, dwc);
3671
3672 if (!event->type.is_devspec)
3673 dwc3_endpoint_interrupt(dwc, &event->depevt);
3674 else if (event->type.type == DWC3_EVENT_TYPE_DEV)
3675 dwc3_gadget_interrupt(dwc, &event->devt);
3676 else
3677 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
3678 }
3679
3680 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
3681 {
3682 struct dwc3 *dwc = evt->dwc;
3683 irqreturn_t ret = IRQ_NONE;
3684 int left;
3685 u32 reg;
3686
3687 left = evt->count;
3688
3689 if (!(evt->flags & DWC3_EVENT_PENDING))
3690 return IRQ_NONE;
3691
3692 while (left > 0) {
3693 union dwc3_event event;
3694
3695 event.raw = *(u32 *) (evt->cache + evt->lpos);
3696
3697 dwc3_process_event_entry(dwc, &event);
3698
3699 /*
3700 * FIXME we wrap around correctly to the next entry as
3701 * almost all entries are 4 bytes in size. There is one
3702 * entry which has 12 bytes which is a regular entry
3703 * followed by 8 bytes data. ATM I don't know how
3704 * things are organized if we get next to the a
3705 * boundary so I worry about that once we try to handle
3706 * that.
3707 */
3708 evt->lpos = (evt->lpos + 4) % evt->length;
3709 left -= 4;
3710 }
3711
3712 evt->count = 0;
3713 evt->flags &= ~DWC3_EVENT_PENDING;
3714 ret = IRQ_HANDLED;
3715
3716 /* Unmask interrupt */
3717 reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3718 reg &= ~DWC3_GEVNTSIZ_INTMASK;
3719 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3720
3721 if (dwc->imod_interval) {
3722 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
3723 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
3724 }
3725
3726 return ret;
3727 }
3728
3729 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
3730 {
3731 struct dwc3_event_buffer *evt = _evt;
3732 struct dwc3 *dwc = evt->dwc;
3733 unsigned long flags;
3734 irqreturn_t ret = IRQ_NONE;
3735
3736 spin_lock_irqsave(&dwc->lock, flags);
3737 ret = dwc3_process_event_buf(evt);
3738 spin_unlock_irqrestore(&dwc->lock, flags);
3739
3740 return ret;
3741 }
3742
3743 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
3744 {
3745 struct dwc3 *dwc = evt->dwc;
3746 u32 amount;
3747 u32 count;
3748 u32 reg;
3749
3750 if (pm_runtime_suspended(dwc->dev)) {
3751 pm_runtime_get(dwc->dev);
3752 disable_irq_nosync(dwc->irq_gadget);
3753 dwc->pending_events = true;
3754 return IRQ_HANDLED;
3755 }
3756
3757 /*
3758 * With PCIe legacy interrupt, test shows that top-half irq handler can
3759 * be called again after HW interrupt deassertion. Check if bottom-half
3760 * irq event handler completes before caching new event to prevent
3761 * losing events.
3762 */
3763 if (evt->flags & DWC3_EVENT_PENDING)
3764 return IRQ_HANDLED;
3765
3766 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
3767 count &= DWC3_GEVNTCOUNT_MASK;
3768 if (!count)
3769 return IRQ_NONE;
3770
3771 evt->count = count;
3772 evt->flags |= DWC3_EVENT_PENDING;
3773
3774 /* Mask interrupt */
3775 reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3776 reg |= DWC3_GEVNTSIZ_INTMASK;
3777 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3778
3779 amount = min(count, evt->length - evt->lpos);
3780 memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
3781
3782 if (amount < count)
3783 memcpy(evt->cache, evt->buf, count - amount);
3784
3785 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
3786
3787 return IRQ_WAKE_THREAD;
3788 }
3789
3790 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
3791 {
3792 struct dwc3_event_buffer *evt = _evt;
3793
3794 return dwc3_check_event_buf(evt);
3795 }
3796
3797 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
3798 {
3799 struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
3800 int irq;
3801
3802 irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
3803 if (irq > 0)
3804 goto out;
3805
3806 if (irq == -EPROBE_DEFER)
3807 goto out;
3808
3809 irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
3810 if (irq > 0)
3811 goto out;
3812
3813 if (irq == -EPROBE_DEFER)
3814 goto out;
3815
3816 irq = platform_get_irq(dwc3_pdev, 0);
3817 if (irq > 0)
3818 goto out;
3819
3820 if (!irq)
3821 irq = -EINVAL;
3822
3823 out:
3824 return irq;
3825 }
3826
3827 static void dwc_gadget_release(struct device *dev)
3828 {
3829 struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
3830
3831 kfree(gadget);
3832 }
3833
3834 /**
3835 * dwc3_gadget_init - initializes gadget related registers
3836 * @dwc: pointer to our controller context structure
3837 *
3838 * Returns 0 on success otherwise negative errno.
3839 */
3840 int dwc3_gadget_init(struct dwc3 *dwc)
3841 {
3842 int ret;
3843 int irq;
3844 struct device *dev;
3845
3846 irq = dwc3_gadget_get_irq(dwc);
3847 if (irq < 0) {
3848 ret = irq;
3849 goto err0;
3850 }
3851
3852 dwc->irq_gadget = irq;
3853
3854 dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
3855 sizeof(*dwc->ep0_trb) * 2,
3856 &dwc->ep0_trb_addr, GFP_KERNEL);
3857 if (!dwc->ep0_trb) {
3858 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
3859 ret = -ENOMEM;
3860 goto err0;
3861 }
3862
3863 dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
3864 if (!dwc->setup_buf) {
3865 ret = -ENOMEM;
3866 goto err1;
3867 }
3868
3869 dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
3870 &dwc->bounce_addr, GFP_KERNEL);
3871 if (!dwc->bounce) {
3872 ret = -ENOMEM;
3873 goto err2;
3874 }
3875
3876 init_completion(&dwc->ep0_in_setup);
3877 dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
3878 if (!dwc->gadget) {
3879 ret = -ENOMEM;
3880 goto err3;
3881 }
3882
3883
3884 usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
3885 dev = &dwc->gadget->dev;
3886 dev->platform_data = dwc;
3887 dwc->gadget->ops = &dwc3_gadget_ops;
3888 dwc->gadget->speed = USB_SPEED_UNKNOWN;
3889 dwc->gadget->sg_supported = true;
3890 dwc->gadget->name = "dwc3-gadget";
3891 dwc->gadget->lpm_capable = !dwc->usb2_gadget_lpm_disable;
3892
3893 /*
3894 * FIXME We might be setting max_speed to <SUPER, however versions
3895 * <2.20a of dwc3 have an issue with metastability (documented
3896 * elsewhere in this driver) which tells us we can't set max speed to
3897 * anything lower than SUPER.
3898 *
3899 * Because gadget.max_speed is only used by composite.c and function
3900 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3901 * to happen so we avoid sending SuperSpeed Capability descriptor
3902 * together with our BOS descriptor as that could confuse host into
3903 * thinking we can handle super speed.
3904 *
3905 * Note that, in fact, we won't even support GetBOS requests when speed
3906 * is less than super speed because we don't have means, yet, to tell
3907 * composite.c that we are USB 2.0 + LPM ECN.
3908 */
3909 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
3910 !dwc->dis_metastability_quirk)
3911 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
3912 dwc->revision);
3913
3914 dwc->gadget->max_speed = dwc->maximum_speed;
3915
3916 /*
3917 * REVISIT: Here we should clear all pending IRQs to be
3918 * sure we're starting from a well known location.
3919 */
3920
3921 ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
3922 if (ret)
3923 goto err4;
3924
3925 ret = usb_add_gadget(dwc->gadget);
3926 if (ret) {
3927 dev_err(dwc->dev, "failed to add gadget\n");
3928 goto err5;
3929 }
3930
3931 dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
3932
3933 return 0;
3934
3935 err5:
3936 dwc3_gadget_free_endpoints(dwc);
3937 err4:
3938 usb_put_gadget(dwc->gadget);
3939 dwc->gadget = NULL;
3940 err3:
3941 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3942 dwc->bounce_addr);
3943
3944 err2:
3945 kfree(dwc->setup_buf);
3946
3947 err1:
3948 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3949 dwc->ep0_trb, dwc->ep0_trb_addr);
3950
3951 err0:
3952 return ret;
3953 }
3954
3955 /* -------------------------------------------------------------------------- */
3956
3957 void dwc3_gadget_exit(struct dwc3 *dwc)
3958 {
3959 if (!dwc->gadget)
3960 return;
3961
3962 usb_del_gadget(dwc->gadget);
3963 dwc3_gadget_free_endpoints(dwc);
3964 usb_put_gadget(dwc->gadget);
3965 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3966 dwc->bounce_addr);
3967 kfree(dwc->setup_buf);
3968 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3969 dwc->ep0_trb, dwc->ep0_trb_addr);
3970 }
3971
3972 int dwc3_gadget_suspend(struct dwc3 *dwc)
3973 {
3974 if (!dwc->gadget_driver)
3975 return 0;
3976
3977 dwc3_gadget_run_stop(dwc, false, false);
3978 dwc3_disconnect_gadget(dwc);
3979 __dwc3_gadget_stop(dwc);
3980
3981 return 0;
3982 }
3983
3984 int dwc3_gadget_resume(struct dwc3 *dwc)
3985 {
3986 int ret;
3987
3988 if (!dwc->gadget_driver)
3989 return 0;
3990
3991 ret = __dwc3_gadget_start(dwc);
3992 if (ret < 0)
3993 goto err0;
3994
3995 ret = dwc3_gadget_run_stop(dwc, true, false);
3996 if (ret < 0)
3997 goto err1;
3998
3999 return 0;
4000
4001 err1:
4002 __dwc3_gadget_stop(dwc);
4003
4004 err0:
4005 return ret;
4006 }
4007
4008 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4009 {
4010 if (dwc->pending_events) {
4011 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4012 dwc->pending_events = false;
4013 enable_irq(dwc->irq_gadget);
4014 }
4015 }