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