1 // SPDX-License-Identifier: GPL-2.0
3 * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
5 * Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com
7 * Authors: Felipe Balbi <balbi@ti.com>,
8 * Sebastian Andrzej Siewior <bigeasy@linutronix.de>
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>
19 #include <linux/list.h>
20 #include <linux/dma-mapping.h>
22 #include <linux/usb/ch9.h>
23 #include <linux/usb/gadget.h>
30 #define DWC3_ALIGN_FRAME(d, n) (((d)->frame_number + ((d)->interval * (n))) \
31 & ~((d)->interval - 1))
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)
38 * Caller should take care of locking. This function will return 0 on
39 * success or -EINVAL if wrong Test Selector is passed.
41 int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
45 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
46 reg &= ~DWC3_DCTL_TSTCTRL_MASK;
51 case USB_TEST_SE0_NAK:
53 case USB_TEST_FORCE_ENABLE:
60 dwc3_gadget_dctl_write_safe(dwc, reg);
66 * dwc3_gadget_get_link_state - gets current state of usb link
67 * @dwc: pointer to our context structure
69 * Caller should take care of locking. This function will
70 * return the link state on success (>= 0) or -ETIMEDOUT.
72 int dwc3_gadget_get_link_state(struct dwc3 *dwc)
76 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
78 return DWC3_DSTS_USBLNKST(reg);
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
86 * Caller should take care of locking. This function will
87 * return 0 on success or -ETIMEDOUT.
89 int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
95 * Wait until device controller is ready. Only applies to 1.94a and
98 if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) {
100 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
101 if (reg & DWC3_DSTS_DCNRD)
111 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
112 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
114 /* set no action before sending new link state change */
115 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
117 /* set requested state */
118 reg |= DWC3_DCTL_ULSTCHNGREQ(state);
119 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
122 * The following code is racy when called from dwc3_gadget_wakeup,
123 * and is not needed, at least on newer versions
125 if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
128 /* wait for a change in DSTS */
131 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
133 if (DWC3_DSTS_USBLNKST(reg) == state)
143 * dwc3_ep_inc_trb - increment a trb index.
144 * @index: Pointer to the TRB index to increment.
146 * The index should never point to the link TRB. After incrementing,
147 * if it is point to the link TRB, wrap around to the beginning. The
148 * link TRB is always at the last TRB entry.
150 static void dwc3_ep_inc_trb(u8 *index)
153 if (*index == (DWC3_TRB_NUM - 1))
158 * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
159 * @dep: The endpoint whose enqueue pointer we're incrementing
161 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
163 dwc3_ep_inc_trb(&dep->trb_enqueue);
167 * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
168 * @dep: The endpoint whose enqueue pointer we're incrementing
170 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
172 dwc3_ep_inc_trb(&dep->trb_dequeue);
175 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
176 struct dwc3_request *req, int status)
178 struct dwc3 *dwc = dep->dwc;
180 list_del(&req->list);
182 req->needs_extra_trb = false;
184 if (req->request.status == -EINPROGRESS)
185 req->request.status = status;
188 usb_gadget_unmap_request_by_dev(dwc->sysdev,
189 &req->request, req->direction);
192 trace_dwc3_gadget_giveback(req);
195 pm_runtime_put(dwc->dev);
199 * dwc3_gadget_giveback - call struct usb_request's ->complete callback
200 * @dep: The endpoint to whom the request belongs to
201 * @req: The request we're giving back
202 * @status: completion code for the request
204 * Must be called with controller's lock held and interrupts disabled. This
205 * function will unmap @req and call its ->complete() callback to notify upper
206 * layers that it has completed.
208 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
211 struct dwc3 *dwc = dep->dwc;
213 dwc3_gadget_del_and_unmap_request(dep, req, status);
214 req->status = DWC3_REQUEST_STATUS_COMPLETED;
216 spin_unlock(&dwc->lock);
217 usb_gadget_giveback_request(&dep->endpoint, &req->request);
218 spin_lock(&dwc->lock);
222 * dwc3_send_gadget_generic_command - issue a generic command for the controller
223 * @dwc: pointer to the controller context
224 * @cmd: the command to be issued
225 * @param: command parameter
227 * Caller should take care of locking. Issue @cmd with a given @param to @dwc
228 * and wait for its completion.
230 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
238 dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
239 dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
242 reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
243 if (!(reg & DWC3_DGCMD_CMDACT)) {
244 status = DWC3_DGCMD_STATUS(reg);
256 trace_dwc3_gadget_generic_cmd(cmd, param, status);
261 static int __dwc3_gadget_wakeup(struct dwc3 *dwc);
264 * dwc3_send_gadget_ep_cmd - issue an endpoint command
265 * @dep: the endpoint to which the command is going to be issued
266 * @cmd: the command to be issued
267 * @params: parameters to the command
269 * Caller should handle locking. This function will issue @cmd with given
270 * @params to @dep and wait for its completion.
272 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd,
273 struct dwc3_gadget_ep_cmd_params *params)
275 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
276 struct dwc3 *dwc = dep->dwc;
278 u32 saved_config = 0;
285 * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or
286 * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an
289 * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY
290 * settings. Restore them after the command is completed.
292 * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2
294 if (dwc->gadget->speed <= USB_SPEED_HIGH) {
295 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
296 if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
297 saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
298 reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
301 if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
302 saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
303 reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
307 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
310 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
314 * Initiate remote wakeup if the link state is in U3 when
315 * operating in SS/SSP or L1/L2 when operating in HS/FS. If the
316 * link state is in U1/U2, no remote wakeup is needed. The Start
317 * Transfer command will initiate the link recovery.
319 link_state = dwc3_gadget_get_link_state(dwc);
320 switch (link_state) {
321 case DWC3_LINK_STATE_U2:
322 if (dwc->gadget->speed >= USB_SPEED_SUPER)
326 case DWC3_LINK_STATE_U3:
327 ret = __dwc3_gadget_wakeup(dwc);
328 dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
334 dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
335 dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
336 dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
339 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
340 * not relying on XferNotReady, we can make use of a special "No
341 * Response Update Transfer" command where we should clear both CmdAct
344 * With this, we don't need to wait for command completion and can
345 * straight away issue further commands to the endpoint.
347 * NOTICE: We're making an assumption that control endpoints will never
348 * make use of Update Transfer command. This is a safe assumption
349 * because we can never have more than one request at a time with
350 * Control Endpoints. If anybody changes that assumption, this chunk
351 * needs to be updated accordingly.
353 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
354 !usb_endpoint_xfer_isoc(desc))
355 cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
357 cmd |= DWC3_DEPCMD_CMDACT;
359 dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
361 if (!(cmd & DWC3_DEPCMD_CMDACT)) {
367 reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
368 if (!(reg & DWC3_DEPCMD_CMDACT)) {
369 cmd_status = DWC3_DEPCMD_STATUS(reg);
371 switch (cmd_status) {
375 case DEPEVT_TRANSFER_NO_RESOURCE:
376 dev_WARN(dwc->dev, "No resource for %s\n",
380 case DEPEVT_TRANSFER_BUS_EXPIRY:
382 * SW issues START TRANSFER command to
383 * isochronous ep with future frame interval. If
384 * future interval time has already passed when
385 * core receives the command, it will respond
386 * with an error status of 'Bus Expiry'.
388 * Instead of always returning -EINVAL, let's
389 * give a hint to the gadget driver that this is
390 * the case by returning -EAGAIN.
395 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
404 cmd_status = -ETIMEDOUT;
408 trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
410 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
412 dep->flags |= DWC3_EP_TRANSFER_STARTED;
414 if (ret != -ETIMEDOUT)
415 dwc3_gadget_ep_get_transfer_index(dep);
419 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
421 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
427 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
429 struct dwc3 *dwc = dep->dwc;
430 struct dwc3_gadget_ep_cmd_params params;
431 u32 cmd = DWC3_DEPCMD_CLEARSTALL;
434 * As of core revision 2.60a the recommended programming model
435 * is to set the ClearPendIN bit when issuing a Clear Stall EP
436 * command for IN endpoints. This is to prevent an issue where
437 * some (non-compliant) hosts may not send ACK TPs for pending
438 * IN transfers due to a mishandled error condition. Synopsys
441 if (dep->direction &&
442 !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
443 (dwc->gadget->speed >= USB_SPEED_SUPER))
444 cmd |= DWC3_DEPCMD_CLEARPENDIN;
446 memset(¶ms, 0, sizeof(params));
448 return dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
451 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
452 struct dwc3_trb *trb)
454 u32 offset = (char *) trb - (char *) dep->trb_pool;
456 return dep->trb_pool_dma + offset;
459 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
461 struct dwc3 *dwc = dep->dwc;
466 dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
467 sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
468 &dep->trb_pool_dma, GFP_KERNEL);
469 if (!dep->trb_pool) {
470 dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
478 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
480 struct dwc3 *dwc = dep->dwc;
482 dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
483 dep->trb_pool, dep->trb_pool_dma);
485 dep->trb_pool = NULL;
486 dep->trb_pool_dma = 0;
489 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
491 struct dwc3_gadget_ep_cmd_params params;
493 memset(¶ms, 0x00, sizeof(params));
495 params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
497 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
502 * dwc3_gadget_start_config - configure ep resources
503 * @dep: endpoint that is being enabled
505 * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
506 * completion, it will set Transfer Resource for all available endpoints.
508 * The assignment of transfer resources cannot perfectly follow the data book
509 * due to the fact that the controller driver does not have all knowledge of the
510 * configuration in advance. It is given this information piecemeal by the
511 * composite gadget framework after every SET_CONFIGURATION and
512 * SET_INTERFACE. Trying to follow the databook programming model in this
513 * scenario can cause errors. For two reasons:
515 * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
516 * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
517 * incorrect in the scenario of multiple interfaces.
519 * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
520 * endpoint on alt setting (8.1.6).
522 * The following simplified method is used instead:
524 * All hardware endpoints can be assigned a transfer resource and this setting
525 * will stay persistent until either a core reset or hibernation. So whenever we
526 * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
527 * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
528 * guaranteed that there are as many transfer resources as endpoints.
530 * This function is called for each endpoint when it is being enabled but is
531 * triggered only when called for EP0-out, which always happens first, and which
532 * should only happen in one of the above conditions.
534 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
536 struct dwc3_gadget_ep_cmd_params params;
545 memset(¶ms, 0x00, sizeof(params));
546 cmd = DWC3_DEPCMD_DEPSTARTCFG;
549 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
553 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
554 struct dwc3_ep *dep = dwc->eps[i];
559 ret = dwc3_gadget_set_xfer_resource(dep);
567 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
569 const struct usb_ss_ep_comp_descriptor *comp_desc;
570 const struct usb_endpoint_descriptor *desc;
571 struct dwc3_gadget_ep_cmd_params params;
572 struct dwc3 *dwc = dep->dwc;
574 comp_desc = dep->endpoint.comp_desc;
575 desc = dep->endpoint.desc;
577 memset(¶ms, 0x00, sizeof(params));
579 params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
580 | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
582 /* Burst size is only needed in SuperSpeed mode */
583 if (dwc->gadget->speed >= USB_SPEED_SUPER) {
584 u32 burst = dep->endpoint.maxburst;
586 params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
589 params.param0 |= action;
590 if (action == DWC3_DEPCFG_ACTION_RESTORE)
591 params.param2 |= dep->saved_state;
593 if (usb_endpoint_xfer_control(desc))
594 params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
596 if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
597 params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
599 if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
600 params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
601 | DWC3_DEPCFG_XFER_COMPLETE_EN
602 | DWC3_DEPCFG_STREAM_EVENT_EN;
603 dep->stream_capable = true;
606 if (!usb_endpoint_xfer_control(desc))
607 params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
610 * We are doing 1:1 mapping for endpoints, meaning
611 * Physical Endpoints 2 maps to Logical Endpoint 2 and
612 * so on. We consider the direction bit as part of the physical
613 * endpoint number. So USB endpoint 0x81 is 0x03.
615 params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
618 * We must use the lower 16 TX FIFOs even though
622 params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
624 if (desc->bInterval) {
628 * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
630 * NOTE: The programming guide incorrectly stated bInterval_m1
631 * must be set to 0 when operating in fullspeed. Internally the
632 * controller does not have this limitation. See DWC_usb3x
633 * programming guide section 3.2.2.1.
635 bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
637 if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
638 dwc->gadget->speed == USB_SPEED_FULL)
639 dep->interval = desc->bInterval;
641 dep->interval = 1 << (desc->bInterval - 1);
643 params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
646 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, ¶ms);
649 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
653 * dwc3_gadget_calc_tx_fifo_size - calculates the txfifo size value
654 * @dwc: pointer to the DWC3 context
655 * @nfifos: number of fifos to calculate for
657 * Calculates the size value based on the equation below:
659 * DWC3 revision 280A and prior:
660 * fifo_size = mult * (max_packet / mdwidth) + 1;
662 * DWC3 revision 290A and onwards:
663 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
665 * The max packet size is set to 1024, as the txfifo requirements mainly apply
666 * to super speed USB use cases. However, it is safe to overestimate the fifo
667 * allocations for other scenarios, i.e. high speed USB.
669 static int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult)
671 int max_packet = 1024;
675 mdwidth = dwc3_mdwidth(dwc);
677 /* MDWIDTH is represented in bits, we need it in bytes */
680 if (DWC3_VER_IS_PRIOR(DWC3, 290A))
681 fifo_size = mult * (max_packet / mdwidth) + 1;
683 fifo_size = mult * ((max_packet + mdwidth) / mdwidth) + 1;
688 * dwc3_gadget_clear_tx_fifo_size - Clears txfifo allocation
689 * @dwc: pointer to the DWC3 context
691 * Iterates through all the endpoint registers and clears the previous txfifo
694 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc)
701 if (!dwc->do_fifo_resize)
704 /* Read ep0IN related TXFIFO size */
706 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
707 if (DWC3_IP_IS(DWC3))
708 fifo_depth = DWC3_GTXFIFOSIZ_TXFDEP(size);
710 fifo_depth = DWC31_GTXFIFOSIZ_TXFDEP(size);
712 dwc->last_fifo_depth = fifo_depth;
713 /* Clear existing TXFIFO for all IN eps except ep0 */
714 for (num = 3; num < min_t(int, dwc->num_eps, DWC3_ENDPOINTS_NUM);
717 /* Don't change TXFRAMNUM on usb31 version */
718 size = DWC3_IP_IS(DWC3) ? 0 :
719 dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1)) &
720 DWC31_GTXFIFOSIZ_TXFRAMNUM;
722 dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1), size);
723 dep->flags &= ~DWC3_EP_TXFIFO_RESIZED;
725 dwc->num_ep_resized = 0;
729 * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
730 * @dwc: pointer to our context structure
732 * This function will a best effort FIFO allocation in order
733 * to improve FIFO usage and throughput, while still allowing
734 * us to enable as many endpoints as possible.
736 * Keep in mind that this operation will be highly dependent
737 * on the configured size for RAM1 - which contains TxFifo -,
738 * the amount of endpoints enabled on coreConsultant tool, and
739 * the width of the Master Bus.
741 * In general, FIFO depths are represented with the following equation:
743 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
745 * In conjunction with dwc3_gadget_check_config(), this resizing logic will
746 * ensure that all endpoints will have enough internal memory for one max
747 * packet per endpoint.
749 static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep)
751 struct dwc3 *dwc = dep->dwc;
762 if (!dwc->do_fifo_resize)
765 /* resize IN endpoints except ep0 */
766 if (!usb_endpoint_dir_in(dep->endpoint.desc) || dep->number <= 1)
769 /* bail if already resized */
770 if (dep->flags & DWC3_EP_TXFIFO_RESIZED)
773 ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
775 if ((dep->endpoint.maxburst > 1 &&
776 usb_endpoint_xfer_bulk(dep->endpoint.desc)) ||
777 usb_endpoint_xfer_isoc(dep->endpoint.desc))
780 if (dep->endpoint.maxburst > 6 &&
781 usb_endpoint_xfer_bulk(dep->endpoint.desc) && DWC3_IP_IS(DWC31))
782 num_fifos = dwc->tx_fifo_resize_max_num;
784 /* FIFO size for a single buffer */
785 fifo = dwc3_gadget_calc_tx_fifo_size(dwc, 1);
787 /* Calculate the number of remaining EPs w/o any FIFO */
788 num_in_ep = dwc->max_cfg_eps;
789 num_in_ep -= dwc->num_ep_resized;
791 /* Reserve at least one FIFO for the number of IN EPs */
792 min_depth = num_in_ep * (fifo + 1);
793 remaining = ram1_depth - min_depth - dwc->last_fifo_depth;
794 remaining = max_t(int, 0, remaining);
796 * We've already reserved 1 FIFO per EP, so check what we can fit in
797 * addition to it. If there is not enough remaining space, allocate
798 * all the remaining space to the EP.
800 fifo_size = (num_fifos - 1) * fifo;
801 if (remaining < fifo_size)
802 fifo_size = remaining;
805 /* Last increment according to the TX FIFO size equation */
808 /* Check if TXFIFOs start at non-zero addr */
809 tmp = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
810 fifo_0_start = DWC3_GTXFIFOSIZ_TXFSTADDR(tmp);
812 fifo_size |= (fifo_0_start + (dwc->last_fifo_depth << 16));
813 if (DWC3_IP_IS(DWC3))
814 dwc->last_fifo_depth += DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
816 dwc->last_fifo_depth += DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
818 /* Check fifo size allocation doesn't exceed available RAM size. */
819 if (dwc->last_fifo_depth >= ram1_depth) {
820 dev_err(dwc->dev, "Fifosize(%d) > RAM size(%d) %s depth:%d\n",
821 dwc->last_fifo_depth, ram1_depth,
822 dep->endpoint.name, fifo_size);
823 if (DWC3_IP_IS(DWC3))
824 fifo_size = DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
826 fifo_size = DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
828 dwc->last_fifo_depth -= fifo_size;
832 dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1), fifo_size);
833 dep->flags |= DWC3_EP_TXFIFO_RESIZED;
834 dwc->num_ep_resized++;
840 * __dwc3_gadget_ep_enable - initializes a hw endpoint
841 * @dep: endpoint to be initialized
842 * @action: one of INIT, MODIFY or RESTORE
844 * Caller should take care of locking. Execute all necessary commands to
845 * initialize a HW endpoint so it can be used by a gadget driver.
847 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
849 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
850 struct dwc3 *dwc = dep->dwc;
855 if (!(dep->flags & DWC3_EP_ENABLED)) {
856 ret = dwc3_gadget_resize_tx_fifos(dep);
860 ret = dwc3_gadget_start_config(dep);
865 ret = dwc3_gadget_set_ep_config(dep, action);
869 if (!(dep->flags & DWC3_EP_ENABLED)) {
870 struct dwc3_trb *trb_st_hw;
871 struct dwc3_trb *trb_link;
873 dep->type = usb_endpoint_type(desc);
874 dep->flags |= DWC3_EP_ENABLED;
876 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
877 reg |= DWC3_DALEPENA_EP(dep->number);
878 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
880 if (usb_endpoint_xfer_control(desc))
883 /* Initialize the TRB ring */
884 dep->trb_dequeue = 0;
885 dep->trb_enqueue = 0;
886 memset(dep->trb_pool, 0,
887 sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
889 /* Link TRB. The HWO bit is never reset */
890 trb_st_hw = &dep->trb_pool[0];
892 trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
893 trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
894 trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
895 trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
896 trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
900 * Issue StartTransfer here with no-op TRB so we can always rely on No
901 * Response Update Transfer command.
903 if (usb_endpoint_xfer_bulk(desc) ||
904 usb_endpoint_xfer_int(desc)) {
905 struct dwc3_gadget_ep_cmd_params params;
906 struct dwc3_trb *trb;
910 memset(¶ms, 0, sizeof(params));
911 trb = &dep->trb_pool[0];
912 trb_dma = dwc3_trb_dma_offset(dep, trb);
914 params.param0 = upper_32_bits(trb_dma);
915 params.param1 = lower_32_bits(trb_dma);
917 cmd = DWC3_DEPCMD_STARTTRANSFER;
919 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
923 if (dep->stream_capable) {
925 * For streams, at start, there maybe a race where the
926 * host primes the endpoint before the function driver
927 * queues a request to initiate a stream. In that case,
928 * the controller will not see the prime to generate the
929 * ERDY and start stream. To workaround this, issue a
930 * no-op TRB as normal, but end it immediately. As a
931 * result, when the function driver queues the request,
932 * the next START_TRANSFER command will cause the
933 * controller to generate an ERDY to initiate the
936 dwc3_stop_active_transfer(dep, true, true);
939 * All stream eps will reinitiate stream on NoStream
940 * rejection until we can determine that the host can
941 * prime after the first transfer.
943 * However, if the controller is capable of
944 * TXF_FLUSH_BYPASS, then IN direction endpoints will
945 * automatically restart the stream without the driver
948 if (!dep->direction ||
949 !(dwc->hwparams.hwparams9 &
950 DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
951 dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
956 trace_dwc3_gadget_ep_enable(dep);
961 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
963 struct dwc3_request *req;
965 dwc3_stop_active_transfer(dep, true, false);
967 /* - giveback all requests to gadget driver */
968 while (!list_empty(&dep->started_list)) {
969 req = next_request(&dep->started_list);
971 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
974 while (!list_empty(&dep->pending_list)) {
975 req = next_request(&dep->pending_list);
977 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
980 while (!list_empty(&dep->cancelled_list)) {
981 req = next_request(&dep->cancelled_list);
983 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
988 * __dwc3_gadget_ep_disable - disables a hw endpoint
989 * @dep: the endpoint to disable
991 * This function undoes what __dwc3_gadget_ep_enable did and also removes
992 * requests which are currently being processed by the hardware and those which
993 * are not yet scheduled.
995 * Caller should take care of locking.
997 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
999 struct dwc3 *dwc = dep->dwc;
1002 trace_dwc3_gadget_ep_disable(dep);
1004 /* make sure HW endpoint isn't stalled */
1005 if (dep->flags & DWC3_EP_STALL)
1006 __dwc3_gadget_ep_set_halt(dep, 0, false);
1008 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
1009 reg &= ~DWC3_DALEPENA_EP(dep->number);
1010 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
1012 /* Clear out the ep descriptors for non-ep0 */
1013 if (dep->number > 1) {
1014 dep->endpoint.comp_desc = NULL;
1015 dep->endpoint.desc = NULL;
1018 dwc3_remove_requests(dwc, dep);
1020 dep->stream_capable = false;
1022 dep->flags &= DWC3_EP_TXFIFO_RESIZED;
1027 /* -------------------------------------------------------------------------- */
1029 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
1030 const struct usb_endpoint_descriptor *desc)
1035 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
1040 /* -------------------------------------------------------------------------- */
1042 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
1043 const struct usb_endpoint_descriptor *desc)
1045 struct dwc3_ep *dep;
1047 unsigned long flags;
1050 if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
1051 pr_debug("dwc3: invalid parameters\n");
1055 if (!desc->wMaxPacketSize) {
1056 pr_debug("dwc3: missing wMaxPacketSize\n");
1060 dep = to_dwc3_ep(ep);
1063 if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
1064 "%s is already enabled\n",
1068 spin_lock_irqsave(&dwc->lock, flags);
1069 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1070 spin_unlock_irqrestore(&dwc->lock, flags);
1075 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
1077 struct dwc3_ep *dep;
1079 unsigned long flags;
1083 pr_debug("dwc3: invalid parameters\n");
1087 dep = to_dwc3_ep(ep);
1090 if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
1091 "%s is already disabled\n",
1095 spin_lock_irqsave(&dwc->lock, flags);
1096 ret = __dwc3_gadget_ep_disable(dep);
1097 spin_unlock_irqrestore(&dwc->lock, flags);
1102 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
1105 struct dwc3_request *req;
1106 struct dwc3_ep *dep = to_dwc3_ep(ep);
1108 req = kzalloc(sizeof(*req), gfp_flags);
1112 req->direction = dep->direction;
1113 req->epnum = dep->number;
1115 req->status = DWC3_REQUEST_STATUS_UNKNOWN;
1117 trace_dwc3_alloc_request(req);
1119 return &req->request;
1122 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
1123 struct usb_request *request)
1125 struct dwc3_request *req = to_dwc3_request(request);
1127 trace_dwc3_free_request(req);
1132 * dwc3_ep_prev_trb - returns the previous TRB in the ring
1133 * @dep: The endpoint with the TRB ring
1134 * @index: The index of the current TRB in the ring
1136 * Returns the TRB prior to the one pointed to by the index. If the
1137 * index is 0, we will wrap backwards, skip the link TRB, and return
1138 * the one just before that.
1140 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1145 tmp = DWC3_TRB_NUM - 1;
1147 return &dep->trb_pool[tmp - 1];
1150 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1155 * If the enqueue & dequeue are equal then the TRB ring is either full
1156 * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
1157 * pending to be processed by the driver.
1159 if (dep->trb_enqueue == dep->trb_dequeue) {
1161 * If there is any request remained in the started_list at
1162 * this point, that means there is no TRB available.
1164 if (!list_empty(&dep->started_list))
1167 return DWC3_TRB_NUM - 1;
1170 trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1171 trbs_left &= (DWC3_TRB_NUM - 1);
1173 if (dep->trb_dequeue < dep->trb_enqueue)
1179 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
1180 dma_addr_t dma, unsigned int length, unsigned int chain,
1181 unsigned int node, unsigned int stream_id,
1182 unsigned int short_not_ok, unsigned int no_interrupt,
1183 unsigned int is_last, bool must_interrupt)
1185 struct dwc3 *dwc = dep->dwc;
1186 struct usb_gadget *gadget = dwc->gadget;
1187 enum usb_device_speed speed = gadget->speed;
1189 trb->size = DWC3_TRB_SIZE_LENGTH(length);
1190 trb->bpl = lower_32_bits(dma);
1191 trb->bph = upper_32_bits(dma);
1193 switch (usb_endpoint_type(dep->endpoint.desc)) {
1194 case USB_ENDPOINT_XFER_CONTROL:
1195 trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
1198 case USB_ENDPOINT_XFER_ISOC:
1200 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
1203 * USB Specification 2.0 Section 5.9.2 states that: "If
1204 * there is only a single transaction in the microframe,
1205 * only a DATA0 data packet PID is used. If there are
1206 * two transactions per microframe, DATA1 is used for
1207 * the first transaction data packet and DATA0 is used
1208 * for the second transaction data packet. If there are
1209 * three transactions per microframe, DATA2 is used for
1210 * the first transaction data packet, DATA1 is used for
1211 * the second, and DATA0 is used for the third."
1213 * IOW, we should satisfy the following cases:
1215 * 1) length <= maxpacket
1218 * 2) maxpacket < length <= (2 * maxpacket)
1221 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1222 * - DATA2, DATA1, DATA0
1224 if (speed == USB_SPEED_HIGH) {
1225 struct usb_ep *ep = &dep->endpoint;
1226 unsigned int mult = 2;
1227 unsigned int maxp = usb_endpoint_maxp(ep->desc);
1229 if (length <= (2 * maxp))
1235 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1238 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1241 /* always enable Interrupt on Missed ISOC */
1242 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1245 case USB_ENDPOINT_XFER_BULK:
1246 case USB_ENDPOINT_XFER_INT:
1247 trb->ctrl = DWC3_TRBCTL_NORMAL;
1251 * This is only possible with faulty memory because we
1252 * checked it already :)
1254 dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1255 usb_endpoint_type(dep->endpoint.desc));
1259 * Enable Continue on Short Packet
1260 * when endpoint is not a stream capable
1262 if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1263 if (!dep->stream_capable)
1264 trb->ctrl |= DWC3_TRB_CTRL_CSP;
1267 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1270 if ((!no_interrupt && !chain) || must_interrupt)
1271 trb->ctrl |= DWC3_TRB_CTRL_IOC;
1274 trb->ctrl |= DWC3_TRB_CTRL_CHN;
1275 else if (dep->stream_capable && is_last)
1276 trb->ctrl |= DWC3_TRB_CTRL_LST;
1278 if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1279 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1281 trb->ctrl |= DWC3_TRB_CTRL_HWO;
1283 dwc3_ep_inc_enq(dep);
1285 trace_dwc3_prepare_trb(dep, trb);
1289 * dwc3_prepare_one_trb - setup one TRB from one request
1290 * @dep: endpoint for which this request is prepared
1291 * @req: dwc3_request pointer
1292 * @trb_length: buffer size of the TRB
1293 * @chain: should this TRB be chained to the next?
1294 * @node: only for isochronous endpoints. First TRB needs different type.
1295 * @use_bounce_buffer: set to use bounce buffer
1296 * @must_interrupt: set to interrupt on TRB completion
1298 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1299 struct dwc3_request *req, unsigned int trb_length,
1300 unsigned int chain, unsigned int node, bool use_bounce_buffer,
1301 bool must_interrupt)
1303 struct dwc3_trb *trb;
1305 unsigned int stream_id = req->request.stream_id;
1306 unsigned int short_not_ok = req->request.short_not_ok;
1307 unsigned int no_interrupt = req->request.no_interrupt;
1308 unsigned int is_last = req->request.is_last;
1310 if (use_bounce_buffer)
1311 dma = dep->dwc->bounce_addr;
1312 else if (req->request.num_sgs > 0)
1313 dma = sg_dma_address(req->start_sg);
1315 dma = req->request.dma;
1317 trb = &dep->trb_pool[dep->trb_enqueue];
1320 dwc3_gadget_move_started_request(req);
1322 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1327 __dwc3_prepare_one_trb(dep, trb, dma, trb_length, chain, node,
1328 stream_id, short_not_ok, no_interrupt, is_last,
1332 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1334 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1335 unsigned int rem = req->request.length % maxp;
1337 if ((req->request.length && req->request.zero && !rem &&
1338 !usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1339 (!req->direction && rem))
1346 * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1347 * @dep: The endpoint that the request belongs to
1348 * @req: The request to prepare
1349 * @entry_length: The last SG entry size
1350 * @node: Indicates whether this is not the first entry (for isoc only)
1352 * Return the number of TRBs prepared.
1354 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1355 struct dwc3_request *req, unsigned int entry_length,
1358 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1359 unsigned int rem = req->request.length % maxp;
1360 unsigned int num_trbs = 1;
1362 if (dwc3_needs_extra_trb(dep, req))
1365 if (dwc3_calc_trbs_left(dep) < num_trbs)
1368 req->needs_extra_trb = num_trbs > 1;
1370 /* Prepare a normal TRB */
1371 if (req->direction || req->request.length)
1372 dwc3_prepare_one_trb(dep, req, entry_length,
1373 req->needs_extra_trb, node, false, false);
1375 /* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1376 if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1377 dwc3_prepare_one_trb(dep, req,
1378 req->direction ? 0 : maxp - rem,
1379 false, 1, true, false);
1384 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1385 struct dwc3_request *req)
1387 struct scatterlist *sg = req->start_sg;
1388 struct scatterlist *s;
1390 unsigned int length = req->request.length;
1391 unsigned int remaining = req->request.num_mapped_sgs
1392 - req->num_queued_sgs;
1393 unsigned int num_trbs = req->num_trbs;
1394 bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1397 * If we resume preparing the request, then get the remaining length of
1398 * the request and resume where we left off.
1400 for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1401 length -= sg_dma_len(s);
1403 for_each_sg(sg, s, remaining, i) {
1404 unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1405 unsigned int trb_length;
1406 bool must_interrupt = false;
1407 bool last_sg = false;
1409 trb_length = min_t(unsigned int, length, sg_dma_len(s));
1411 length -= trb_length;
1414 * IOMMU driver is coalescing the list of sgs which shares a
1415 * page boundary into one and giving it to USB driver. With
1416 * this the number of sgs mapped is not equal to the number of
1417 * sgs passed. So mark the chain bit to false if it isthe last
1420 if ((i == remaining - 1) || !length)
1427 if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1431 * Look ahead to check if we have enough TRBs for the
1432 * next SG entry. If not, set interrupt on this TRB to
1433 * resume preparing the next SG entry when more TRBs are
1436 if (num_trbs_left == 1 || (needs_extra_trb &&
1437 num_trbs_left <= 2 &&
1438 sg_dma_len(sg_next(s)) >= length))
1439 must_interrupt = true;
1441 dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1446 * There can be a situation where all sgs in sglist are not
1447 * queued because of insufficient trb number. To handle this
1448 * case, update start_sg to next sg to be queued, so that
1449 * we have free trbs we can continue queuing from where we
1450 * previously stopped
1453 req->start_sg = sg_next(s);
1455 req->num_queued_sgs++;
1456 req->num_pending_sgs--;
1459 * The number of pending SG entries may not correspond to the
1460 * number of mapped SG entries. If all the data are queued, then
1461 * don't include unused SG entries.
1464 req->num_pending_sgs = 0;
1472 return req->num_trbs - num_trbs;
1475 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1476 struct dwc3_request *req)
1478 return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1482 * dwc3_prepare_trbs - setup TRBs from requests
1483 * @dep: endpoint for which requests are being prepared
1485 * The function goes through the requests list and sets up TRBs for the
1486 * transfers. The function returns once there are no more TRBs available or
1487 * it runs out of requests.
1489 * Returns the number of TRBs prepared or negative errno.
1491 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1493 struct dwc3_request *req, *n;
1496 BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1499 * We can get in a situation where there's a request in the started list
1500 * but there weren't enough TRBs to fully kick it in the first time
1501 * around, so it has been waiting for more TRBs to be freed up.
1503 * In that case, we should check if we have a request with pending_sgs
1504 * in the started list and prepare TRBs for that request first,
1505 * otherwise we will prepare TRBs completely out of order and that will
1508 list_for_each_entry(req, &dep->started_list, list) {
1509 if (req->num_pending_sgs > 0) {
1510 ret = dwc3_prepare_trbs_sg(dep, req);
1511 if (!ret || req->num_pending_sgs)
1515 if (!dwc3_calc_trbs_left(dep))
1519 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1520 * burst capability may try to read and use TRBs beyond the
1521 * active transfer instead of stopping.
1523 if (dep->stream_capable && req->request.is_last)
1527 list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1528 struct dwc3 *dwc = dep->dwc;
1530 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1535 req->sg = req->request.sg;
1536 req->start_sg = req->sg;
1537 req->num_queued_sgs = 0;
1538 req->num_pending_sgs = req->request.num_mapped_sgs;
1540 if (req->num_pending_sgs > 0) {
1541 ret = dwc3_prepare_trbs_sg(dep, req);
1542 if (req->num_pending_sgs)
1545 ret = dwc3_prepare_trbs_linear(dep, req);
1548 if (!ret || !dwc3_calc_trbs_left(dep))
1552 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1553 * burst capability may try to read and use TRBs beyond the
1554 * active transfer instead of stopping.
1556 if (dep->stream_capable && req->request.is_last)
1563 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1565 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1567 struct dwc3_gadget_ep_cmd_params params;
1568 struct dwc3_request *req;
1574 * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1575 * This happens when we need to stop and restart a transfer such as in
1576 * the case of reinitiating a stream or retrying an isoc transfer.
1578 ret = dwc3_prepare_trbs(dep);
1582 starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1585 * If there's no new TRB prepared and we don't need to restart a
1586 * transfer, there's no need to update the transfer.
1588 if (!ret && !starting)
1591 req = next_request(&dep->started_list);
1593 dep->flags |= DWC3_EP_PENDING_REQUEST;
1597 memset(¶ms, 0, sizeof(params));
1600 params.param0 = upper_32_bits(req->trb_dma);
1601 params.param1 = lower_32_bits(req->trb_dma);
1602 cmd = DWC3_DEPCMD_STARTTRANSFER;
1604 if (dep->stream_capable)
1605 cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1607 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1608 cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1610 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1611 DWC3_DEPCMD_PARAM(dep->resource_index);
1614 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1616 struct dwc3_request *tmp;
1621 dwc3_stop_active_transfer(dep, true, true);
1623 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1624 dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_DEQUEUED);
1626 /* If ep isn't started, then there's no end transfer pending */
1627 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1628 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1633 if (dep->stream_capable && req->request.is_last)
1634 dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1639 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1643 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1644 return DWC3_DSTS_SOFFN(reg);
1648 * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1649 * @dep: isoc endpoint
1651 * This function tests for the correct combination of BIT[15:14] from the 16-bit
1652 * microframe number reported by the XferNotReady event for the future frame
1653 * number to start the isoc transfer.
1655 * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1656 * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1657 * XferNotReady event are invalid. The driver uses this number to schedule the
1658 * isochronous transfer and passes it to the START TRANSFER command. Because
1659 * this number is invalid, the command may fail. If BIT[15:14] matches the
1660 * internal 16-bit microframe, the START TRANSFER command will pass and the
1661 * transfer will start at the scheduled time, if it is off by 1, the command
1662 * will still pass, but the transfer will start 2 seconds in the future. For all
1663 * other conditions, the START TRANSFER command will fail with bus-expiry.
1665 * In order to workaround this issue, we can test for the correct combination of
1666 * BIT[15:14] by sending START TRANSFER commands with different values of
1667 * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1668 * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1669 * As the result, within the 4 possible combinations for BIT[15:14], there will
1670 * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1671 * command status will result in a 2-second delay start. The smaller BIT[15:14]
1672 * value is the correct combination.
1674 * Since there are only 4 outcomes and the results are ordered, we can simply
1675 * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1676 * deduce the smaller successful combination.
1678 * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1679 * of BIT[15:14]. The correct combination is as follow:
1681 * if test0 fails and test1 passes, BIT[15:14] is 'b01
1682 * if test0 fails and test1 fails, BIT[15:14] is 'b10
1683 * if test0 passes and test1 fails, BIT[15:14] is 'b11
1684 * if test0 passes and test1 passes, BIT[15:14] is 'b00
1686 * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1689 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1695 while (dep->combo_num < 2) {
1696 struct dwc3_gadget_ep_cmd_params params;
1697 u32 test_frame_number;
1701 * Check if we can start isoc transfer on the next interval or
1702 * 4 uframes in the future with BIT[15:14] as dep->combo_num
1704 test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1705 test_frame_number |= dep->combo_num << 14;
1706 test_frame_number += max_t(u32, 4, dep->interval);
1708 params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1709 params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1711 cmd = DWC3_DEPCMD_STARTTRANSFER;
1712 cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1713 cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1715 /* Redo if some other failure beside bus-expiry is received */
1716 if (cmd_status && cmd_status != -EAGAIN) {
1717 dep->start_cmd_status = 0;
1722 /* Store the first test status */
1723 if (dep->combo_num == 0)
1724 dep->start_cmd_status = cmd_status;
1729 * End the transfer if the START_TRANSFER command is successful
1730 * to wait for the next XferNotReady to test the command again
1732 if (cmd_status == 0) {
1733 dwc3_stop_active_transfer(dep, true, true);
1738 /* test0 and test1 are both completed at this point */
1739 test0 = (dep->start_cmd_status == 0);
1740 test1 = (cmd_status == 0);
1742 if (!test0 && test1)
1744 else if (!test0 && !test1)
1746 else if (test0 && !test1)
1748 else if (test0 && test1)
1751 dep->frame_number &= DWC3_FRNUMBER_MASK;
1752 dep->frame_number |= dep->combo_num << 14;
1753 dep->frame_number += max_t(u32, 4, dep->interval);
1755 /* Reinitialize test variables */
1756 dep->start_cmd_status = 0;
1759 return __dwc3_gadget_kick_transfer(dep);
1762 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1764 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1765 struct dwc3 *dwc = dep->dwc;
1769 if (list_empty(&dep->pending_list) &&
1770 list_empty(&dep->started_list)) {
1771 dep->flags |= DWC3_EP_PENDING_REQUEST;
1775 if (!dwc->dis_start_transfer_quirk &&
1776 (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1777 DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1778 if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1779 return dwc3_gadget_start_isoc_quirk(dep);
1782 if (desc->bInterval <= 14 &&
1783 dwc->gadget->speed >= USB_SPEED_HIGH) {
1784 u32 frame = __dwc3_gadget_get_frame(dwc);
1785 bool rollover = frame <
1786 (dep->frame_number & DWC3_FRNUMBER_MASK);
1789 * frame_number is set from XferNotReady and may be already
1790 * out of date. DSTS only provides the lower 14 bit of the
1791 * current frame number. So add the upper two bits of
1792 * frame_number and handle a possible rollover.
1793 * This will provide the correct frame_number unless more than
1794 * rollover has happened since XferNotReady.
1797 dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1800 dep->frame_number += BIT(14);
1803 for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1804 dep->frame_number = DWC3_ALIGN_FRAME(dep, i + 1);
1806 ret = __dwc3_gadget_kick_transfer(dep);
1812 * After a number of unsuccessful start attempts due to bus-expiry
1813 * status, issue END_TRANSFER command and retry on the next XferNotReady
1816 if (ret == -EAGAIN) {
1817 struct dwc3_gadget_ep_cmd_params params;
1820 cmd = DWC3_DEPCMD_ENDTRANSFER |
1821 DWC3_DEPCMD_CMDIOC |
1822 DWC3_DEPCMD_PARAM(dep->resource_index);
1824 dep->resource_index = 0;
1825 memset(¶ms, 0, sizeof(params));
1827 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1829 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1835 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1837 struct dwc3 *dwc = dep->dwc;
1839 if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1840 dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
1845 if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1846 &req->request, req->dep->name))
1849 if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1850 "%s: request %pK already in flight\n",
1851 dep->name, &req->request))
1854 pm_runtime_get(dwc->dev);
1856 req->request.actual = 0;
1857 req->request.status = -EINPROGRESS;
1859 trace_dwc3_ep_queue(req);
1861 list_add_tail(&req->list, &dep->pending_list);
1862 req->status = DWC3_REQUEST_STATUS_QUEUED;
1864 if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1868 * Start the transfer only after the END_TRANSFER is completed
1869 * and endpoint STALL is cleared.
1871 if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1872 (dep->flags & DWC3_EP_WEDGE) ||
1873 (dep->flags & DWC3_EP_STALL)) {
1874 dep->flags |= DWC3_EP_DELAY_START;
1879 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1880 * wait for a XferNotReady event so we will know what's the current
1881 * (micro-)frame number.
1883 * Without this trick, we are very, very likely gonna get Bus Expiry
1884 * errors which will force us issue EndTransfer command.
1886 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1887 if (!(dep->flags & DWC3_EP_PENDING_REQUEST) &&
1888 !(dep->flags & DWC3_EP_TRANSFER_STARTED))
1891 if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1892 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
1893 return __dwc3_gadget_start_isoc(dep);
1897 __dwc3_gadget_kick_transfer(dep);
1902 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1905 struct dwc3_request *req = to_dwc3_request(request);
1906 struct dwc3_ep *dep = to_dwc3_ep(ep);
1907 struct dwc3 *dwc = dep->dwc;
1909 unsigned long flags;
1913 spin_lock_irqsave(&dwc->lock, flags);
1914 ret = __dwc3_gadget_ep_queue(dep, req);
1915 spin_unlock_irqrestore(&dwc->lock, flags);
1920 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
1924 /* If req->trb is not set, then the request has not started */
1929 * If request was already started, this means we had to
1930 * stop the transfer. With that we also need to ignore
1931 * all TRBs used by the request, however TRBs can only
1932 * be modified after completion of END_TRANSFER
1933 * command. So what we do here is that we wait for
1934 * END_TRANSFER completion and only after that, we jump
1935 * over TRBs by clearing HWO and incrementing dequeue
1938 for (i = 0; i < req->num_trbs; i++) {
1939 struct dwc3_trb *trb;
1941 trb = &dep->trb_pool[dep->trb_dequeue];
1942 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1943 dwc3_ep_inc_deq(dep);
1949 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
1951 struct dwc3_request *req;
1952 struct dwc3_request *tmp;
1953 struct dwc3 *dwc = dep->dwc;
1955 list_for_each_entry_safe(req, tmp, &dep->cancelled_list, list) {
1956 dwc3_gadget_ep_skip_trbs(dep, req);
1957 switch (req->status) {
1958 case DWC3_REQUEST_STATUS_DISCONNECTED:
1959 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
1961 case DWC3_REQUEST_STATUS_DEQUEUED:
1962 dwc3_gadget_giveback(dep, req, -ECONNRESET);
1964 case DWC3_REQUEST_STATUS_STALLED:
1965 dwc3_gadget_giveback(dep, req, -EPIPE);
1968 dev_err(dwc->dev, "request cancelled with wrong reason:%d\n", req->status);
1969 dwc3_gadget_giveback(dep, req, -ECONNRESET);
1975 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1976 struct usb_request *request)
1978 struct dwc3_request *req = to_dwc3_request(request);
1979 struct dwc3_request *r = NULL;
1981 struct dwc3_ep *dep = to_dwc3_ep(ep);
1982 struct dwc3 *dwc = dep->dwc;
1984 unsigned long flags;
1987 trace_dwc3_ep_dequeue(req);
1989 spin_lock_irqsave(&dwc->lock, flags);
1991 list_for_each_entry(r, &dep->cancelled_list, list) {
1996 list_for_each_entry(r, &dep->pending_list, list) {
1998 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2003 list_for_each_entry(r, &dep->started_list, list) {
2005 struct dwc3_request *t;
2007 /* wait until it is processed */
2008 dwc3_stop_active_transfer(dep, true, true);
2011 * Remove any started request if the transfer is
2014 list_for_each_entry_safe(r, t, &dep->started_list, list)
2015 dwc3_gadget_move_cancelled_request(r,
2016 DWC3_REQUEST_STATUS_DEQUEUED);
2018 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2024 dev_err(dwc->dev, "request %pK was not queued to %s\n",
2028 spin_unlock_irqrestore(&dwc->lock, flags);
2033 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
2035 struct dwc3_gadget_ep_cmd_params params;
2036 struct dwc3 *dwc = dep->dwc;
2037 struct dwc3_request *req;
2038 struct dwc3_request *tmp;
2041 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2042 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
2046 memset(¶ms, 0x00, sizeof(params));
2049 struct dwc3_trb *trb;
2051 unsigned int transfer_in_flight;
2052 unsigned int started;
2054 if (dep->number > 1)
2055 trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
2057 trb = &dwc->ep0_trb[dep->trb_enqueue];
2059 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
2060 started = !list_empty(&dep->started_list);
2062 if (!protocol && ((dep->direction && transfer_in_flight) ||
2063 (!dep->direction && started))) {
2067 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
2070 dev_err(dwc->dev, "failed to set STALL on %s\n",
2073 dep->flags |= DWC3_EP_STALL;
2076 * Don't issue CLEAR_STALL command to control endpoints. The
2077 * controller automatically clears the STALL when it receives
2080 if (dep->number <= 1) {
2081 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2085 dwc3_stop_active_transfer(dep, true, true);
2087 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
2088 dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_STALLED);
2090 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) {
2091 dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
2095 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
2097 ret = dwc3_send_clear_stall_ep_cmd(dep);
2099 dev_err(dwc->dev, "failed to clear STALL on %s\n",
2104 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2106 if ((dep->flags & DWC3_EP_DELAY_START) &&
2107 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
2108 __dwc3_gadget_kick_transfer(dep);
2110 dep->flags &= ~DWC3_EP_DELAY_START;
2116 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
2118 struct dwc3_ep *dep = to_dwc3_ep(ep);
2119 struct dwc3 *dwc = dep->dwc;
2121 unsigned long flags;
2125 spin_lock_irqsave(&dwc->lock, flags);
2126 ret = __dwc3_gadget_ep_set_halt(dep, value, false);
2127 spin_unlock_irqrestore(&dwc->lock, flags);
2132 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
2134 struct dwc3_ep *dep = to_dwc3_ep(ep);
2135 struct dwc3 *dwc = dep->dwc;
2136 unsigned long flags;
2139 spin_lock_irqsave(&dwc->lock, flags);
2140 dep->flags |= DWC3_EP_WEDGE;
2142 if (dep->number == 0 || dep->number == 1)
2143 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
2145 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
2146 spin_unlock_irqrestore(&dwc->lock, flags);
2151 /* -------------------------------------------------------------------------- */
2153 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
2154 .bLength = USB_DT_ENDPOINT_SIZE,
2155 .bDescriptorType = USB_DT_ENDPOINT,
2156 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
2159 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
2160 .enable = dwc3_gadget_ep0_enable,
2161 .disable = dwc3_gadget_ep0_disable,
2162 .alloc_request = dwc3_gadget_ep_alloc_request,
2163 .free_request = dwc3_gadget_ep_free_request,
2164 .queue = dwc3_gadget_ep0_queue,
2165 .dequeue = dwc3_gadget_ep_dequeue,
2166 .set_halt = dwc3_gadget_ep0_set_halt,
2167 .set_wedge = dwc3_gadget_ep_set_wedge,
2170 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
2171 .enable = dwc3_gadget_ep_enable,
2172 .disable = dwc3_gadget_ep_disable,
2173 .alloc_request = dwc3_gadget_ep_alloc_request,
2174 .free_request = dwc3_gadget_ep_free_request,
2175 .queue = dwc3_gadget_ep_queue,
2176 .dequeue = dwc3_gadget_ep_dequeue,
2177 .set_halt = dwc3_gadget_ep_set_halt,
2178 .set_wedge = dwc3_gadget_ep_set_wedge,
2181 /* -------------------------------------------------------------------------- */
2183 static int dwc3_gadget_get_frame(struct usb_gadget *g)
2185 struct dwc3 *dwc = gadget_to_dwc(g);
2187 return __dwc3_gadget_get_frame(dwc);
2190 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
2200 * According to the Databook Remote wakeup request should
2201 * be issued only when the device is in early suspend state.
2203 * We can check that via USB Link State bits in DSTS register.
2205 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2207 link_state = DWC3_DSTS_USBLNKST(reg);
2209 switch (link_state) {
2210 case DWC3_LINK_STATE_RESET:
2211 case DWC3_LINK_STATE_RX_DET: /* in HS, means Early Suspend */
2212 case DWC3_LINK_STATE_U3: /* in HS, means SUSPEND */
2213 case DWC3_LINK_STATE_U2: /* in HS, means Sleep (L1) */
2214 case DWC3_LINK_STATE_U1:
2215 case DWC3_LINK_STATE_RESUME:
2221 ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
2223 dev_err(dwc->dev, "failed to put link in Recovery\n");
2227 /* Recent versions do this automatically */
2228 if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
2229 /* write zeroes to Link Change Request */
2230 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2231 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
2232 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2235 /* poll until Link State changes to ON */
2239 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2241 /* in HS, means ON */
2242 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2246 if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2247 dev_err(dwc->dev, "failed to send remote wakeup\n");
2254 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2256 struct dwc3 *dwc = gadget_to_dwc(g);
2257 unsigned long flags;
2260 spin_lock_irqsave(&dwc->lock, flags);
2261 ret = __dwc3_gadget_wakeup(dwc);
2262 spin_unlock_irqrestore(&dwc->lock, flags);
2267 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2270 struct dwc3 *dwc = gadget_to_dwc(g);
2271 unsigned long flags;
2273 spin_lock_irqsave(&dwc->lock, flags);
2274 g->is_selfpowered = !!is_selfpowered;
2275 spin_unlock_irqrestore(&dwc->lock, flags);
2280 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2284 for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2285 struct dwc3_ep *dep;
2287 dep = dwc->eps[epnum];
2291 dwc3_remove_requests(dwc, dep);
2295 static void __dwc3_gadget_set_ssp_rate(struct dwc3 *dwc)
2297 enum usb_ssp_rate ssp_rate = dwc->gadget_ssp_rate;
2300 if (ssp_rate == USB_SSP_GEN_UNKNOWN)
2301 ssp_rate = dwc->max_ssp_rate;
2303 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2304 reg &= ~DWC3_DCFG_SPEED_MASK;
2305 reg &= ~DWC3_DCFG_NUMLANES(~0);
2307 if (ssp_rate == USB_SSP_GEN_1x2)
2308 reg |= DWC3_DCFG_SUPERSPEED;
2309 else if (dwc->max_ssp_rate != USB_SSP_GEN_1x2)
2310 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2312 if (ssp_rate != USB_SSP_GEN_2x1 &&
2313 dwc->max_ssp_rate != USB_SSP_GEN_2x1)
2314 reg |= DWC3_DCFG_NUMLANES(1);
2316 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2319 static void __dwc3_gadget_set_speed(struct dwc3 *dwc)
2321 enum usb_device_speed speed;
2324 speed = dwc->gadget_max_speed;
2325 if (speed == USB_SPEED_UNKNOWN || speed > dwc->maximum_speed)
2326 speed = dwc->maximum_speed;
2328 if (speed == USB_SPEED_SUPER_PLUS &&
2329 DWC3_IP_IS(DWC32)) {
2330 __dwc3_gadget_set_ssp_rate(dwc);
2334 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2335 reg &= ~(DWC3_DCFG_SPEED_MASK);
2338 * WORKAROUND: DWC3 revision < 2.20a have an issue
2339 * which would cause metastability state on Run/Stop
2340 * bit if we try to force the IP to USB2-only mode.
2342 * Because of that, we cannot configure the IP to any
2343 * speed other than the SuperSpeed
2347 * STAR#9000525659: Clock Domain Crossing on DCTL in
2350 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2351 !dwc->dis_metastability_quirk) {
2352 reg |= DWC3_DCFG_SUPERSPEED;
2355 case USB_SPEED_FULL:
2356 reg |= DWC3_DCFG_FULLSPEED;
2358 case USB_SPEED_HIGH:
2359 reg |= DWC3_DCFG_HIGHSPEED;
2361 case USB_SPEED_SUPER:
2362 reg |= DWC3_DCFG_SUPERSPEED;
2364 case USB_SPEED_SUPER_PLUS:
2365 if (DWC3_IP_IS(DWC3))
2366 reg |= DWC3_DCFG_SUPERSPEED;
2368 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2371 dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2373 if (DWC3_IP_IS(DWC3))
2374 reg |= DWC3_DCFG_SUPERSPEED;
2376 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2380 if (DWC3_IP_IS(DWC32) &&
2381 speed > USB_SPEED_UNKNOWN &&
2382 speed < USB_SPEED_SUPER_PLUS)
2383 reg &= ~DWC3_DCFG_NUMLANES(~0);
2385 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2388 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
2393 if (pm_runtime_suspended(dwc->dev))
2396 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2398 if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2399 reg &= ~DWC3_DCTL_TRGTULST_MASK;
2400 reg |= DWC3_DCTL_TRGTULST_RX_DET;
2403 if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2404 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2405 reg |= DWC3_DCTL_RUN_STOP;
2407 if (dwc->has_hibernation)
2408 reg |= DWC3_DCTL_KEEP_CONNECT;
2410 __dwc3_gadget_set_speed(dwc);
2411 dwc->pullups_connected = true;
2413 reg &= ~DWC3_DCTL_RUN_STOP;
2415 if (dwc->has_hibernation && !suspend)
2416 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2418 dwc->pullups_connected = false;
2421 dwc3_gadget_dctl_write_safe(dwc, reg);
2424 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2425 reg &= DWC3_DSTS_DEVCTRLHLT;
2426 } while (--timeout && !(!is_on ^ !reg));
2434 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2435 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2436 static int __dwc3_gadget_start(struct dwc3 *dwc);
2438 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2440 struct dwc3 *dwc = gadget_to_dwc(g);
2441 unsigned long flags;
2445 dwc->softconnect = is_on;
2447 * Per databook, when we want to stop the gadget, if a control transfer
2448 * is still in process, complete it and get the core into setup phase.
2450 if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
2451 reinit_completion(&dwc->ep0_in_setup);
2453 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2454 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2456 dev_warn(dwc->dev, "timed out waiting for SETUP phase\n");
2460 * Avoid issuing a runtime resume if the device is already in the
2461 * suspended state during gadget disconnect. DWC3 gadget was already
2462 * halted/stopped during runtime suspend.
2465 pm_runtime_barrier(dwc->dev);
2466 if (pm_runtime_suspended(dwc->dev))
2471 * Check the return value for successful resume, or error. For a
2472 * successful resume, the DWC3 runtime PM resume routine will handle
2473 * the run stop sequence, so avoid duplicate operations here.
2475 ret = pm_runtime_get_sync(dwc->dev);
2476 if (!ret || ret < 0) {
2477 pm_runtime_put(dwc->dev);
2482 * Synchronize and disable any further event handling while controller
2483 * is being enabled/disabled.
2485 disable_irq(dwc->irq_gadget);
2487 spin_lock_irqsave(&dwc->lock, flags);
2492 dwc->connected = false;
2494 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2495 * Section 4.1.8 Table 4-7, it states that for a device-initiated
2496 * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2497 * command for any active transfers" before clearing the RunStop
2500 dwc3_stop_active_transfers(dwc);
2501 __dwc3_gadget_stop(dwc);
2504 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2505 * Section 1.3.4, it mentions that for the DEVCTRLHLT bit, the
2506 * "software needs to acknowledge the events that are generated
2507 * (by writing to GEVNTCOUNTn) while it is waiting for this bit
2508 * to be set to '1'."
2510 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
2511 count &= DWC3_GEVNTCOUNT_MASK;
2513 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
2514 dwc->ev_buf->lpos = (dwc->ev_buf->lpos + count) %
2515 dwc->ev_buf->length;
2518 __dwc3_gadget_start(dwc);
2521 ret = dwc3_gadget_run_stop(dwc, is_on, false);
2522 spin_unlock_irqrestore(&dwc->lock, flags);
2523 enable_irq(dwc->irq_gadget);
2525 pm_runtime_put(dwc->dev);
2530 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2534 /* Enable all but Start and End of Frame IRQs */
2535 reg = (DWC3_DEVTEN_EVNTOVERFLOWEN |
2536 DWC3_DEVTEN_CMDCMPLTEN |
2537 DWC3_DEVTEN_ERRTICERREN |
2538 DWC3_DEVTEN_WKUPEVTEN |
2539 DWC3_DEVTEN_CONNECTDONEEN |
2540 DWC3_DEVTEN_USBRSTEN |
2541 DWC3_DEVTEN_DISCONNEVTEN);
2543 if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2544 reg |= DWC3_DEVTEN_ULSTCNGEN;
2546 /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2547 if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2548 reg |= DWC3_DEVTEN_U3L2L1SUSPEN;
2550 dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2553 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2555 /* mask all interrupts */
2556 dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2559 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2560 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2563 * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2564 * @dwc: pointer to our context structure
2566 * The following looks like complex but it's actually very simple. In order to
2567 * calculate the number of packets we can burst at once on OUT transfers, we're
2568 * gonna use RxFIFO size.
2570 * To calculate RxFIFO size we need two numbers:
2571 * MDWIDTH = size, in bits, of the internal memory bus
2572 * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2574 * Given these two numbers, the formula is simple:
2576 * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2578 * 24 bytes is for 3x SETUP packets
2579 * 16 bytes is a clock domain crossing tolerance
2581 * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2583 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2590 ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2591 mdwidth = dwc3_mdwidth(dwc);
2593 nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2594 nump = min_t(u32, nump, 16);
2597 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2598 reg &= ~DWC3_DCFG_NUMP_MASK;
2599 reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2600 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2603 static int __dwc3_gadget_start(struct dwc3 *dwc)
2605 struct dwc3_ep *dep;
2610 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2611 * the core supports IMOD, disable it.
2613 if (dwc->imod_interval) {
2614 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2615 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2616 } else if (dwc3_has_imod(dwc)) {
2617 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2621 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2622 * field instead of letting dwc3 itself calculate that automatically.
2624 * This way, we maximize the chances that we'll be able to get several
2625 * bursts of data without going through any sort of endpoint throttling.
2627 reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2628 if (DWC3_IP_IS(DWC3))
2629 reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2631 reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2633 dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2635 dwc3_gadget_setup_nump(dwc);
2638 * Currently the controller handles single stream only. So, Ignore
2639 * Packet Pending bit for stream selection and don't search for another
2640 * stream if the host sends Data Packet with PP=0 (for OUT direction) or
2641 * ACK with NumP=0 and PP=0 (for IN direction). This slightly improves
2642 * the stream performance.
2644 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2645 reg |= DWC3_DCFG_IGNSTRMPP;
2646 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2648 /* Start with SuperSpeed Default */
2649 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2652 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2654 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2659 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2661 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2665 /* begin to receive SETUP packets */
2666 dwc->ep0state = EP0_SETUP_PHASE;
2667 dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2668 dwc->delayed_status = false;
2669 dwc3_ep0_out_start(dwc);
2671 dwc3_gadget_enable_irq(dwc);
2676 __dwc3_gadget_ep_disable(dwc->eps[0]);
2682 static int dwc3_gadget_start(struct usb_gadget *g,
2683 struct usb_gadget_driver *driver)
2685 struct dwc3 *dwc = gadget_to_dwc(g);
2686 unsigned long flags;
2690 irq = dwc->irq_gadget;
2691 ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2692 IRQF_SHARED, "dwc3", dwc->ev_buf);
2694 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2699 spin_lock_irqsave(&dwc->lock, flags);
2700 dwc->gadget_driver = driver;
2701 spin_unlock_irqrestore(&dwc->lock, flags);
2706 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2708 dwc3_gadget_disable_irq(dwc);
2709 __dwc3_gadget_ep_disable(dwc->eps[0]);
2710 __dwc3_gadget_ep_disable(dwc->eps[1]);
2713 static int dwc3_gadget_stop(struct usb_gadget *g)
2715 struct dwc3 *dwc = gadget_to_dwc(g);
2716 unsigned long flags;
2718 spin_lock_irqsave(&dwc->lock, flags);
2719 dwc->gadget_driver = NULL;
2720 dwc->max_cfg_eps = 0;
2721 spin_unlock_irqrestore(&dwc->lock, flags);
2723 free_irq(dwc->irq_gadget, dwc->ev_buf);
2728 static void dwc3_gadget_config_params(struct usb_gadget *g,
2729 struct usb_dcd_config_params *params)
2731 struct dwc3 *dwc = gadget_to_dwc(g);
2733 params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2734 params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2736 /* Recommended BESL */
2737 if (!dwc->dis_enblslpm_quirk) {
2739 * If the recommended BESL baseline is 0 or if the BESL deep is
2740 * less than 2, Microsoft's Windows 10 host usb stack will issue
2741 * a usb reset immediately after it receives the extended BOS
2742 * descriptor and the enumeration will fail. To maintain
2743 * compatibility with the Windows' usb stack, let's set the
2744 * recommended BESL baseline to 1 and clamp the BESL deep to be
2747 params->besl_baseline = 1;
2748 if (dwc->is_utmi_l1_suspend)
2750 clamp_t(u8, dwc->hird_threshold, 2, 15);
2753 /* U1 Device exit Latency */
2754 if (dwc->dis_u1_entry_quirk)
2755 params->bU1devExitLat = 0;
2757 params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
2759 /* U2 Device exit Latency */
2760 if (dwc->dis_u2_entry_quirk)
2761 params->bU2DevExitLat = 0;
2763 params->bU2DevExitLat =
2764 cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
2767 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2768 enum usb_device_speed speed)
2770 struct dwc3 *dwc = gadget_to_dwc(g);
2771 unsigned long flags;
2773 spin_lock_irqsave(&dwc->lock, flags);
2774 dwc->gadget_max_speed = speed;
2775 spin_unlock_irqrestore(&dwc->lock, flags);
2778 static void dwc3_gadget_set_ssp_rate(struct usb_gadget *g,
2779 enum usb_ssp_rate rate)
2781 struct dwc3 *dwc = gadget_to_dwc(g);
2782 unsigned long flags;
2784 spin_lock_irqsave(&dwc->lock, flags);
2785 dwc->gadget_max_speed = USB_SPEED_SUPER_PLUS;
2786 dwc->gadget_ssp_rate = rate;
2787 spin_unlock_irqrestore(&dwc->lock, flags);
2790 static int dwc3_gadget_vbus_draw(struct usb_gadget *g, unsigned int mA)
2792 struct dwc3 *dwc = gadget_to_dwc(g);
2793 union power_supply_propval val = {0};
2797 return usb_phy_set_power(dwc->usb2_phy, mA);
2802 val.intval = 1000 * mA;
2803 ret = power_supply_set_property(dwc->usb_psy, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
2809 * dwc3_gadget_check_config - ensure dwc3 can support the USB configuration
2810 * @g: pointer to the USB gadget
2812 * Used to record the maximum number of endpoints being used in a USB composite
2813 * device. (across all configurations) This is to be used in the calculation
2814 * of the TXFIFO sizes when resizing internal memory for individual endpoints.
2815 * It will help ensured that the resizing logic reserves enough space for at
2816 * least one max packet.
2818 static int dwc3_gadget_check_config(struct usb_gadget *g)
2820 struct dwc3 *dwc = gadget_to_dwc(g);
2826 if (!dwc->do_fifo_resize)
2829 list_for_each_entry(ep, &g->ep_list, ep_list) {
2830 /* Only interested in the IN endpoints */
2831 if (ep->claimed && (ep->address & USB_DIR_IN))
2835 if (ep_num <= dwc->max_cfg_eps)
2838 /* Update the max number of eps in the composition */
2839 dwc->max_cfg_eps = ep_num;
2841 fifo_size = dwc3_gadget_calc_tx_fifo_size(dwc, dwc->max_cfg_eps);
2842 /* Based on the equation, increment by one for every ep */
2843 fifo_size += dwc->max_cfg_eps;
2845 /* Check if we can fit a single fifo per endpoint */
2846 ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
2847 if (fifo_size > ram1_depth)
2853 static void dwc3_gadget_async_callbacks(struct usb_gadget *g, bool enable)
2855 struct dwc3 *dwc = gadget_to_dwc(g);
2856 unsigned long flags;
2858 spin_lock_irqsave(&dwc->lock, flags);
2859 dwc->async_callbacks = enable;
2860 spin_unlock_irqrestore(&dwc->lock, flags);
2863 static const struct usb_gadget_ops dwc3_gadget_ops = {
2864 .get_frame = dwc3_gadget_get_frame,
2865 .wakeup = dwc3_gadget_wakeup,
2866 .set_selfpowered = dwc3_gadget_set_selfpowered,
2867 .pullup = dwc3_gadget_pullup,
2868 .udc_start = dwc3_gadget_start,
2869 .udc_stop = dwc3_gadget_stop,
2870 .udc_set_speed = dwc3_gadget_set_speed,
2871 .udc_set_ssp_rate = dwc3_gadget_set_ssp_rate,
2872 .get_config_params = dwc3_gadget_config_params,
2873 .vbus_draw = dwc3_gadget_vbus_draw,
2874 .check_config = dwc3_gadget_check_config,
2875 .udc_async_callbacks = dwc3_gadget_async_callbacks,
2878 /* -------------------------------------------------------------------------- */
2880 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2882 struct dwc3 *dwc = dep->dwc;
2884 usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2885 dep->endpoint.maxburst = 1;
2886 dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2887 if (!dep->direction)
2888 dwc->gadget->ep0 = &dep->endpoint;
2890 dep->endpoint.caps.type_control = true;
2895 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2897 struct dwc3 *dwc = dep->dwc;
2901 mdwidth = dwc3_mdwidth(dwc);
2903 /* MDWIDTH is represented in bits, we need it in bytes */
2906 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2907 if (DWC3_IP_IS(DWC3))
2908 size = DWC3_GTXFIFOSIZ_TXFDEP(size);
2910 size = DWC31_GTXFIFOSIZ_TXFDEP(size);
2912 /* FIFO Depth is in MDWDITH bytes. Multiply */
2916 * To meet performance requirement, a minimum TxFIFO size of 3x
2917 * MaxPacketSize is recommended for endpoints that support burst and a
2918 * minimum TxFIFO size of 2x MaxPacketSize for endpoints that don't
2919 * support burst. Use those numbers and we can calculate the max packet
2922 if (dwc->maximum_speed >= USB_SPEED_SUPER)
2927 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2929 dep->endpoint.max_streams = 16;
2930 dep->endpoint.ops = &dwc3_gadget_ep_ops;
2931 list_add_tail(&dep->endpoint.ep_list,
2932 &dwc->gadget->ep_list);
2933 dep->endpoint.caps.type_iso = true;
2934 dep->endpoint.caps.type_bulk = true;
2935 dep->endpoint.caps.type_int = true;
2937 return dwc3_alloc_trb_pool(dep);
2940 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
2942 struct dwc3 *dwc = dep->dwc;
2946 mdwidth = dwc3_mdwidth(dwc);
2948 /* MDWIDTH is represented in bits, convert to bytes */
2951 /* All OUT endpoints share a single RxFIFO space */
2952 size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
2953 if (DWC3_IP_IS(DWC3))
2954 size = DWC3_GRXFIFOSIZ_RXFDEP(size);
2956 size = DWC31_GRXFIFOSIZ_RXFDEP(size);
2958 /* FIFO depth is in MDWDITH bytes */
2962 * To meet performance requirement, a minimum recommended RxFIFO size
2963 * is defined as follow:
2964 * RxFIFO size >= (3 x MaxPacketSize) +
2965 * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
2967 * Then calculate the max packet limit as below.
2969 size -= (3 * 8) + 16;
2975 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2976 dep->endpoint.max_streams = 16;
2977 dep->endpoint.ops = &dwc3_gadget_ep_ops;
2978 list_add_tail(&dep->endpoint.ep_list,
2979 &dwc->gadget->ep_list);
2980 dep->endpoint.caps.type_iso = true;
2981 dep->endpoint.caps.type_bulk = true;
2982 dep->endpoint.caps.type_int = true;
2984 return dwc3_alloc_trb_pool(dep);
2987 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
2989 struct dwc3_ep *dep;
2990 bool direction = epnum & 1;
2992 u8 num = epnum >> 1;
2994 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2999 dep->number = epnum;
3000 dep->direction = direction;
3001 dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
3002 dwc->eps[epnum] = dep;
3004 dep->start_cmd_status = 0;
3006 snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
3007 direction ? "in" : "out");
3009 dep->endpoint.name = dep->name;
3011 if (!(dep->number > 1)) {
3012 dep->endpoint.desc = &dwc3_gadget_ep0_desc;
3013 dep->endpoint.comp_desc = NULL;
3017 ret = dwc3_gadget_init_control_endpoint(dep);
3019 ret = dwc3_gadget_init_in_endpoint(dep);
3021 ret = dwc3_gadget_init_out_endpoint(dep);
3026 dep->endpoint.caps.dir_in = direction;
3027 dep->endpoint.caps.dir_out = !direction;
3029 INIT_LIST_HEAD(&dep->pending_list);
3030 INIT_LIST_HEAD(&dep->started_list);
3031 INIT_LIST_HEAD(&dep->cancelled_list);
3033 dwc3_debugfs_create_endpoint_dir(dep);
3038 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
3042 INIT_LIST_HEAD(&dwc->gadget->ep_list);
3044 for (epnum = 0; epnum < total; epnum++) {
3047 ret = dwc3_gadget_init_endpoint(dwc, epnum);
3055 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
3057 struct dwc3_ep *dep;
3060 for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3061 dep = dwc->eps[epnum];
3065 * Physical endpoints 0 and 1 are special; they form the
3066 * bi-directional USB endpoint 0.
3068 * For those two physical endpoints, we don't allocate a TRB
3069 * pool nor do we add them the endpoints list. Due to that, we
3070 * shouldn't do these two operations otherwise we would end up
3071 * with all sorts of bugs when removing dwc3.ko.
3073 if (epnum != 0 && epnum != 1) {
3074 dwc3_free_trb_pool(dep);
3075 list_del(&dep->endpoint.ep_list);
3078 debugfs_remove_recursive(debugfs_lookup(dep->name,
3079 debugfs_lookup(dev_name(dep->dwc->dev),
3085 /* -------------------------------------------------------------------------- */
3087 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
3088 struct dwc3_request *req, struct dwc3_trb *trb,
3089 const struct dwc3_event_depevt *event, int status, int chain)
3093 dwc3_ep_inc_deq(dep);
3095 trace_dwc3_complete_trb(dep, trb);
3099 * If we're in the middle of series of chained TRBs and we
3100 * receive a short transfer along the way, DWC3 will skip
3101 * through all TRBs including the last TRB in the chain (the
3102 * where CHN bit is zero. DWC3 will also avoid clearing HWO
3103 * bit and SW has to do it manually.
3105 * We're going to do that here to avoid problems of HW trying
3106 * to use bogus TRBs for transfers.
3108 if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
3109 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3112 * For isochronous transfers, the first TRB in a service interval must
3113 * have the Isoc-First type. Track and report its interval frame number.
3115 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3116 (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
3117 unsigned int frame_number;
3119 frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
3120 frame_number &= ~(dep->interval - 1);
3121 req->request.frame_number = frame_number;
3125 * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
3126 * this TRB points to the bounce buffer address, it's a MPS alignment
3127 * TRB. Don't add it to req->remaining calculation.
3129 if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
3130 trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
3131 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3135 count = trb->size & DWC3_TRB_SIZE_MASK;
3136 req->remaining += count;
3138 if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
3141 if (event->status & DEPEVT_STATUS_SHORT && !chain)
3144 if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
3145 (trb->ctrl & DWC3_TRB_CTRL_LST))
3151 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
3152 struct dwc3_request *req, const struct dwc3_event_depevt *event,
3155 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3156 struct scatterlist *sg = req->sg;
3157 struct scatterlist *s;
3158 unsigned int num_queued = req->num_queued_sgs;
3162 for_each_sg(sg, s, num_queued, i) {
3163 trb = &dep->trb_pool[dep->trb_dequeue];
3165 req->sg = sg_next(s);
3166 req->num_queued_sgs--;
3168 ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
3169 trb, event, status, true);
3177 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
3178 struct dwc3_request *req, const struct dwc3_event_depevt *event,
3181 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3183 return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
3184 event, status, false);
3187 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
3189 return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
3192 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
3193 const struct dwc3_event_depevt *event,
3194 struct dwc3_request *req, int status)
3198 if (req->request.num_mapped_sgs)
3199 ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
3202 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3205 req->request.actual = req->request.length - req->remaining;
3207 if (!dwc3_gadget_ep_request_completed(req))
3210 if (req->needs_extra_trb) {
3211 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3213 req->needs_extra_trb = false;
3216 dwc3_gadget_giveback(dep, req, status);
3222 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
3223 const struct dwc3_event_depevt *event, int status)
3225 struct dwc3_request *req;
3226 struct dwc3_request *tmp;
3228 list_for_each_entry_safe(req, tmp, &dep->started_list, list) {
3231 ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
3238 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
3240 struct dwc3_request *req;
3241 struct dwc3 *dwc = dep->dwc;
3243 if (!dep->endpoint.desc || !dwc->pullups_connected ||
3247 if (!list_empty(&dep->pending_list))
3251 * We only need to check the first entry of the started list. We can
3252 * assume the completed requests are removed from the started list.
3254 req = next_request(&dep->started_list);
3258 return !dwc3_gadget_ep_request_completed(req);
3261 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
3262 const struct dwc3_event_depevt *event)
3264 dep->frame_number = event->parameters;
3267 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
3268 const struct dwc3_event_depevt *event, int status)
3270 struct dwc3 *dwc = dep->dwc;
3271 bool no_started_trb = true;
3273 if (!dep->endpoint.desc)
3274 return no_started_trb;
3276 dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
3278 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3281 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3282 list_empty(&dep->started_list) &&
3283 (list_empty(&dep->pending_list) || status == -EXDEV))
3284 dwc3_stop_active_transfer(dep, true, true);
3285 else if (dwc3_gadget_ep_should_continue(dep))
3286 if (__dwc3_gadget_kick_transfer(dep) == 0)
3287 no_started_trb = false;
3291 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
3292 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
3294 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3298 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
3301 if (!(dep->flags & DWC3_EP_ENABLED))
3304 if (!list_empty(&dep->started_list))
3305 return no_started_trb;
3308 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3310 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
3315 return no_started_trb;
3318 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
3319 const struct dwc3_event_depevt *event)
3323 if (!dep->endpoint.desc)
3326 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
3327 dwc3_gadget_endpoint_frame_from_event(dep, event);
3329 if (event->status & DEPEVT_STATUS_BUSERR)
3330 status = -ECONNRESET;
3332 if (event->status & DEPEVT_STATUS_MISSED_ISOC)
3335 dwc3_gadget_endpoint_trbs_complete(dep, event, status);
3338 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
3339 const struct dwc3_event_depevt *event)
3343 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3345 if (event->status & DEPEVT_STATUS_BUSERR)
3346 status = -ECONNRESET;
3348 if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
3349 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
3352 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
3353 const struct dwc3_event_depevt *event)
3355 dwc3_gadget_endpoint_frame_from_event(dep, event);
3358 * The XferNotReady event is generated only once before the endpoint
3359 * starts. It will be generated again when END_TRANSFER command is
3360 * issued. For some controller versions, the XferNotReady event may be
3361 * generated while the END_TRANSFER command is still in process. Ignore
3362 * it and wait for the next XferNotReady event after the command is
3365 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3368 (void) __dwc3_gadget_start_isoc(dep);
3371 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
3372 const struct dwc3_event_depevt *event)
3374 u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
3376 if (cmd != DWC3_DEPCMD_ENDTRANSFER)
3380 * The END_TRANSFER command will cause the controller to generate a
3381 * NoStream Event, and it's not due to the host DP NoStream rejection.
3382 * Ignore the next NoStream event.
3384 if (dep->stream_capable)
3385 dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3387 dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
3388 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3389 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3391 if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3392 struct dwc3 *dwc = dep->dwc;
3394 dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3395 if (dwc3_send_clear_stall_ep_cmd(dep)) {
3396 struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3398 dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3399 if (dwc->delayed_status)
3400 __dwc3_gadget_ep0_set_halt(ep0, 1);
3404 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3405 if (dwc->delayed_status)
3406 dwc3_ep0_send_delayed_status(dwc);
3409 if ((dep->flags & DWC3_EP_DELAY_START) &&
3410 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3411 __dwc3_gadget_kick_transfer(dep);
3413 dep->flags &= ~DWC3_EP_DELAY_START;
3416 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3417 const struct dwc3_event_depevt *event)
3419 struct dwc3 *dwc = dep->dwc;
3421 if (event->status == DEPEVT_STREAMEVT_FOUND) {
3422 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3426 /* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3427 switch (event->parameters) {
3428 case DEPEVT_STREAM_PRIME:
3430 * If the host can properly transition the endpoint state from
3431 * idle to prime after a NoStream rejection, there's no need to
3432 * force restarting the endpoint to reinitiate the stream. To
3433 * simplify the check, assume the host follows the USB spec if
3434 * it primed the endpoint more than once.
3436 if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3437 if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3438 dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3440 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3444 case DEPEVT_STREAM_NOSTREAM:
3445 if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3446 !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3447 !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE))
3451 * If the host rejects a stream due to no active stream, by the
3452 * USB and xHCI spec, the endpoint will be put back to idle
3453 * state. When the host is ready (buffer added/updated), it will
3454 * prime the endpoint to inform the usb device controller. This
3455 * triggers the device controller to issue ERDY to restart the
3456 * stream. However, some hosts don't follow this and keep the
3457 * endpoint in the idle state. No prime will come despite host
3458 * streams are updated, and the device controller will not be
3459 * triggered to generate ERDY to move the next stream data. To
3460 * workaround this and maintain compatibility with various
3461 * hosts, force to reinitate the stream until the host is ready
3462 * instead of waiting for the host to prime the endpoint.
3464 if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3465 unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3467 dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3469 dep->flags |= DWC3_EP_DELAY_START;
3470 dwc3_stop_active_transfer(dep, true, true);
3477 dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3480 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3481 const struct dwc3_event_depevt *event)
3483 struct dwc3_ep *dep;
3484 u8 epnum = event->endpoint_number;
3486 dep = dwc->eps[epnum];
3488 if (!(dep->flags & DWC3_EP_ENABLED)) {
3489 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
3492 /* Handle only EPCMDCMPLT when EP disabled */
3493 if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
3497 if (epnum == 0 || epnum == 1) {
3498 dwc3_ep0_interrupt(dwc, event);
3502 switch (event->endpoint_event) {
3503 case DWC3_DEPEVT_XFERINPROGRESS:
3504 dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3506 case DWC3_DEPEVT_XFERNOTREADY:
3507 dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3509 case DWC3_DEPEVT_EPCMDCMPLT:
3510 dwc3_gadget_endpoint_command_complete(dep, event);
3512 case DWC3_DEPEVT_XFERCOMPLETE:
3513 dwc3_gadget_endpoint_transfer_complete(dep, event);
3515 case DWC3_DEPEVT_STREAMEVT:
3516 dwc3_gadget_endpoint_stream_event(dep, event);
3518 case DWC3_DEPEVT_RXTXFIFOEVT:
3523 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3525 if (dwc->async_callbacks && dwc->gadget_driver->disconnect) {
3526 spin_unlock(&dwc->lock);
3527 dwc->gadget_driver->disconnect(dwc->gadget);
3528 spin_lock(&dwc->lock);
3532 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3534 if (dwc->async_callbacks && dwc->gadget_driver->suspend) {
3535 spin_unlock(&dwc->lock);
3536 dwc->gadget_driver->suspend(dwc->gadget);
3537 spin_lock(&dwc->lock);
3541 static void dwc3_resume_gadget(struct dwc3 *dwc)
3543 if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3544 spin_unlock(&dwc->lock);
3545 dwc->gadget_driver->resume(dwc->gadget);
3546 spin_lock(&dwc->lock);
3550 static void dwc3_reset_gadget(struct dwc3 *dwc)
3552 if (!dwc->gadget_driver)
3555 if (dwc->async_callbacks && dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3556 spin_unlock(&dwc->lock);
3557 usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3558 spin_lock(&dwc->lock);
3562 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3565 struct dwc3_gadget_ep_cmd_params params;
3569 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3570 (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3574 * NOTICE: We are violating what the Databook says about the
3575 * EndTransfer command. Ideally we would _always_ wait for the
3576 * EndTransfer Command Completion IRQ, but that's causing too
3577 * much trouble synchronizing between us and gadget driver.
3579 * We have discussed this with the IP Provider and it was
3580 * suggested to giveback all requests here.
3582 * Note also that a similar handling was tested by Synopsys
3583 * (thanks a lot Paul) and nothing bad has come out of it.
3584 * In short, what we're doing is issuing EndTransfer with
3585 * CMDIOC bit set and delay kicking transfer until the
3586 * EndTransfer command had completed.
3588 * As of IP version 3.10a of the DWC_usb3 IP, the controller
3589 * supports a mode to work around the above limitation. The
3590 * software can poll the CMDACT bit in the DEPCMD register
3591 * after issuing a EndTransfer command. This mode is enabled
3592 * by writing GUCTL2[14]. This polling is already done in the
3593 * dwc3_send_gadget_ep_cmd() function so if the mode is
3594 * enabled, the EndTransfer command will have completed upon
3595 * returning from this function.
3597 * This mode is NOT available on the DWC_usb31 IP.
3600 cmd = DWC3_DEPCMD_ENDTRANSFER;
3601 cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
3602 cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
3603 cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
3604 memset(¶ms, 0, sizeof(params));
3605 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
3607 dep->resource_index = 0;
3610 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3612 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
3615 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3619 for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3620 struct dwc3_ep *dep;
3623 dep = dwc->eps[epnum];
3627 if (!(dep->flags & DWC3_EP_STALL))
3630 dep->flags &= ~DWC3_EP_STALL;
3632 ret = dwc3_send_clear_stall_ep_cmd(dep);
3637 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3641 dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3643 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3644 reg &= ~DWC3_DCTL_INITU1ENA;
3645 reg &= ~DWC3_DCTL_INITU2ENA;
3646 dwc3_gadget_dctl_write_safe(dwc, reg);
3648 dwc3_disconnect_gadget(dwc);
3650 dwc->gadget->speed = USB_SPEED_UNKNOWN;
3651 dwc->setup_packet_pending = false;
3652 usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3654 dwc->connected = false;
3657 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
3662 * Ideally, dwc3_reset_gadget() would trigger the function
3663 * drivers to stop any active transfers through ep disable.
3664 * However, for functions which defer ep disable, such as mass
3665 * storage, we will need to rely on the call to stop active
3666 * transfers here, and avoid allowing of request queuing.
3668 dwc->connected = false;
3671 * WORKAROUND: DWC3 revisions <1.88a have an issue which
3672 * would cause a missing Disconnect Event if there's a
3673 * pending Setup Packet in the FIFO.
3675 * There's no suggested workaround on the official Bug
3676 * report, which states that "unless the driver/application
3677 * is doing any special handling of a disconnect event,
3678 * there is no functional issue".
3680 * Unfortunately, it turns out that we _do_ some special
3681 * handling of a disconnect event, namely complete all
3682 * pending transfers, notify gadget driver of the
3683 * disconnection, and so on.
3685 * Our suggested workaround is to follow the Disconnect
3686 * Event steps here, instead, based on a setup_packet_pending
3687 * flag. Such flag gets set whenever we have a SETUP_PENDING
3688 * status for EP0 TRBs and gets cleared on XferComplete for the
3693 * STAR#9000466709: RTL: Device : Disconnect event not
3694 * generated if setup packet pending in FIFO
3696 if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
3697 if (dwc->setup_packet_pending)
3698 dwc3_gadget_disconnect_interrupt(dwc);
3701 dwc3_reset_gadget(dwc);
3703 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
3704 * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
3705 * needs to ensure that it sends "a DEPENDXFER command for any active
3708 dwc3_stop_active_transfers(dwc);
3709 dwc->connected = true;
3711 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3712 reg &= ~DWC3_DCTL_TSTCTRL_MASK;
3713 dwc3_gadget_dctl_write_safe(dwc, reg);
3714 dwc->test_mode = false;
3715 dwc3_clear_stall_all_ep(dwc);
3717 /* Reset device address to zero */
3718 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3719 reg &= ~(DWC3_DCFG_DEVADDR_MASK);
3720 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3723 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
3725 struct dwc3_ep *dep;
3731 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
3732 speed = reg & DWC3_DSTS_CONNECTSPD;
3735 if (DWC3_IP_IS(DWC32))
3736 lanes = DWC3_DSTS_CONNLANES(reg) + 1;
3738 dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
3741 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
3742 * each time on Connect Done.
3744 * Currently we always use the reset value. If any platform
3745 * wants to set this to a different value, we need to add a
3746 * setting and update GCTL.RAMCLKSEL here.
3750 case DWC3_DSTS_SUPERSPEED_PLUS:
3751 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3752 dwc->gadget->ep0->maxpacket = 512;
3753 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3756 dwc->gadget->ssp_rate = USB_SSP_GEN_2x2;
3758 dwc->gadget->ssp_rate = USB_SSP_GEN_2x1;
3760 case DWC3_DSTS_SUPERSPEED:
3762 * WORKAROUND: DWC3 revisions <1.90a have an issue which
3763 * would cause a missing USB3 Reset event.
3765 * In such situations, we should force a USB3 Reset
3766 * event by calling our dwc3_gadget_reset_interrupt()
3771 * STAR#9000483510: RTL: SS : USB3 reset event may
3772 * not be generated always when the link enters poll
3774 if (DWC3_VER_IS_PRIOR(DWC3, 190A))
3775 dwc3_gadget_reset_interrupt(dwc);
3777 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3778 dwc->gadget->ep0->maxpacket = 512;
3779 dwc->gadget->speed = USB_SPEED_SUPER;
3782 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3783 dwc->gadget->ssp_rate = USB_SSP_GEN_1x2;
3786 case DWC3_DSTS_HIGHSPEED:
3787 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3788 dwc->gadget->ep0->maxpacket = 64;
3789 dwc->gadget->speed = USB_SPEED_HIGH;
3791 case DWC3_DSTS_FULLSPEED:
3792 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3793 dwc->gadget->ep0->maxpacket = 64;
3794 dwc->gadget->speed = USB_SPEED_FULL;
3798 dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
3800 /* Enable USB2 LPM Capability */
3802 if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
3803 !dwc->usb2_gadget_lpm_disable &&
3804 (speed != DWC3_DSTS_SUPERSPEED) &&
3805 (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
3806 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3807 reg |= DWC3_DCFG_LPM_CAP;
3808 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3810 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3811 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
3813 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
3814 (dwc->is_utmi_l1_suspend << 4));
3817 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
3818 * DCFG.LPMCap is set, core responses with an ACK and the
3819 * BESL value in the LPM token is less than or equal to LPM
3822 WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
3823 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
3825 if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
3826 reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
3828 dwc3_gadget_dctl_write_safe(dwc, reg);
3830 if (dwc->usb2_gadget_lpm_disable) {
3831 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3832 reg &= ~DWC3_DCFG_LPM_CAP;
3833 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3836 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3837 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
3838 dwc3_gadget_dctl_write_safe(dwc, reg);
3842 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3844 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3849 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3851 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3856 * Configure PHY via GUSB3PIPECTLn if required.
3858 * Update GTXFIFOSIZn
3860 * In both cases reset values should be sufficient.
3864 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
3867 * TODO take core out of low power mode when that's
3871 if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3872 spin_unlock(&dwc->lock);
3873 dwc->gadget_driver->resume(dwc->gadget);
3874 spin_lock(&dwc->lock);
3878 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
3879 unsigned int evtinfo)
3881 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3882 unsigned int pwropt;
3885 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
3886 * Hibernation mode enabled which would show up when device detects
3887 * host-initiated U3 exit.
3889 * In that case, device will generate a Link State Change Interrupt
3890 * from U3 to RESUME which is only necessary if Hibernation is
3893 * There are no functional changes due to such spurious event and we
3894 * just need to ignore it.
3898 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
3901 pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
3902 if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
3903 (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
3904 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
3905 (next == DWC3_LINK_STATE_RESUME)) {
3911 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
3912 * on the link partner, the USB session might do multiple entry/exit
3913 * of low power states before a transfer takes place.
3915 * Due to this problem, we might experience lower throughput. The
3916 * suggested workaround is to disable DCTL[12:9] bits if we're
3917 * transitioning from U1/U2 to U0 and enable those bits again
3918 * after a transfer completes and there are no pending transfers
3919 * on any of the enabled endpoints.
3921 * This is the first half of that workaround.
3925 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
3926 * core send LGO_Ux entering U0
3928 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3929 if (next == DWC3_LINK_STATE_U0) {
3933 switch (dwc->link_state) {
3934 case DWC3_LINK_STATE_U1:
3935 case DWC3_LINK_STATE_U2:
3936 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3937 u1u2 = reg & (DWC3_DCTL_INITU2ENA
3938 | DWC3_DCTL_ACCEPTU2ENA
3939 | DWC3_DCTL_INITU1ENA
3940 | DWC3_DCTL_ACCEPTU1ENA);
3943 dwc->u1u2 = reg & u1u2;
3947 dwc3_gadget_dctl_write_safe(dwc, reg);
3957 case DWC3_LINK_STATE_U1:
3958 if (dwc->speed == USB_SPEED_SUPER)
3959 dwc3_suspend_gadget(dwc);
3961 case DWC3_LINK_STATE_U2:
3962 case DWC3_LINK_STATE_U3:
3963 dwc3_suspend_gadget(dwc);
3965 case DWC3_LINK_STATE_RESUME:
3966 dwc3_resume_gadget(dwc);
3973 dwc->link_state = next;
3976 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
3977 unsigned int evtinfo)
3979 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3981 if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
3982 dwc3_suspend_gadget(dwc);
3984 dwc->link_state = next;
3987 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
3988 unsigned int evtinfo)
3990 unsigned int is_ss = evtinfo & BIT(4);
3993 * WORKAROUND: DWC3 revison 2.20a with hibernation support
3994 * have a known issue which can cause USB CV TD.9.23 to fail
3997 * Because of this issue, core could generate bogus hibernation
3998 * events which SW needs to ignore.
4002 * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
4003 * Device Fallback from SuperSpeed
4005 if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
4008 /* enter hibernation here */
4011 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
4012 const struct dwc3_event_devt *event)
4014 switch (event->type) {
4015 case DWC3_DEVICE_EVENT_DISCONNECT:
4016 dwc3_gadget_disconnect_interrupt(dwc);
4018 case DWC3_DEVICE_EVENT_RESET:
4019 dwc3_gadget_reset_interrupt(dwc);
4021 case DWC3_DEVICE_EVENT_CONNECT_DONE:
4022 dwc3_gadget_conndone_interrupt(dwc);
4024 case DWC3_DEVICE_EVENT_WAKEUP:
4025 dwc3_gadget_wakeup_interrupt(dwc);
4027 case DWC3_DEVICE_EVENT_HIBER_REQ:
4028 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
4029 "unexpected hibernation event\n"))
4032 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
4034 case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
4035 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
4037 case DWC3_DEVICE_EVENT_SUSPEND:
4038 /* It changed to be suspend event for version 2.30a and above */
4039 if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) {
4041 * Ignore suspend event until the gadget enters into
4042 * USB_STATE_CONFIGURED state.
4044 if (dwc->gadget->state >= USB_STATE_CONFIGURED)
4045 dwc3_gadget_suspend_interrupt(dwc,
4049 case DWC3_DEVICE_EVENT_SOF:
4050 case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
4051 case DWC3_DEVICE_EVENT_CMD_CMPL:
4052 case DWC3_DEVICE_EVENT_OVERFLOW:
4055 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
4059 static void dwc3_process_event_entry(struct dwc3 *dwc,
4060 const union dwc3_event *event)
4062 trace_dwc3_event(event->raw, dwc);
4064 if (!event->type.is_devspec)
4065 dwc3_endpoint_interrupt(dwc, &event->depevt);
4066 else if (event->type.type == DWC3_EVENT_TYPE_DEV)
4067 dwc3_gadget_interrupt(dwc, &event->devt);
4069 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
4072 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
4074 struct dwc3 *dwc = evt->dwc;
4075 irqreturn_t ret = IRQ_NONE;
4081 if (!(evt->flags & DWC3_EVENT_PENDING))
4085 union dwc3_event event;
4087 event.raw = *(u32 *) (evt->cache + evt->lpos);
4089 dwc3_process_event_entry(dwc, &event);
4092 * FIXME we wrap around correctly to the next entry as
4093 * almost all entries are 4 bytes in size. There is one
4094 * entry which has 12 bytes which is a regular entry
4095 * followed by 8 bytes data. ATM I don't know how
4096 * things are organized if we get next to the a
4097 * boundary so I worry about that once we try to handle
4100 evt->lpos = (evt->lpos + 4) % evt->length;
4105 evt->flags &= ~DWC3_EVENT_PENDING;
4108 /* Unmask interrupt */
4109 reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
4110 reg &= ~DWC3_GEVNTSIZ_INTMASK;
4111 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
4113 if (dwc->imod_interval) {
4114 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
4115 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
4121 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
4123 struct dwc3_event_buffer *evt = _evt;
4124 struct dwc3 *dwc = evt->dwc;
4125 unsigned long flags;
4126 irqreturn_t ret = IRQ_NONE;
4128 spin_lock_irqsave(&dwc->lock, flags);
4129 ret = dwc3_process_event_buf(evt);
4130 spin_unlock_irqrestore(&dwc->lock, flags);
4135 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
4137 struct dwc3 *dwc = evt->dwc;
4142 if (pm_runtime_suspended(dwc->dev)) {
4143 pm_runtime_get(dwc->dev);
4144 disable_irq_nosync(dwc->irq_gadget);
4145 dwc->pending_events = true;
4150 * With PCIe legacy interrupt, test shows that top-half irq handler can
4151 * be called again after HW interrupt deassertion. Check if bottom-half
4152 * irq event handler completes before caching new event to prevent
4155 if (evt->flags & DWC3_EVENT_PENDING)
4158 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
4159 count &= DWC3_GEVNTCOUNT_MASK;
4164 evt->flags |= DWC3_EVENT_PENDING;
4166 /* Mask interrupt */
4167 reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
4168 reg |= DWC3_GEVNTSIZ_INTMASK;
4169 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
4171 amount = min(count, evt->length - evt->lpos);
4172 memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
4175 memcpy(evt->cache, evt->buf, count - amount);
4177 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
4179 return IRQ_WAKE_THREAD;
4182 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
4184 struct dwc3_event_buffer *evt = _evt;
4186 return dwc3_check_event_buf(evt);
4189 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
4191 struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
4194 irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
4198 if (irq == -EPROBE_DEFER)
4201 irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
4205 if (irq == -EPROBE_DEFER)
4208 irq = platform_get_irq(dwc3_pdev, 0);
4219 static void dwc_gadget_release(struct device *dev)
4221 struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
4227 * dwc3_gadget_init - initializes gadget related registers
4228 * @dwc: pointer to our controller context structure
4230 * Returns 0 on success otherwise negative errno.
4232 int dwc3_gadget_init(struct dwc3 *dwc)
4238 irq = dwc3_gadget_get_irq(dwc);
4244 dwc->irq_gadget = irq;
4246 dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
4247 sizeof(*dwc->ep0_trb) * 2,
4248 &dwc->ep0_trb_addr, GFP_KERNEL);
4249 if (!dwc->ep0_trb) {
4250 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
4255 dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
4256 if (!dwc->setup_buf) {
4261 dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
4262 &dwc->bounce_addr, GFP_KERNEL);
4268 init_completion(&dwc->ep0_in_setup);
4269 dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
4276 usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
4277 dev = &dwc->gadget->dev;
4278 dev->platform_data = dwc;
4279 dwc->gadget->ops = &dwc3_gadget_ops;
4280 dwc->gadget->speed = USB_SPEED_UNKNOWN;
4281 dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
4282 dwc->gadget->sg_supported = true;
4283 dwc->gadget->name = "dwc3-gadget";
4284 dwc->gadget->lpm_capable = !dwc->usb2_gadget_lpm_disable;
4287 * FIXME We might be setting max_speed to <SUPER, however versions
4288 * <2.20a of dwc3 have an issue with metastability (documented
4289 * elsewhere in this driver) which tells us we can't set max speed to
4290 * anything lower than SUPER.
4292 * Because gadget.max_speed is only used by composite.c and function
4293 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
4294 * to happen so we avoid sending SuperSpeed Capability descriptor
4295 * together with our BOS descriptor as that could confuse host into
4296 * thinking we can handle super speed.
4298 * Note that, in fact, we won't even support GetBOS requests when speed
4299 * is less than super speed because we don't have means, yet, to tell
4300 * composite.c that we are USB 2.0 + LPM ECN.
4302 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
4303 !dwc->dis_metastability_quirk)
4304 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
4307 dwc->gadget->max_speed = dwc->maximum_speed;
4308 dwc->gadget->max_ssp_rate = dwc->max_ssp_rate;
4311 * REVISIT: Here we should clear all pending IRQs to be
4312 * sure we're starting from a well known location.
4315 ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
4319 ret = usb_add_gadget(dwc->gadget);
4321 dev_err(dwc->dev, "failed to add gadget\n");
4325 if (DWC3_IP_IS(DWC32) && dwc->maximum_speed == USB_SPEED_SUPER_PLUS)
4326 dwc3_gadget_set_ssp_rate(dwc->gadget, dwc->max_ssp_rate);
4328 dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
4333 dwc3_gadget_free_endpoints(dwc);
4335 usb_put_gadget(dwc->gadget);
4338 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4342 kfree(dwc->setup_buf);
4345 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4346 dwc->ep0_trb, dwc->ep0_trb_addr);
4352 /* -------------------------------------------------------------------------- */
4354 void dwc3_gadget_exit(struct dwc3 *dwc)
4359 usb_del_gadget(dwc->gadget);
4360 dwc3_gadget_free_endpoints(dwc);
4361 usb_put_gadget(dwc->gadget);
4362 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4364 kfree(dwc->setup_buf);
4365 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4366 dwc->ep0_trb, dwc->ep0_trb_addr);
4369 int dwc3_gadget_suspend(struct dwc3 *dwc)
4371 if (!dwc->gadget_driver)
4374 dwc3_gadget_run_stop(dwc, false, false);
4375 dwc3_disconnect_gadget(dwc);
4376 __dwc3_gadget_stop(dwc);
4381 int dwc3_gadget_resume(struct dwc3 *dwc)
4385 if (!dwc->gadget_driver || !dwc->softconnect)
4388 ret = __dwc3_gadget_start(dwc);
4392 ret = dwc3_gadget_run_stop(dwc, true, false);
4399 __dwc3_gadget_stop(dwc);
4405 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4407 if (dwc->pending_events) {
4408 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4409 dwc->pending_events = false;
4410 enable_irq(dwc->irq_gadget);