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
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",
335 * For some commands such as Update Transfer command, DEPCMDPARn
336 * registers are reserved. Since the driver often sends Update Transfer
337 * command, don't write to DEPCMDPARn to avoid register write delays and
338 * improve performance.
340 if (DWC3_DEPCMD_CMD(cmd) != DWC3_DEPCMD_UPDATETRANSFER) {
341 dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
342 dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
343 dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
347 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
348 * not relying on XferNotReady, we can make use of a special "No
349 * Response Update Transfer" command where we should clear both CmdAct
352 * With this, we don't need to wait for command completion and can
353 * straight away issue further commands to the endpoint.
355 * NOTICE: We're making an assumption that control endpoints will never
356 * make use of Update Transfer command. This is a safe assumption
357 * because we can never have more than one request at a time with
358 * Control Endpoints. If anybody changes that assumption, this chunk
359 * needs to be updated accordingly.
361 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
362 !usb_endpoint_xfer_isoc(desc))
363 cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
365 cmd |= DWC3_DEPCMD_CMDACT;
367 dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
369 if (!(cmd & DWC3_DEPCMD_CMDACT)) {
375 reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
376 if (!(reg & DWC3_DEPCMD_CMDACT)) {
377 cmd_status = DWC3_DEPCMD_STATUS(reg);
379 switch (cmd_status) {
383 case DEPEVT_TRANSFER_NO_RESOURCE:
384 dev_WARN(dwc->dev, "No resource for %s\n",
388 case DEPEVT_TRANSFER_BUS_EXPIRY:
390 * SW issues START TRANSFER command to
391 * isochronous ep with future frame interval. If
392 * future interval time has already passed when
393 * core receives the command, it will respond
394 * with an error status of 'Bus Expiry'.
396 * Instead of always returning -EINVAL, let's
397 * give a hint to the gadget driver that this is
398 * the case by returning -EAGAIN.
403 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
412 cmd_status = -ETIMEDOUT;
416 trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
418 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
420 dep->flags |= DWC3_EP_TRANSFER_STARTED;
422 if (ret != -ETIMEDOUT)
423 dwc3_gadget_ep_get_transfer_index(dep);
427 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
429 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
435 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
437 struct dwc3 *dwc = dep->dwc;
438 struct dwc3_gadget_ep_cmd_params params;
439 u32 cmd = DWC3_DEPCMD_CLEARSTALL;
442 * As of core revision 2.60a the recommended programming model
443 * is to set the ClearPendIN bit when issuing a Clear Stall EP
444 * command for IN endpoints. This is to prevent an issue where
445 * some (non-compliant) hosts may not send ACK TPs for pending
446 * IN transfers due to a mishandled error condition. Synopsys
449 if (dep->direction &&
450 !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
451 (dwc->gadget->speed >= USB_SPEED_SUPER))
452 cmd |= DWC3_DEPCMD_CLEARPENDIN;
454 memset(¶ms, 0, sizeof(params));
456 return dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
459 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
460 struct dwc3_trb *trb)
462 u32 offset = (char *) trb - (char *) dep->trb_pool;
464 return dep->trb_pool_dma + offset;
467 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
469 struct dwc3 *dwc = dep->dwc;
474 dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
475 sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
476 &dep->trb_pool_dma, GFP_KERNEL);
477 if (!dep->trb_pool) {
478 dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
486 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
488 struct dwc3 *dwc = dep->dwc;
490 dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
491 dep->trb_pool, dep->trb_pool_dma);
493 dep->trb_pool = NULL;
494 dep->trb_pool_dma = 0;
497 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
499 struct dwc3_gadget_ep_cmd_params params;
501 memset(¶ms, 0x00, sizeof(params));
503 params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
505 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
510 * dwc3_gadget_start_config - configure ep resources
511 * @dep: endpoint that is being enabled
513 * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
514 * completion, it will set Transfer Resource for all available endpoints.
516 * The assignment of transfer resources cannot perfectly follow the data book
517 * due to the fact that the controller driver does not have all knowledge of the
518 * configuration in advance. It is given this information piecemeal by the
519 * composite gadget framework after every SET_CONFIGURATION and
520 * SET_INTERFACE. Trying to follow the databook programming model in this
521 * scenario can cause errors. For two reasons:
523 * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
524 * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
525 * incorrect in the scenario of multiple interfaces.
527 * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
528 * endpoint on alt setting (8.1.6).
530 * The following simplified method is used instead:
532 * All hardware endpoints can be assigned a transfer resource and this setting
533 * will stay persistent until either a core reset or hibernation. So whenever we
534 * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
535 * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
536 * guaranteed that there are as many transfer resources as endpoints.
538 * This function is called for each endpoint when it is being enabled but is
539 * triggered only when called for EP0-out, which always happens first, and which
540 * should only happen in one of the above conditions.
542 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
544 struct dwc3_gadget_ep_cmd_params params;
553 memset(¶ms, 0x00, sizeof(params));
554 cmd = DWC3_DEPCMD_DEPSTARTCFG;
557 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
561 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
562 struct dwc3_ep *dep = dwc->eps[i];
567 ret = dwc3_gadget_set_xfer_resource(dep);
575 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
577 const struct usb_ss_ep_comp_descriptor *comp_desc;
578 const struct usb_endpoint_descriptor *desc;
579 struct dwc3_gadget_ep_cmd_params params;
580 struct dwc3 *dwc = dep->dwc;
582 comp_desc = dep->endpoint.comp_desc;
583 desc = dep->endpoint.desc;
585 memset(¶ms, 0x00, sizeof(params));
587 params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
588 | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
590 /* Burst size is only needed in SuperSpeed mode */
591 if (dwc->gadget->speed >= USB_SPEED_SUPER) {
592 u32 burst = dep->endpoint.maxburst;
594 params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
597 params.param0 |= action;
598 if (action == DWC3_DEPCFG_ACTION_RESTORE)
599 params.param2 |= dep->saved_state;
601 if (usb_endpoint_xfer_control(desc))
602 params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
604 if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
605 params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
607 if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
608 params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
609 | DWC3_DEPCFG_XFER_COMPLETE_EN
610 | DWC3_DEPCFG_STREAM_EVENT_EN;
611 dep->stream_capable = true;
614 if (!usb_endpoint_xfer_control(desc))
615 params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
618 * We are doing 1:1 mapping for endpoints, meaning
619 * Physical Endpoints 2 maps to Logical Endpoint 2 and
620 * so on. We consider the direction bit as part of the physical
621 * endpoint number. So USB endpoint 0x81 is 0x03.
623 params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
626 * We must use the lower 16 TX FIFOs even though
630 params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
632 if (desc->bInterval) {
636 * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
638 * NOTE: The programming guide incorrectly stated bInterval_m1
639 * must be set to 0 when operating in fullspeed. Internally the
640 * controller does not have this limitation. See DWC_usb3x
641 * programming guide section 3.2.2.1.
643 bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
645 if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
646 dwc->gadget->speed == USB_SPEED_FULL)
647 dep->interval = desc->bInterval;
649 dep->interval = 1 << (desc->bInterval - 1);
651 params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
654 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, ¶ms);
658 * dwc3_gadget_calc_tx_fifo_size - calculates the txfifo size value
659 * @dwc: pointer to the DWC3 context
660 * @nfifos: number of fifos to calculate for
662 * Calculates the size value based on the equation below:
664 * DWC3 revision 280A and prior:
665 * fifo_size = mult * (max_packet / mdwidth) + 1;
667 * DWC3 revision 290A and onwards:
668 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
670 * The max packet size is set to 1024, as the txfifo requirements mainly apply
671 * to super speed USB use cases. However, it is safe to overestimate the fifo
672 * allocations for other scenarios, i.e. high speed USB.
674 static int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult)
676 int max_packet = 1024;
680 mdwidth = dwc3_mdwidth(dwc);
682 /* MDWIDTH is represented in bits, we need it in bytes */
685 if (DWC3_VER_IS_PRIOR(DWC3, 290A))
686 fifo_size = mult * (max_packet / mdwidth) + 1;
688 fifo_size = mult * ((max_packet + mdwidth) / mdwidth) + 1;
693 * dwc3_gadget_clear_tx_fifo_size - Clears txfifo allocation
694 * @dwc: pointer to the DWC3 context
696 * Iterates through all the endpoint registers and clears the previous txfifo
699 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc)
706 if (!dwc->do_fifo_resize)
709 /* Read ep0IN related TXFIFO size */
711 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
712 if (DWC3_IP_IS(DWC3))
713 fifo_depth = DWC3_GTXFIFOSIZ_TXFDEP(size);
715 fifo_depth = DWC31_GTXFIFOSIZ_TXFDEP(size);
717 dwc->last_fifo_depth = fifo_depth;
718 /* Clear existing TXFIFO for all IN eps except ep0 */
719 for (num = 3; num < min_t(int, dwc->num_eps, DWC3_ENDPOINTS_NUM);
722 /* Don't change TXFRAMNUM on usb31 version */
723 size = DWC3_IP_IS(DWC3) ? 0 :
724 dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1)) &
725 DWC31_GTXFIFOSIZ_TXFRAMNUM;
727 dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1), size);
728 dep->flags &= ~DWC3_EP_TXFIFO_RESIZED;
730 dwc->num_ep_resized = 0;
734 * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
735 * @dwc: pointer to our context structure
737 * This function will a best effort FIFO allocation in order
738 * to improve FIFO usage and throughput, while still allowing
739 * us to enable as many endpoints as possible.
741 * Keep in mind that this operation will be highly dependent
742 * on the configured size for RAM1 - which contains TxFifo -,
743 * the amount of endpoints enabled on coreConsultant tool, and
744 * the width of the Master Bus.
746 * In general, FIFO depths are represented with the following equation:
748 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
750 * In conjunction with dwc3_gadget_check_config(), this resizing logic will
751 * ensure that all endpoints will have enough internal memory for one max
752 * packet per endpoint.
754 static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep)
756 struct dwc3 *dwc = dep->dwc;
767 if (!dwc->do_fifo_resize)
770 /* resize IN endpoints except ep0 */
771 if (!usb_endpoint_dir_in(dep->endpoint.desc) || dep->number <= 1)
774 /* bail if already resized */
775 if (dep->flags & DWC3_EP_TXFIFO_RESIZED)
778 ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
780 if ((dep->endpoint.maxburst > 1 &&
781 usb_endpoint_xfer_bulk(dep->endpoint.desc)) ||
782 usb_endpoint_xfer_isoc(dep->endpoint.desc))
785 if (dep->endpoint.maxburst > 6 &&
786 usb_endpoint_xfer_bulk(dep->endpoint.desc) && DWC3_IP_IS(DWC31))
787 num_fifos = dwc->tx_fifo_resize_max_num;
789 /* FIFO size for a single buffer */
790 fifo = dwc3_gadget_calc_tx_fifo_size(dwc, 1);
792 /* Calculate the number of remaining EPs w/o any FIFO */
793 num_in_ep = dwc->max_cfg_eps;
794 num_in_ep -= dwc->num_ep_resized;
796 /* Reserve at least one FIFO for the number of IN EPs */
797 min_depth = num_in_ep * (fifo + 1);
798 remaining = ram1_depth - min_depth - dwc->last_fifo_depth;
799 remaining = max_t(int, 0, remaining);
801 * We've already reserved 1 FIFO per EP, so check what we can fit in
802 * addition to it. If there is not enough remaining space, allocate
803 * all the remaining space to the EP.
805 fifo_size = (num_fifos - 1) * fifo;
806 if (remaining < fifo_size)
807 fifo_size = remaining;
810 /* Last increment according to the TX FIFO size equation */
813 /* Check if TXFIFOs start at non-zero addr */
814 tmp = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
815 fifo_0_start = DWC3_GTXFIFOSIZ_TXFSTADDR(tmp);
817 fifo_size |= (fifo_0_start + (dwc->last_fifo_depth << 16));
818 if (DWC3_IP_IS(DWC3))
819 dwc->last_fifo_depth += DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
821 dwc->last_fifo_depth += DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
823 /* Check fifo size allocation doesn't exceed available RAM size. */
824 if (dwc->last_fifo_depth >= ram1_depth) {
825 dev_err(dwc->dev, "Fifosize(%d) > RAM size(%d) %s depth:%d\n",
826 dwc->last_fifo_depth, ram1_depth,
827 dep->endpoint.name, fifo_size);
828 if (DWC3_IP_IS(DWC3))
829 fifo_size = DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
831 fifo_size = DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
833 dwc->last_fifo_depth -= fifo_size;
837 dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1), fifo_size);
838 dep->flags |= DWC3_EP_TXFIFO_RESIZED;
839 dwc->num_ep_resized++;
845 * __dwc3_gadget_ep_enable - initializes a hw endpoint
846 * @dep: endpoint to be initialized
847 * @action: one of INIT, MODIFY or RESTORE
849 * Caller should take care of locking. Execute all necessary commands to
850 * initialize a HW endpoint so it can be used by a gadget driver.
852 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
854 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
855 struct dwc3 *dwc = dep->dwc;
860 if (!(dep->flags & DWC3_EP_ENABLED)) {
861 ret = dwc3_gadget_resize_tx_fifos(dep);
865 ret = dwc3_gadget_start_config(dep);
870 ret = dwc3_gadget_set_ep_config(dep, action);
874 if (!(dep->flags & DWC3_EP_ENABLED)) {
875 struct dwc3_trb *trb_st_hw;
876 struct dwc3_trb *trb_link;
878 dep->type = usb_endpoint_type(desc);
879 dep->flags |= DWC3_EP_ENABLED;
881 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
882 reg |= DWC3_DALEPENA_EP(dep->number);
883 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
885 if (usb_endpoint_xfer_control(desc))
888 /* Initialize the TRB ring */
889 dep->trb_dequeue = 0;
890 dep->trb_enqueue = 0;
891 memset(dep->trb_pool, 0,
892 sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
894 /* Link TRB. The HWO bit is never reset */
895 trb_st_hw = &dep->trb_pool[0];
897 trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
898 trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
899 trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
900 trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
901 trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
905 * Issue StartTransfer here with no-op TRB so we can always rely on No
906 * Response Update Transfer command.
908 if (usb_endpoint_xfer_bulk(desc) ||
909 usb_endpoint_xfer_int(desc)) {
910 struct dwc3_gadget_ep_cmd_params params;
911 struct dwc3_trb *trb;
915 memset(¶ms, 0, sizeof(params));
916 trb = &dep->trb_pool[0];
917 trb_dma = dwc3_trb_dma_offset(dep, trb);
919 params.param0 = upper_32_bits(trb_dma);
920 params.param1 = lower_32_bits(trb_dma);
922 cmd = DWC3_DEPCMD_STARTTRANSFER;
924 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
928 if (dep->stream_capable) {
930 * For streams, at start, there maybe a race where the
931 * host primes the endpoint before the function driver
932 * queues a request to initiate a stream. In that case,
933 * the controller will not see the prime to generate the
934 * ERDY and start stream. To workaround this, issue a
935 * no-op TRB as normal, but end it immediately. As a
936 * result, when the function driver queues the request,
937 * the next START_TRANSFER command will cause the
938 * controller to generate an ERDY to initiate the
941 dwc3_stop_active_transfer(dep, true, true);
944 * All stream eps will reinitiate stream on NoStream
945 * rejection until we can determine that the host can
946 * prime after the first transfer.
948 * However, if the controller is capable of
949 * TXF_FLUSH_BYPASS, then IN direction endpoints will
950 * automatically restart the stream without the driver
953 if (!dep->direction ||
954 !(dwc->hwparams.hwparams9 &
955 DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
956 dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
961 trace_dwc3_gadget_ep_enable(dep);
966 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
968 struct dwc3_request *req;
970 dwc3_stop_active_transfer(dep, true, false);
972 /* - giveback all requests to gadget driver */
973 while (!list_empty(&dep->started_list)) {
974 req = next_request(&dep->started_list);
976 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
979 while (!list_empty(&dep->pending_list)) {
980 req = next_request(&dep->pending_list);
982 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
985 while (!list_empty(&dep->cancelled_list)) {
986 req = next_request(&dep->cancelled_list);
988 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
993 * __dwc3_gadget_ep_disable - disables a hw endpoint
994 * @dep: the endpoint to disable
996 * This function undoes what __dwc3_gadget_ep_enable did and also removes
997 * requests which are currently being processed by the hardware and those which
998 * are not yet scheduled.
1000 * Caller should take care of locking.
1002 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
1004 struct dwc3 *dwc = dep->dwc;
1007 trace_dwc3_gadget_ep_disable(dep);
1009 /* make sure HW endpoint isn't stalled */
1010 if (dep->flags & DWC3_EP_STALL)
1011 __dwc3_gadget_ep_set_halt(dep, 0, false);
1013 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
1014 reg &= ~DWC3_DALEPENA_EP(dep->number);
1015 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
1017 /* Clear out the ep descriptors for non-ep0 */
1018 if (dep->number > 1) {
1019 dep->endpoint.comp_desc = NULL;
1020 dep->endpoint.desc = NULL;
1023 dwc3_remove_requests(dwc, dep);
1025 dep->stream_capable = false;
1027 dep->flags &= DWC3_EP_TXFIFO_RESIZED;
1032 /* -------------------------------------------------------------------------- */
1034 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
1035 const struct usb_endpoint_descriptor *desc)
1040 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
1045 /* -------------------------------------------------------------------------- */
1047 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
1048 const struct usb_endpoint_descriptor *desc)
1050 struct dwc3_ep *dep;
1052 unsigned long flags;
1055 if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
1056 pr_debug("dwc3: invalid parameters\n");
1060 if (!desc->wMaxPacketSize) {
1061 pr_debug("dwc3: missing wMaxPacketSize\n");
1065 dep = to_dwc3_ep(ep);
1068 if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
1069 "%s is already enabled\n",
1073 spin_lock_irqsave(&dwc->lock, flags);
1074 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1075 spin_unlock_irqrestore(&dwc->lock, flags);
1080 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
1082 struct dwc3_ep *dep;
1084 unsigned long flags;
1088 pr_debug("dwc3: invalid parameters\n");
1092 dep = to_dwc3_ep(ep);
1095 if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
1096 "%s is already disabled\n",
1100 spin_lock_irqsave(&dwc->lock, flags);
1101 ret = __dwc3_gadget_ep_disable(dep);
1102 spin_unlock_irqrestore(&dwc->lock, flags);
1107 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
1110 struct dwc3_request *req;
1111 struct dwc3_ep *dep = to_dwc3_ep(ep);
1113 req = kzalloc(sizeof(*req), gfp_flags);
1117 req->direction = dep->direction;
1118 req->epnum = dep->number;
1120 req->status = DWC3_REQUEST_STATUS_UNKNOWN;
1122 trace_dwc3_alloc_request(req);
1124 return &req->request;
1127 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
1128 struct usb_request *request)
1130 struct dwc3_request *req = to_dwc3_request(request);
1132 trace_dwc3_free_request(req);
1137 * dwc3_ep_prev_trb - returns the previous TRB in the ring
1138 * @dep: The endpoint with the TRB ring
1139 * @index: The index of the current TRB in the ring
1141 * Returns the TRB prior to the one pointed to by the index. If the
1142 * index is 0, we will wrap backwards, skip the link TRB, and return
1143 * the one just before that.
1145 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1150 tmp = DWC3_TRB_NUM - 1;
1152 return &dep->trb_pool[tmp - 1];
1155 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1160 * If the enqueue & dequeue are equal then the TRB ring is either full
1161 * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
1162 * pending to be processed by the driver.
1164 if (dep->trb_enqueue == dep->trb_dequeue) {
1166 * If there is any request remained in the started_list at
1167 * this point, that means there is no TRB available.
1169 if (!list_empty(&dep->started_list))
1172 return DWC3_TRB_NUM - 1;
1175 trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1176 trbs_left &= (DWC3_TRB_NUM - 1);
1178 if (dep->trb_dequeue < dep->trb_enqueue)
1184 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
1185 dma_addr_t dma, unsigned int length, unsigned int chain,
1186 unsigned int node, unsigned int stream_id,
1187 unsigned int short_not_ok, unsigned int no_interrupt,
1188 unsigned int is_last, bool must_interrupt)
1190 struct dwc3 *dwc = dep->dwc;
1191 struct usb_gadget *gadget = dwc->gadget;
1192 enum usb_device_speed speed = gadget->speed;
1194 trb->size = DWC3_TRB_SIZE_LENGTH(length);
1195 trb->bpl = lower_32_bits(dma);
1196 trb->bph = upper_32_bits(dma);
1198 switch (usb_endpoint_type(dep->endpoint.desc)) {
1199 case USB_ENDPOINT_XFER_CONTROL:
1200 trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
1203 case USB_ENDPOINT_XFER_ISOC:
1205 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
1208 * USB Specification 2.0 Section 5.9.2 states that: "If
1209 * there is only a single transaction in the microframe,
1210 * only a DATA0 data packet PID is used. If there are
1211 * two transactions per microframe, DATA1 is used for
1212 * the first transaction data packet and DATA0 is used
1213 * for the second transaction data packet. If there are
1214 * three transactions per microframe, DATA2 is used for
1215 * the first transaction data packet, DATA1 is used for
1216 * the second, and DATA0 is used for the third."
1218 * IOW, we should satisfy the following cases:
1220 * 1) length <= maxpacket
1223 * 2) maxpacket < length <= (2 * maxpacket)
1226 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1227 * - DATA2, DATA1, DATA0
1229 if (speed == USB_SPEED_HIGH) {
1230 struct usb_ep *ep = &dep->endpoint;
1231 unsigned int mult = 2;
1232 unsigned int maxp = usb_endpoint_maxp(ep->desc);
1234 if (length <= (2 * maxp))
1240 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1243 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1246 /* always enable Interrupt on Missed ISOC */
1247 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1250 case USB_ENDPOINT_XFER_BULK:
1251 case USB_ENDPOINT_XFER_INT:
1252 trb->ctrl = DWC3_TRBCTL_NORMAL;
1256 * This is only possible with faulty memory because we
1257 * checked it already :)
1259 dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1260 usb_endpoint_type(dep->endpoint.desc));
1264 * Enable Continue on Short Packet
1265 * when endpoint is not a stream capable
1267 if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1268 if (!dep->stream_capable)
1269 trb->ctrl |= DWC3_TRB_CTRL_CSP;
1272 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1275 /* All TRBs setup for MST must set CSP=1 when LST=0 */
1276 if (dep->stream_capable && DWC3_MST_CAPABLE(&dwc->hwparams))
1277 trb->ctrl |= DWC3_TRB_CTRL_CSP;
1279 if ((!no_interrupt && !chain) || must_interrupt)
1280 trb->ctrl |= DWC3_TRB_CTRL_IOC;
1283 trb->ctrl |= DWC3_TRB_CTRL_CHN;
1284 else if (dep->stream_capable && is_last &&
1285 !DWC3_MST_CAPABLE(&dwc->hwparams))
1286 trb->ctrl |= DWC3_TRB_CTRL_LST;
1288 if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1289 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1292 * As per data book 4.2.3.2TRB Control Bit Rules section
1294 * The controller autonomously checks the HWO field of a TRB to determine if the
1295 * entire TRB is valid. Therefore, software must ensure that the rest of the TRB
1296 * is valid before setting the HWO field to '1'. In most systems, this means that
1297 * software must update the fourth DWORD of a TRB last.
1299 * However there is a possibility of CPU re-ordering here which can cause
1300 * controller to observe the HWO bit set prematurely.
1301 * Add a write memory barrier to prevent CPU re-ordering.
1304 trb->ctrl |= DWC3_TRB_CTRL_HWO;
1306 dwc3_ep_inc_enq(dep);
1308 trace_dwc3_prepare_trb(dep, trb);
1312 * dwc3_prepare_one_trb - setup one TRB from one request
1313 * @dep: endpoint for which this request is prepared
1314 * @req: dwc3_request pointer
1315 * @trb_length: buffer size of the TRB
1316 * @chain: should this TRB be chained to the next?
1317 * @node: only for isochronous endpoints. First TRB needs different type.
1318 * @use_bounce_buffer: set to use bounce buffer
1319 * @must_interrupt: set to interrupt on TRB completion
1321 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1322 struct dwc3_request *req, unsigned int trb_length,
1323 unsigned int chain, unsigned int node, bool use_bounce_buffer,
1324 bool must_interrupt)
1326 struct dwc3_trb *trb;
1328 unsigned int stream_id = req->request.stream_id;
1329 unsigned int short_not_ok = req->request.short_not_ok;
1330 unsigned int no_interrupt = req->request.no_interrupt;
1331 unsigned int is_last = req->request.is_last;
1333 if (use_bounce_buffer)
1334 dma = dep->dwc->bounce_addr;
1335 else if (req->request.num_sgs > 0)
1336 dma = sg_dma_address(req->start_sg);
1338 dma = req->request.dma;
1340 trb = &dep->trb_pool[dep->trb_enqueue];
1343 dwc3_gadget_move_started_request(req);
1345 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1350 __dwc3_prepare_one_trb(dep, trb, dma, trb_length, chain, node,
1351 stream_id, short_not_ok, no_interrupt, is_last,
1355 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1357 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1358 unsigned int rem = req->request.length % maxp;
1360 if ((req->request.length && req->request.zero && !rem &&
1361 !usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1362 (!req->direction && rem))
1369 * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1370 * @dep: The endpoint that the request belongs to
1371 * @req: The request to prepare
1372 * @entry_length: The last SG entry size
1373 * @node: Indicates whether this is not the first entry (for isoc only)
1375 * Return the number of TRBs prepared.
1377 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1378 struct dwc3_request *req, unsigned int entry_length,
1381 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1382 unsigned int rem = req->request.length % maxp;
1383 unsigned int num_trbs = 1;
1385 if (dwc3_needs_extra_trb(dep, req))
1388 if (dwc3_calc_trbs_left(dep) < num_trbs)
1391 req->needs_extra_trb = num_trbs > 1;
1393 /* Prepare a normal TRB */
1394 if (req->direction || req->request.length)
1395 dwc3_prepare_one_trb(dep, req, entry_length,
1396 req->needs_extra_trb, node, false, false);
1398 /* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1399 if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1400 dwc3_prepare_one_trb(dep, req,
1401 req->direction ? 0 : maxp - rem,
1402 false, 1, true, false);
1407 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1408 struct dwc3_request *req)
1410 struct scatterlist *sg = req->start_sg;
1411 struct scatterlist *s;
1413 unsigned int length = req->request.length;
1414 unsigned int remaining = req->request.num_mapped_sgs
1415 - req->num_queued_sgs;
1416 unsigned int num_trbs = req->num_trbs;
1417 bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1420 * If we resume preparing the request, then get the remaining length of
1421 * the request and resume where we left off.
1423 for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1424 length -= sg_dma_len(s);
1426 for_each_sg(sg, s, remaining, i) {
1427 unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1428 unsigned int trb_length;
1429 bool must_interrupt = false;
1430 bool last_sg = false;
1432 trb_length = min_t(unsigned int, length, sg_dma_len(s));
1434 length -= trb_length;
1437 * IOMMU driver is coalescing the list of sgs which shares a
1438 * page boundary into one and giving it to USB driver. With
1439 * this the number of sgs mapped is not equal to the number of
1440 * sgs passed. So mark the chain bit to false if it isthe last
1443 if ((i == remaining - 1) || !length)
1450 if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1454 * Look ahead to check if we have enough TRBs for the
1455 * next SG entry. If not, set interrupt on this TRB to
1456 * resume preparing the next SG entry when more TRBs are
1459 if (num_trbs_left == 1 || (needs_extra_trb &&
1460 num_trbs_left <= 2 &&
1461 sg_dma_len(sg_next(s)) >= length))
1462 must_interrupt = true;
1464 dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1469 * There can be a situation where all sgs in sglist are not
1470 * queued because of insufficient trb number. To handle this
1471 * case, update start_sg to next sg to be queued, so that
1472 * we have free trbs we can continue queuing from where we
1473 * previously stopped
1476 req->start_sg = sg_next(s);
1478 req->num_queued_sgs++;
1479 req->num_pending_sgs--;
1482 * The number of pending SG entries may not correspond to the
1483 * number of mapped SG entries. If all the data are queued, then
1484 * don't include unused SG entries.
1487 req->num_pending_sgs = 0;
1495 return req->num_trbs - num_trbs;
1498 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1499 struct dwc3_request *req)
1501 return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1505 * dwc3_prepare_trbs - setup TRBs from requests
1506 * @dep: endpoint for which requests are being prepared
1508 * The function goes through the requests list and sets up TRBs for the
1509 * transfers. The function returns once there are no more TRBs available or
1510 * it runs out of requests.
1512 * Returns the number of TRBs prepared or negative errno.
1514 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1516 struct dwc3_request *req, *n;
1519 BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1522 * We can get in a situation where there's a request in the started list
1523 * but there weren't enough TRBs to fully kick it in the first time
1524 * around, so it has been waiting for more TRBs to be freed up.
1526 * In that case, we should check if we have a request with pending_sgs
1527 * in the started list and prepare TRBs for that request first,
1528 * otherwise we will prepare TRBs completely out of order and that will
1531 list_for_each_entry(req, &dep->started_list, list) {
1532 if (req->num_pending_sgs > 0) {
1533 ret = dwc3_prepare_trbs_sg(dep, req);
1534 if (!ret || req->num_pending_sgs)
1538 if (!dwc3_calc_trbs_left(dep))
1542 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1543 * burst capability may try to read and use TRBs beyond the
1544 * active transfer instead of stopping.
1546 if (dep->stream_capable && req->request.is_last &&
1547 !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1551 list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1552 struct dwc3 *dwc = dep->dwc;
1554 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1559 req->sg = req->request.sg;
1560 req->start_sg = req->sg;
1561 req->num_queued_sgs = 0;
1562 req->num_pending_sgs = req->request.num_mapped_sgs;
1564 if (req->num_pending_sgs > 0) {
1565 ret = dwc3_prepare_trbs_sg(dep, req);
1566 if (req->num_pending_sgs)
1569 ret = dwc3_prepare_trbs_linear(dep, req);
1572 if (!ret || !dwc3_calc_trbs_left(dep))
1576 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1577 * burst capability may try to read and use TRBs beyond the
1578 * active transfer instead of stopping.
1580 if (dep->stream_capable && req->request.is_last &&
1581 !DWC3_MST_CAPABLE(&dwc->hwparams))
1588 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1590 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1592 struct dwc3_gadget_ep_cmd_params params;
1593 struct dwc3_request *req;
1599 * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1600 * This happens when we need to stop and restart a transfer such as in
1601 * the case of reinitiating a stream or retrying an isoc transfer.
1603 ret = dwc3_prepare_trbs(dep);
1607 starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1610 * If there's no new TRB prepared and we don't need to restart a
1611 * transfer, there's no need to update the transfer.
1613 if (!ret && !starting)
1616 req = next_request(&dep->started_list);
1618 dep->flags |= DWC3_EP_PENDING_REQUEST;
1622 memset(¶ms, 0, sizeof(params));
1625 params.param0 = upper_32_bits(req->trb_dma);
1626 params.param1 = lower_32_bits(req->trb_dma);
1627 cmd = DWC3_DEPCMD_STARTTRANSFER;
1629 if (dep->stream_capable)
1630 cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1632 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1633 cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1635 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1636 DWC3_DEPCMD_PARAM(dep->resource_index);
1639 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1641 struct dwc3_request *tmp;
1646 dwc3_stop_active_transfer(dep, true, true);
1648 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1649 dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_DEQUEUED);
1651 /* If ep isn't started, then there's no end transfer pending */
1652 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1653 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1658 if (dep->stream_capable && req->request.is_last &&
1659 !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1660 dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1665 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1669 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1670 return DWC3_DSTS_SOFFN(reg);
1674 * __dwc3_stop_active_transfer - stop the current active transfer
1675 * @dep: isoc endpoint
1676 * @force: set forcerm bit in the command
1677 * @interrupt: command complete interrupt after End Transfer command
1679 * When setting force, the ForceRM bit will be set. In that case
1680 * the controller won't update the TRB progress on command
1681 * completion. It also won't clear the HWO bit in the TRB.
1682 * The command will also not complete immediately in that case.
1684 static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt)
1686 struct dwc3_gadget_ep_cmd_params params;
1690 cmd = DWC3_DEPCMD_ENDTRANSFER;
1691 cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
1692 cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
1693 cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
1694 memset(¶ms, 0, sizeof(params));
1695 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1697 dep->resource_index = 0;
1700 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
1702 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1708 * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1709 * @dep: isoc endpoint
1711 * This function tests for the correct combination of BIT[15:14] from the 16-bit
1712 * microframe number reported by the XferNotReady event for the future frame
1713 * number to start the isoc transfer.
1715 * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1716 * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1717 * XferNotReady event are invalid. The driver uses this number to schedule the
1718 * isochronous transfer and passes it to the START TRANSFER command. Because
1719 * this number is invalid, the command may fail. If BIT[15:14] matches the
1720 * internal 16-bit microframe, the START TRANSFER command will pass and the
1721 * transfer will start at the scheduled time, if it is off by 1, the command
1722 * will still pass, but the transfer will start 2 seconds in the future. For all
1723 * other conditions, the START TRANSFER command will fail with bus-expiry.
1725 * In order to workaround this issue, we can test for the correct combination of
1726 * BIT[15:14] by sending START TRANSFER commands with different values of
1727 * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1728 * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1729 * As the result, within the 4 possible combinations for BIT[15:14], there will
1730 * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1731 * command status will result in a 2-second delay start. The smaller BIT[15:14]
1732 * value is the correct combination.
1734 * Since there are only 4 outcomes and the results are ordered, we can simply
1735 * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1736 * deduce the smaller successful combination.
1738 * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1739 * of BIT[15:14]. The correct combination is as follow:
1741 * if test0 fails and test1 passes, BIT[15:14] is 'b01
1742 * if test0 fails and test1 fails, BIT[15:14] is 'b10
1743 * if test0 passes and test1 fails, BIT[15:14] is 'b11
1744 * if test0 passes and test1 passes, BIT[15:14] is 'b00
1746 * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1749 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1755 while (dep->combo_num < 2) {
1756 struct dwc3_gadget_ep_cmd_params params;
1757 u32 test_frame_number;
1761 * Check if we can start isoc transfer on the next interval or
1762 * 4 uframes in the future with BIT[15:14] as dep->combo_num
1764 test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1765 test_frame_number |= dep->combo_num << 14;
1766 test_frame_number += max_t(u32, 4, dep->interval);
1768 params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1769 params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1771 cmd = DWC3_DEPCMD_STARTTRANSFER;
1772 cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1773 cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1775 /* Redo if some other failure beside bus-expiry is received */
1776 if (cmd_status && cmd_status != -EAGAIN) {
1777 dep->start_cmd_status = 0;
1782 /* Store the first test status */
1783 if (dep->combo_num == 0)
1784 dep->start_cmd_status = cmd_status;
1789 * End the transfer if the START_TRANSFER command is successful
1790 * to wait for the next XferNotReady to test the command again
1792 if (cmd_status == 0) {
1793 dwc3_stop_active_transfer(dep, true, true);
1798 /* test0 and test1 are both completed at this point */
1799 test0 = (dep->start_cmd_status == 0);
1800 test1 = (cmd_status == 0);
1802 if (!test0 && test1)
1804 else if (!test0 && !test1)
1806 else if (test0 && !test1)
1808 else if (test0 && test1)
1811 dep->frame_number &= DWC3_FRNUMBER_MASK;
1812 dep->frame_number |= dep->combo_num << 14;
1813 dep->frame_number += max_t(u32, 4, dep->interval);
1815 /* Reinitialize test variables */
1816 dep->start_cmd_status = 0;
1819 return __dwc3_gadget_kick_transfer(dep);
1822 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1824 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1825 struct dwc3 *dwc = dep->dwc;
1829 if (list_empty(&dep->pending_list) &&
1830 list_empty(&dep->started_list)) {
1831 dep->flags |= DWC3_EP_PENDING_REQUEST;
1835 if (!dwc->dis_start_transfer_quirk &&
1836 (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1837 DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1838 if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1839 return dwc3_gadget_start_isoc_quirk(dep);
1842 if (desc->bInterval <= 14 &&
1843 dwc->gadget->speed >= USB_SPEED_HIGH) {
1844 u32 frame = __dwc3_gadget_get_frame(dwc);
1845 bool rollover = frame <
1846 (dep->frame_number & DWC3_FRNUMBER_MASK);
1849 * frame_number is set from XferNotReady and may be already
1850 * out of date. DSTS only provides the lower 14 bit of the
1851 * current frame number. So add the upper two bits of
1852 * frame_number and handle a possible rollover.
1853 * This will provide the correct frame_number unless more than
1854 * rollover has happened since XferNotReady.
1857 dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1860 dep->frame_number += BIT(14);
1863 for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1864 int future_interval = i + 1;
1866 /* Give the controller at least 500us to schedule transfers */
1867 if (desc->bInterval < 3)
1868 future_interval += 3 - desc->bInterval;
1870 dep->frame_number = DWC3_ALIGN_FRAME(dep, future_interval);
1872 ret = __dwc3_gadget_kick_transfer(dep);
1878 * After a number of unsuccessful start attempts due to bus-expiry
1879 * status, issue END_TRANSFER command and retry on the next XferNotReady
1883 ret = __dwc3_stop_active_transfer(dep, false, true);
1888 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1890 struct dwc3 *dwc = dep->dwc;
1892 if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1893 dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
1898 if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1899 &req->request, req->dep->name))
1902 if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1903 "%s: request %pK already in flight\n",
1904 dep->name, &req->request))
1907 pm_runtime_get(dwc->dev);
1909 req->request.actual = 0;
1910 req->request.status = -EINPROGRESS;
1912 trace_dwc3_ep_queue(req);
1914 list_add_tail(&req->list, &dep->pending_list);
1915 req->status = DWC3_REQUEST_STATUS_QUEUED;
1917 if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1921 * Start the transfer only after the END_TRANSFER is completed
1922 * and endpoint STALL is cleared.
1924 if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1925 (dep->flags & DWC3_EP_WEDGE) ||
1926 (dep->flags & DWC3_EP_DELAY_STOP) ||
1927 (dep->flags & DWC3_EP_STALL)) {
1928 dep->flags |= DWC3_EP_DELAY_START;
1933 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1934 * wait for a XferNotReady event so we will know what's the current
1935 * (micro-)frame number.
1937 * Without this trick, we are very, very likely gonna get Bus Expiry
1938 * errors which will force us issue EndTransfer command.
1940 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1941 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1942 if ((dep->flags & DWC3_EP_PENDING_REQUEST))
1943 return __dwc3_gadget_start_isoc(dep);
1949 __dwc3_gadget_kick_transfer(dep);
1954 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1957 struct dwc3_request *req = to_dwc3_request(request);
1958 struct dwc3_ep *dep = to_dwc3_ep(ep);
1959 struct dwc3 *dwc = dep->dwc;
1961 unsigned long flags;
1965 spin_lock_irqsave(&dwc->lock, flags);
1966 ret = __dwc3_gadget_ep_queue(dep, req);
1967 spin_unlock_irqrestore(&dwc->lock, flags);
1972 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
1976 /* If req->trb is not set, then the request has not started */
1981 * If request was already started, this means we had to
1982 * stop the transfer. With that we also need to ignore
1983 * all TRBs used by the request, however TRBs can only
1984 * be modified after completion of END_TRANSFER
1985 * command. So what we do here is that we wait for
1986 * END_TRANSFER completion and only after that, we jump
1987 * over TRBs by clearing HWO and incrementing dequeue
1990 for (i = 0; i < req->num_trbs; i++) {
1991 struct dwc3_trb *trb;
1993 trb = &dep->trb_pool[dep->trb_dequeue];
1994 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1995 dwc3_ep_inc_deq(dep);
2001 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
2003 struct dwc3_request *req;
2004 struct dwc3_request *tmp;
2005 struct dwc3 *dwc = dep->dwc;
2007 list_for_each_entry_safe(req, tmp, &dep->cancelled_list, list) {
2008 dwc3_gadget_ep_skip_trbs(dep, req);
2009 switch (req->status) {
2010 case DWC3_REQUEST_STATUS_DISCONNECTED:
2011 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
2013 case DWC3_REQUEST_STATUS_DEQUEUED:
2014 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2016 case DWC3_REQUEST_STATUS_STALLED:
2017 dwc3_gadget_giveback(dep, req, -EPIPE);
2020 dev_err(dwc->dev, "request cancelled with wrong reason:%d\n", req->status);
2021 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2027 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
2028 struct usb_request *request)
2030 struct dwc3_request *req = to_dwc3_request(request);
2031 struct dwc3_request *r = NULL;
2033 struct dwc3_ep *dep = to_dwc3_ep(ep);
2034 struct dwc3 *dwc = dep->dwc;
2036 unsigned long flags;
2039 trace_dwc3_ep_dequeue(req);
2041 spin_lock_irqsave(&dwc->lock, flags);
2043 list_for_each_entry(r, &dep->cancelled_list, list) {
2048 list_for_each_entry(r, &dep->pending_list, list) {
2050 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2055 list_for_each_entry(r, &dep->started_list, list) {
2057 struct dwc3_request *t;
2060 * If a Setup packet is received but yet to DMA out, the controller will
2061 * not process the End Transfer command of any endpoint. Polling of its
2062 * DEPCMD.CmdAct may block setting up TRB for Setup packet, causing a
2063 * timeout. Delay issuing the End Transfer command until the Setup TRB is
2066 if (dwc->ep0state != EP0_SETUP_PHASE && !dwc->delayed_status)
2067 dep->flags |= DWC3_EP_DELAY_STOP;
2069 /* wait until it is processed */
2070 dwc3_stop_active_transfer(dep, true, true);
2073 * Remove any started request if the transfer is
2076 list_for_each_entry_safe(r, t, &dep->started_list, list)
2077 dwc3_gadget_move_cancelled_request(r,
2078 DWC3_REQUEST_STATUS_DEQUEUED);
2080 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2086 dev_err(dwc->dev, "request %pK was not queued to %s\n",
2090 spin_unlock_irqrestore(&dwc->lock, flags);
2095 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
2097 struct dwc3_gadget_ep_cmd_params params;
2098 struct dwc3 *dwc = dep->dwc;
2099 struct dwc3_request *req;
2100 struct dwc3_request *tmp;
2103 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2104 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
2108 memset(¶ms, 0x00, sizeof(params));
2111 struct dwc3_trb *trb;
2113 unsigned int transfer_in_flight;
2114 unsigned int started;
2116 if (dep->number > 1)
2117 trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
2119 trb = &dwc->ep0_trb[dep->trb_enqueue];
2121 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
2122 started = !list_empty(&dep->started_list);
2124 if (!protocol && ((dep->direction && transfer_in_flight) ||
2125 (!dep->direction && started))) {
2129 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
2132 dev_err(dwc->dev, "failed to set STALL on %s\n",
2135 dep->flags |= DWC3_EP_STALL;
2138 * Don't issue CLEAR_STALL command to control endpoints. The
2139 * controller automatically clears the STALL when it receives
2142 if (dep->number <= 1) {
2143 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2147 dwc3_stop_active_transfer(dep, true, true);
2149 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
2150 dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_STALLED);
2152 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING ||
2153 (dep->flags & DWC3_EP_DELAY_STOP)) {
2154 dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
2158 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
2160 ret = dwc3_send_clear_stall_ep_cmd(dep);
2162 dev_err(dwc->dev, "failed to clear STALL on %s\n",
2167 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2169 if ((dep->flags & DWC3_EP_DELAY_START) &&
2170 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
2171 __dwc3_gadget_kick_transfer(dep);
2173 dep->flags &= ~DWC3_EP_DELAY_START;
2179 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
2181 struct dwc3_ep *dep = to_dwc3_ep(ep);
2182 struct dwc3 *dwc = dep->dwc;
2184 unsigned long flags;
2188 spin_lock_irqsave(&dwc->lock, flags);
2189 ret = __dwc3_gadget_ep_set_halt(dep, value, false);
2190 spin_unlock_irqrestore(&dwc->lock, flags);
2195 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
2197 struct dwc3_ep *dep = to_dwc3_ep(ep);
2198 struct dwc3 *dwc = dep->dwc;
2199 unsigned long flags;
2202 spin_lock_irqsave(&dwc->lock, flags);
2203 dep->flags |= DWC3_EP_WEDGE;
2205 if (dep->number == 0 || dep->number == 1)
2206 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
2208 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
2209 spin_unlock_irqrestore(&dwc->lock, flags);
2214 /* -------------------------------------------------------------------------- */
2216 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
2217 .bLength = USB_DT_ENDPOINT_SIZE,
2218 .bDescriptorType = USB_DT_ENDPOINT,
2219 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
2222 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
2223 .enable = dwc3_gadget_ep0_enable,
2224 .disable = dwc3_gadget_ep0_disable,
2225 .alloc_request = dwc3_gadget_ep_alloc_request,
2226 .free_request = dwc3_gadget_ep_free_request,
2227 .queue = dwc3_gadget_ep0_queue,
2228 .dequeue = dwc3_gadget_ep_dequeue,
2229 .set_halt = dwc3_gadget_ep0_set_halt,
2230 .set_wedge = dwc3_gadget_ep_set_wedge,
2233 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
2234 .enable = dwc3_gadget_ep_enable,
2235 .disable = dwc3_gadget_ep_disable,
2236 .alloc_request = dwc3_gadget_ep_alloc_request,
2237 .free_request = dwc3_gadget_ep_free_request,
2238 .queue = dwc3_gadget_ep_queue,
2239 .dequeue = dwc3_gadget_ep_dequeue,
2240 .set_halt = dwc3_gadget_ep_set_halt,
2241 .set_wedge = dwc3_gadget_ep_set_wedge,
2244 /* -------------------------------------------------------------------------- */
2246 static int dwc3_gadget_get_frame(struct usb_gadget *g)
2248 struct dwc3 *dwc = gadget_to_dwc(g);
2250 return __dwc3_gadget_get_frame(dwc);
2253 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
2263 * According to the Databook Remote wakeup request should
2264 * be issued only when the device is in early suspend state.
2266 * We can check that via USB Link State bits in DSTS register.
2268 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2270 link_state = DWC3_DSTS_USBLNKST(reg);
2272 switch (link_state) {
2273 case DWC3_LINK_STATE_RESET:
2274 case DWC3_LINK_STATE_RX_DET: /* in HS, means Early Suspend */
2275 case DWC3_LINK_STATE_U3: /* in HS, means SUSPEND */
2276 case DWC3_LINK_STATE_U2: /* in HS, means Sleep (L1) */
2277 case DWC3_LINK_STATE_U1:
2278 case DWC3_LINK_STATE_RESUME:
2284 ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
2286 dev_err(dwc->dev, "failed to put link in Recovery\n");
2290 /* Recent versions do this automatically */
2291 if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
2292 /* write zeroes to Link Change Request */
2293 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2294 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
2295 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2298 /* poll until Link State changes to ON */
2302 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2304 /* in HS, means ON */
2305 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2309 if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2310 dev_err(dwc->dev, "failed to send remote wakeup\n");
2317 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2319 struct dwc3 *dwc = gadget_to_dwc(g);
2320 unsigned long flags;
2323 spin_lock_irqsave(&dwc->lock, flags);
2324 ret = __dwc3_gadget_wakeup(dwc);
2325 spin_unlock_irqrestore(&dwc->lock, flags);
2330 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2333 struct dwc3 *dwc = gadget_to_dwc(g);
2334 unsigned long flags;
2336 spin_lock_irqsave(&dwc->lock, flags);
2337 g->is_selfpowered = !!is_selfpowered;
2338 spin_unlock_irqrestore(&dwc->lock, flags);
2343 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2347 for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2348 struct dwc3_ep *dep;
2350 dep = dwc->eps[epnum];
2354 dwc3_remove_requests(dwc, dep);
2358 static void __dwc3_gadget_set_ssp_rate(struct dwc3 *dwc)
2360 enum usb_ssp_rate ssp_rate = dwc->gadget_ssp_rate;
2363 if (ssp_rate == USB_SSP_GEN_UNKNOWN)
2364 ssp_rate = dwc->max_ssp_rate;
2366 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2367 reg &= ~DWC3_DCFG_SPEED_MASK;
2368 reg &= ~DWC3_DCFG_NUMLANES(~0);
2370 if (ssp_rate == USB_SSP_GEN_1x2)
2371 reg |= DWC3_DCFG_SUPERSPEED;
2372 else if (dwc->max_ssp_rate != USB_SSP_GEN_1x2)
2373 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2375 if (ssp_rate != USB_SSP_GEN_2x1 &&
2376 dwc->max_ssp_rate != USB_SSP_GEN_2x1)
2377 reg |= DWC3_DCFG_NUMLANES(1);
2379 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2382 static void __dwc3_gadget_set_speed(struct dwc3 *dwc)
2384 enum usb_device_speed speed;
2387 speed = dwc->gadget_max_speed;
2388 if (speed == USB_SPEED_UNKNOWN || speed > dwc->maximum_speed)
2389 speed = dwc->maximum_speed;
2391 if (speed == USB_SPEED_SUPER_PLUS &&
2392 DWC3_IP_IS(DWC32)) {
2393 __dwc3_gadget_set_ssp_rate(dwc);
2397 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2398 reg &= ~(DWC3_DCFG_SPEED_MASK);
2401 * WORKAROUND: DWC3 revision < 2.20a have an issue
2402 * which would cause metastability state on Run/Stop
2403 * bit if we try to force the IP to USB2-only mode.
2405 * Because of that, we cannot configure the IP to any
2406 * speed other than the SuperSpeed
2410 * STAR#9000525659: Clock Domain Crossing on DCTL in
2413 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2414 !dwc->dis_metastability_quirk) {
2415 reg |= DWC3_DCFG_SUPERSPEED;
2418 case USB_SPEED_FULL:
2419 reg |= DWC3_DCFG_FULLSPEED;
2421 case USB_SPEED_HIGH:
2422 reg |= DWC3_DCFG_HIGHSPEED;
2424 case USB_SPEED_SUPER:
2425 reg |= DWC3_DCFG_SUPERSPEED;
2427 case USB_SPEED_SUPER_PLUS:
2428 if (DWC3_IP_IS(DWC3))
2429 reg |= DWC3_DCFG_SUPERSPEED;
2431 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2434 dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2436 if (DWC3_IP_IS(DWC3))
2437 reg |= DWC3_DCFG_SUPERSPEED;
2439 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2443 if (DWC3_IP_IS(DWC32) &&
2444 speed > USB_SPEED_UNKNOWN &&
2445 speed < USB_SPEED_SUPER_PLUS)
2446 reg &= ~DWC3_DCFG_NUMLANES(~0);
2448 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2451 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
2456 if (pm_runtime_suspended(dwc->dev))
2459 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2461 if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2462 reg &= ~DWC3_DCTL_TRGTULST_MASK;
2463 reg |= DWC3_DCTL_TRGTULST_RX_DET;
2466 if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2467 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2468 reg |= DWC3_DCTL_RUN_STOP;
2470 if (dwc->has_hibernation)
2471 reg |= DWC3_DCTL_KEEP_CONNECT;
2473 __dwc3_gadget_set_speed(dwc);
2474 dwc->pullups_connected = true;
2476 reg &= ~DWC3_DCTL_RUN_STOP;
2478 if (dwc->has_hibernation && !suspend)
2479 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2481 dwc->pullups_connected = false;
2484 dwc3_gadget_dctl_write_safe(dwc, reg);
2487 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2488 reg &= DWC3_DSTS_DEVCTRLHLT;
2489 } while (--timeout && !(!is_on ^ !reg));
2497 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2498 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2499 static int __dwc3_gadget_start(struct dwc3 *dwc);
2501 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2503 struct dwc3 *dwc = gadget_to_dwc(g);
2504 unsigned long flags;
2508 dwc->softconnect = is_on;
2510 * Per databook, when we want to stop the gadget, if a control transfer
2511 * is still in process, complete it and get the core into setup phase.
2513 if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
2514 reinit_completion(&dwc->ep0_in_setup);
2516 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2517 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2519 dev_warn(dwc->dev, "timed out waiting for SETUP phase\n");
2523 * Avoid issuing a runtime resume if the device is already in the
2524 * suspended state during gadget disconnect. DWC3 gadget was already
2525 * halted/stopped during runtime suspend.
2528 pm_runtime_barrier(dwc->dev);
2529 if (pm_runtime_suspended(dwc->dev))
2534 * Check the return value for successful resume, or error. For a
2535 * successful resume, the DWC3 runtime PM resume routine will handle
2536 * the run stop sequence, so avoid duplicate operations here.
2538 ret = pm_runtime_get_sync(dwc->dev);
2539 if (!ret || ret < 0) {
2540 pm_runtime_put(dwc->dev);
2545 * Synchronize and disable any further event handling while controller
2546 * is being enabled/disabled.
2548 disable_irq(dwc->irq_gadget);
2550 spin_lock_irqsave(&dwc->lock, flags);
2555 dwc->connected = false;
2557 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2558 * Section 4.1.8 Table 4-7, it states that for a device-initiated
2559 * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2560 * command for any active transfers" before clearing the RunStop
2563 dwc3_stop_active_transfers(dwc);
2564 __dwc3_gadget_stop(dwc);
2567 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
2568 * Section 1.3.4, it mentions that for the DEVCTRLHLT bit, the
2569 * "software needs to acknowledge the events that are generated
2570 * (by writing to GEVNTCOUNTn) while it is waiting for this bit
2571 * to be set to '1'."
2573 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
2574 count &= DWC3_GEVNTCOUNT_MASK;
2576 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
2577 dwc->ev_buf->lpos = (dwc->ev_buf->lpos + count) %
2578 dwc->ev_buf->length;
2582 * In the Synopsys DWC_usb31 1.90a programming guide section
2583 * 4.1.9, it specifies that for a reconnect after a
2584 * device-initiated disconnect requires a core soft reset
2585 * (DCTL.CSftRst) before enabling the run/stop bit.
2587 spin_unlock_irqrestore(&dwc->lock, flags);
2588 dwc3_core_soft_reset(dwc);
2589 spin_lock_irqsave(&dwc->lock, flags);
2591 dwc3_event_buffers_setup(dwc);
2592 __dwc3_gadget_start(dwc);
2595 ret = dwc3_gadget_run_stop(dwc, is_on, false);
2596 spin_unlock_irqrestore(&dwc->lock, flags);
2597 enable_irq(dwc->irq_gadget);
2599 pm_runtime_put(dwc->dev);
2604 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2608 /* Enable all but Start and End of Frame IRQs */
2609 reg = (DWC3_DEVTEN_EVNTOVERFLOWEN |
2610 DWC3_DEVTEN_CMDCMPLTEN |
2611 DWC3_DEVTEN_ERRTICERREN |
2612 DWC3_DEVTEN_WKUPEVTEN |
2613 DWC3_DEVTEN_CONNECTDONEEN |
2614 DWC3_DEVTEN_USBRSTEN |
2615 DWC3_DEVTEN_DISCONNEVTEN);
2617 if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2618 reg |= DWC3_DEVTEN_ULSTCNGEN;
2620 /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2621 if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2622 reg |= DWC3_DEVTEN_U3L2L1SUSPEN;
2624 dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2627 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2629 /* mask all interrupts */
2630 dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2633 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2634 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2637 * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2638 * @dwc: pointer to our context structure
2640 * The following looks like complex but it's actually very simple. In order to
2641 * calculate the number of packets we can burst at once on OUT transfers, we're
2642 * gonna use RxFIFO size.
2644 * To calculate RxFIFO size we need two numbers:
2645 * MDWIDTH = size, in bits, of the internal memory bus
2646 * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2648 * Given these two numbers, the formula is simple:
2650 * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2652 * 24 bytes is for 3x SETUP packets
2653 * 16 bytes is a clock domain crossing tolerance
2655 * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2657 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2664 ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2665 mdwidth = dwc3_mdwidth(dwc);
2667 nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2668 nump = min_t(u32, nump, 16);
2671 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2672 reg &= ~DWC3_DCFG_NUMP_MASK;
2673 reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2674 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2677 static int __dwc3_gadget_start(struct dwc3 *dwc)
2679 struct dwc3_ep *dep;
2684 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2685 * the core supports IMOD, disable it.
2687 if (dwc->imod_interval) {
2688 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2689 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2690 } else if (dwc3_has_imod(dwc)) {
2691 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2695 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2696 * field instead of letting dwc3 itself calculate that automatically.
2698 * This way, we maximize the chances that we'll be able to get several
2699 * bursts of data without going through any sort of endpoint throttling.
2701 reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2702 if (DWC3_IP_IS(DWC3))
2703 reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2705 reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2707 dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2709 dwc3_gadget_setup_nump(dwc);
2712 * Currently the controller handles single stream only. So, Ignore
2713 * Packet Pending bit for stream selection and don't search for another
2714 * stream if the host sends Data Packet with PP=0 (for OUT direction) or
2715 * ACK with NumP=0 and PP=0 (for IN direction). This slightly improves
2716 * the stream performance.
2718 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2719 reg |= DWC3_DCFG_IGNSTRMPP;
2720 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2722 /* Enable MST by default if the device is capable of MST */
2723 if (DWC3_MST_CAPABLE(&dwc->hwparams)) {
2724 reg = dwc3_readl(dwc->regs, DWC3_DCFG1);
2725 reg &= ~DWC3_DCFG1_DIS_MST_ENH;
2726 dwc3_writel(dwc->regs, DWC3_DCFG1, reg);
2729 /* Start with SuperSpeed Default */
2730 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2733 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2735 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2740 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2742 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2746 /* begin to receive SETUP packets */
2747 dwc->ep0state = EP0_SETUP_PHASE;
2748 dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2749 dwc->delayed_status = false;
2750 dwc3_ep0_out_start(dwc);
2752 dwc3_gadget_enable_irq(dwc);
2757 __dwc3_gadget_ep_disable(dwc->eps[0]);
2763 static int dwc3_gadget_start(struct usb_gadget *g,
2764 struct usb_gadget_driver *driver)
2766 struct dwc3 *dwc = gadget_to_dwc(g);
2767 unsigned long flags;
2771 irq = dwc->irq_gadget;
2772 ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2773 IRQF_SHARED, "dwc3", dwc->ev_buf);
2775 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2780 spin_lock_irqsave(&dwc->lock, flags);
2781 dwc->gadget_driver = driver;
2782 spin_unlock_irqrestore(&dwc->lock, flags);
2787 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2789 dwc3_gadget_disable_irq(dwc);
2790 __dwc3_gadget_ep_disable(dwc->eps[0]);
2791 __dwc3_gadget_ep_disable(dwc->eps[1]);
2794 static int dwc3_gadget_stop(struct usb_gadget *g)
2796 struct dwc3 *dwc = gadget_to_dwc(g);
2797 unsigned long flags;
2799 spin_lock_irqsave(&dwc->lock, flags);
2800 dwc->gadget_driver = NULL;
2801 dwc->max_cfg_eps = 0;
2802 spin_unlock_irqrestore(&dwc->lock, flags);
2804 free_irq(dwc->irq_gadget, dwc->ev_buf);
2809 static void dwc3_gadget_config_params(struct usb_gadget *g,
2810 struct usb_dcd_config_params *params)
2812 struct dwc3 *dwc = gadget_to_dwc(g);
2814 params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2815 params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2817 /* Recommended BESL */
2818 if (!dwc->dis_enblslpm_quirk) {
2820 * If the recommended BESL baseline is 0 or if the BESL deep is
2821 * less than 2, Microsoft's Windows 10 host usb stack will issue
2822 * a usb reset immediately after it receives the extended BOS
2823 * descriptor and the enumeration will fail. To maintain
2824 * compatibility with the Windows' usb stack, let's set the
2825 * recommended BESL baseline to 1 and clamp the BESL deep to be
2828 params->besl_baseline = 1;
2829 if (dwc->is_utmi_l1_suspend)
2831 clamp_t(u8, dwc->hird_threshold, 2, 15);
2834 /* U1 Device exit Latency */
2835 if (dwc->dis_u1_entry_quirk)
2836 params->bU1devExitLat = 0;
2838 params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
2840 /* U2 Device exit Latency */
2841 if (dwc->dis_u2_entry_quirk)
2842 params->bU2DevExitLat = 0;
2844 params->bU2DevExitLat =
2845 cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
2848 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2849 enum usb_device_speed speed)
2851 struct dwc3 *dwc = gadget_to_dwc(g);
2852 unsigned long flags;
2854 spin_lock_irqsave(&dwc->lock, flags);
2855 dwc->gadget_max_speed = speed;
2856 spin_unlock_irqrestore(&dwc->lock, flags);
2859 static void dwc3_gadget_set_ssp_rate(struct usb_gadget *g,
2860 enum usb_ssp_rate rate)
2862 struct dwc3 *dwc = gadget_to_dwc(g);
2863 unsigned long flags;
2865 spin_lock_irqsave(&dwc->lock, flags);
2866 dwc->gadget_max_speed = USB_SPEED_SUPER_PLUS;
2867 dwc->gadget_ssp_rate = rate;
2868 spin_unlock_irqrestore(&dwc->lock, flags);
2871 static int dwc3_gadget_vbus_draw(struct usb_gadget *g, unsigned int mA)
2873 struct dwc3 *dwc = gadget_to_dwc(g);
2874 union power_supply_propval val = {0};
2878 return usb_phy_set_power(dwc->usb2_phy, mA);
2883 val.intval = 1000 * mA;
2884 ret = power_supply_set_property(dwc->usb_psy, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
2890 * dwc3_gadget_check_config - ensure dwc3 can support the USB configuration
2891 * @g: pointer to the USB gadget
2893 * Used to record the maximum number of endpoints being used in a USB composite
2894 * device. (across all configurations) This is to be used in the calculation
2895 * of the TXFIFO sizes when resizing internal memory for individual endpoints.
2896 * It will help ensured that the resizing logic reserves enough space for at
2897 * least one max packet.
2899 static int dwc3_gadget_check_config(struct usb_gadget *g)
2901 struct dwc3 *dwc = gadget_to_dwc(g);
2907 if (!dwc->do_fifo_resize)
2910 list_for_each_entry(ep, &g->ep_list, ep_list) {
2911 /* Only interested in the IN endpoints */
2912 if (ep->claimed && (ep->address & USB_DIR_IN))
2916 if (ep_num <= dwc->max_cfg_eps)
2919 /* Update the max number of eps in the composition */
2920 dwc->max_cfg_eps = ep_num;
2922 fifo_size = dwc3_gadget_calc_tx_fifo_size(dwc, dwc->max_cfg_eps);
2923 /* Based on the equation, increment by one for every ep */
2924 fifo_size += dwc->max_cfg_eps;
2926 /* Check if we can fit a single fifo per endpoint */
2927 ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
2928 if (fifo_size > ram1_depth)
2934 static void dwc3_gadget_async_callbacks(struct usb_gadget *g, bool enable)
2936 struct dwc3 *dwc = gadget_to_dwc(g);
2937 unsigned long flags;
2939 spin_lock_irqsave(&dwc->lock, flags);
2940 dwc->async_callbacks = enable;
2941 spin_unlock_irqrestore(&dwc->lock, flags);
2944 static const struct usb_gadget_ops dwc3_gadget_ops = {
2945 .get_frame = dwc3_gadget_get_frame,
2946 .wakeup = dwc3_gadget_wakeup,
2947 .set_selfpowered = dwc3_gadget_set_selfpowered,
2948 .pullup = dwc3_gadget_pullup,
2949 .udc_start = dwc3_gadget_start,
2950 .udc_stop = dwc3_gadget_stop,
2951 .udc_set_speed = dwc3_gadget_set_speed,
2952 .udc_set_ssp_rate = dwc3_gadget_set_ssp_rate,
2953 .get_config_params = dwc3_gadget_config_params,
2954 .vbus_draw = dwc3_gadget_vbus_draw,
2955 .check_config = dwc3_gadget_check_config,
2956 .udc_async_callbacks = dwc3_gadget_async_callbacks,
2959 /* -------------------------------------------------------------------------- */
2961 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2963 struct dwc3 *dwc = dep->dwc;
2965 usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2966 dep->endpoint.maxburst = 1;
2967 dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2968 if (!dep->direction)
2969 dwc->gadget->ep0 = &dep->endpoint;
2971 dep->endpoint.caps.type_control = true;
2976 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2978 struct dwc3 *dwc = dep->dwc;
2982 mdwidth = dwc3_mdwidth(dwc);
2984 /* MDWIDTH is represented in bits, we need it in bytes */
2987 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2988 if (DWC3_IP_IS(DWC3))
2989 size = DWC3_GTXFIFOSIZ_TXFDEP(size);
2991 size = DWC31_GTXFIFOSIZ_TXFDEP(size);
2993 /* FIFO Depth is in MDWDITH bytes. Multiply */
2997 * To meet performance requirement, a minimum TxFIFO size of 3x
2998 * MaxPacketSize is recommended for endpoints that support burst and a
2999 * minimum TxFIFO size of 2x MaxPacketSize for endpoints that don't
3000 * support burst. Use those numbers and we can calculate the max packet
3003 if (dwc->maximum_speed >= USB_SPEED_SUPER)
3008 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3010 dep->endpoint.max_streams = 16;
3011 dep->endpoint.ops = &dwc3_gadget_ep_ops;
3012 list_add_tail(&dep->endpoint.ep_list,
3013 &dwc->gadget->ep_list);
3014 dep->endpoint.caps.type_iso = true;
3015 dep->endpoint.caps.type_bulk = true;
3016 dep->endpoint.caps.type_int = true;
3018 return dwc3_alloc_trb_pool(dep);
3021 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
3023 struct dwc3 *dwc = dep->dwc;
3027 mdwidth = dwc3_mdwidth(dwc);
3029 /* MDWIDTH is represented in bits, convert to bytes */
3032 /* All OUT endpoints share a single RxFIFO space */
3033 size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
3034 if (DWC3_IP_IS(DWC3))
3035 size = DWC3_GRXFIFOSIZ_RXFDEP(size);
3037 size = DWC31_GRXFIFOSIZ_RXFDEP(size);
3039 /* FIFO depth is in MDWDITH bytes */
3043 * To meet performance requirement, a minimum recommended RxFIFO size
3044 * is defined as follow:
3045 * RxFIFO size >= (3 x MaxPacketSize) +
3046 * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
3048 * Then calculate the max packet limit as below.
3050 size -= (3 * 8) + 16;
3056 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3057 dep->endpoint.max_streams = 16;
3058 dep->endpoint.ops = &dwc3_gadget_ep_ops;
3059 list_add_tail(&dep->endpoint.ep_list,
3060 &dwc->gadget->ep_list);
3061 dep->endpoint.caps.type_iso = true;
3062 dep->endpoint.caps.type_bulk = true;
3063 dep->endpoint.caps.type_int = true;
3065 return dwc3_alloc_trb_pool(dep);
3068 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
3070 struct dwc3_ep *dep;
3071 bool direction = epnum & 1;
3073 u8 num = epnum >> 1;
3075 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
3080 dep->number = epnum;
3081 dep->direction = direction;
3082 dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
3083 dwc->eps[epnum] = dep;
3085 dep->start_cmd_status = 0;
3087 snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
3088 direction ? "in" : "out");
3090 dep->endpoint.name = dep->name;
3092 if (!(dep->number > 1)) {
3093 dep->endpoint.desc = &dwc3_gadget_ep0_desc;
3094 dep->endpoint.comp_desc = NULL;
3098 ret = dwc3_gadget_init_control_endpoint(dep);
3100 ret = dwc3_gadget_init_in_endpoint(dep);
3102 ret = dwc3_gadget_init_out_endpoint(dep);
3107 dep->endpoint.caps.dir_in = direction;
3108 dep->endpoint.caps.dir_out = !direction;
3110 INIT_LIST_HEAD(&dep->pending_list);
3111 INIT_LIST_HEAD(&dep->started_list);
3112 INIT_LIST_HEAD(&dep->cancelled_list);
3114 dwc3_debugfs_create_endpoint_dir(dep);
3119 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
3123 INIT_LIST_HEAD(&dwc->gadget->ep_list);
3125 for (epnum = 0; epnum < total; epnum++) {
3128 ret = dwc3_gadget_init_endpoint(dwc, epnum);
3136 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
3138 struct dwc3_ep *dep;
3141 for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3142 dep = dwc->eps[epnum];
3146 * Physical endpoints 0 and 1 are special; they form the
3147 * bi-directional USB endpoint 0.
3149 * For those two physical endpoints, we don't allocate a TRB
3150 * pool nor do we add them the endpoints list. Due to that, we
3151 * shouldn't do these two operations otherwise we would end up
3152 * with all sorts of bugs when removing dwc3.ko.
3154 if (epnum != 0 && epnum != 1) {
3155 dwc3_free_trb_pool(dep);
3156 list_del(&dep->endpoint.ep_list);
3159 debugfs_remove_recursive(debugfs_lookup(dep->name,
3160 debugfs_lookup(dev_name(dep->dwc->dev),
3166 /* -------------------------------------------------------------------------- */
3168 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
3169 struct dwc3_request *req, struct dwc3_trb *trb,
3170 const struct dwc3_event_depevt *event, int status, int chain)
3174 dwc3_ep_inc_deq(dep);
3176 trace_dwc3_complete_trb(dep, trb);
3180 * If we're in the middle of series of chained TRBs and we
3181 * receive a short transfer along the way, DWC3 will skip
3182 * through all TRBs including the last TRB in the chain (the
3183 * where CHN bit is zero. DWC3 will also avoid clearing HWO
3184 * bit and SW has to do it manually.
3186 * We're going to do that here to avoid problems of HW trying
3187 * to use bogus TRBs for transfers.
3189 if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
3190 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3193 * For isochronous transfers, the first TRB in a service interval must
3194 * have the Isoc-First type. Track and report its interval frame number.
3196 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3197 (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
3198 unsigned int frame_number;
3200 frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
3201 frame_number &= ~(dep->interval - 1);
3202 req->request.frame_number = frame_number;
3206 * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
3207 * this TRB points to the bounce buffer address, it's a MPS alignment
3208 * TRB. Don't add it to req->remaining calculation.
3210 if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
3211 trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
3212 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3216 count = trb->size & DWC3_TRB_SIZE_MASK;
3217 req->remaining += count;
3219 if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
3222 if (event->status & DEPEVT_STATUS_SHORT && !chain)
3225 if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
3226 (trb->ctrl & DWC3_TRB_CTRL_LST))
3232 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
3233 struct dwc3_request *req, const struct dwc3_event_depevt *event,
3236 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3237 struct scatterlist *sg = req->sg;
3238 struct scatterlist *s;
3239 unsigned int num_queued = req->num_queued_sgs;
3243 for_each_sg(sg, s, num_queued, i) {
3244 trb = &dep->trb_pool[dep->trb_dequeue];
3246 req->sg = sg_next(s);
3247 req->num_queued_sgs--;
3249 ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
3250 trb, event, status, true);
3258 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
3259 struct dwc3_request *req, const struct dwc3_event_depevt *event,
3262 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3264 return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
3265 event, status, false);
3268 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
3270 return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
3273 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
3274 const struct dwc3_event_depevt *event,
3275 struct dwc3_request *req, int status)
3279 if (req->request.num_mapped_sgs)
3280 ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
3283 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3286 req->request.actual = req->request.length - req->remaining;
3288 if (!dwc3_gadget_ep_request_completed(req))
3291 if (req->needs_extra_trb) {
3292 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3294 req->needs_extra_trb = false;
3297 dwc3_gadget_giveback(dep, req, status);
3303 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
3304 const struct dwc3_event_depevt *event, int status)
3306 struct dwc3_request *req;
3307 struct dwc3_request *tmp;
3309 list_for_each_entry_safe(req, tmp, &dep->started_list, list) {
3312 ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
3319 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
3321 struct dwc3_request *req;
3322 struct dwc3 *dwc = dep->dwc;
3324 if (!dep->endpoint.desc || !dwc->pullups_connected ||
3328 if (!list_empty(&dep->pending_list))
3332 * We only need to check the first entry of the started list. We can
3333 * assume the completed requests are removed from the started list.
3335 req = next_request(&dep->started_list);
3339 return !dwc3_gadget_ep_request_completed(req);
3342 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
3343 const struct dwc3_event_depevt *event)
3345 dep->frame_number = event->parameters;
3348 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
3349 const struct dwc3_event_depevt *event, int status)
3351 struct dwc3 *dwc = dep->dwc;
3352 bool no_started_trb = true;
3354 if (!dep->endpoint.desc)
3355 return no_started_trb;
3357 dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
3359 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3362 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3363 list_empty(&dep->started_list) &&
3364 (list_empty(&dep->pending_list) || status == -EXDEV))
3365 dwc3_stop_active_transfer(dep, true, true);
3366 else if (dwc3_gadget_ep_should_continue(dep))
3367 if (__dwc3_gadget_kick_transfer(dep) == 0)
3368 no_started_trb = false;
3372 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
3373 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
3375 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3379 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
3382 if (!(dep->flags & DWC3_EP_ENABLED))
3385 if (!list_empty(&dep->started_list))
3386 return no_started_trb;
3389 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3391 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
3396 return no_started_trb;
3399 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
3400 const struct dwc3_event_depevt *event)
3404 if (!dep->endpoint.desc)
3407 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
3408 dwc3_gadget_endpoint_frame_from_event(dep, event);
3410 if (event->status & DEPEVT_STATUS_BUSERR)
3411 status = -ECONNRESET;
3413 if (event->status & DEPEVT_STATUS_MISSED_ISOC)
3416 dwc3_gadget_endpoint_trbs_complete(dep, event, status);
3419 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
3420 const struct dwc3_event_depevt *event)
3424 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3426 if (event->status & DEPEVT_STATUS_BUSERR)
3427 status = -ECONNRESET;
3429 if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
3430 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
3433 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
3434 const struct dwc3_event_depevt *event)
3436 dwc3_gadget_endpoint_frame_from_event(dep, event);
3439 * The XferNotReady event is generated only once before the endpoint
3440 * starts. It will be generated again when END_TRANSFER command is
3441 * issued. For some controller versions, the XferNotReady event may be
3442 * generated while the END_TRANSFER command is still in process. Ignore
3443 * it and wait for the next XferNotReady event after the command is
3446 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3449 (void) __dwc3_gadget_start_isoc(dep);
3452 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
3453 const struct dwc3_event_depevt *event)
3455 u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
3457 if (cmd != DWC3_DEPCMD_ENDTRANSFER)
3461 * The END_TRANSFER command will cause the controller to generate a
3462 * NoStream Event, and it's not due to the host DP NoStream rejection.
3463 * Ignore the next NoStream event.
3465 if (dep->stream_capable)
3466 dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3468 dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
3469 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3470 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3472 if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3473 struct dwc3 *dwc = dep->dwc;
3475 dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3476 if (dwc3_send_clear_stall_ep_cmd(dep)) {
3477 struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3479 dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3480 if (dwc->delayed_status)
3481 __dwc3_gadget_ep0_set_halt(ep0, 1);
3485 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3486 if (dwc->delayed_status)
3487 dwc3_ep0_send_delayed_status(dwc);
3490 if ((dep->flags & DWC3_EP_DELAY_START) &&
3491 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3492 __dwc3_gadget_kick_transfer(dep);
3494 dep->flags &= ~DWC3_EP_DELAY_START;
3497 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3498 const struct dwc3_event_depevt *event)
3500 struct dwc3 *dwc = dep->dwc;
3502 if (event->status == DEPEVT_STREAMEVT_FOUND) {
3503 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3507 /* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3508 switch (event->parameters) {
3509 case DEPEVT_STREAM_PRIME:
3511 * If the host can properly transition the endpoint state from
3512 * idle to prime after a NoStream rejection, there's no need to
3513 * force restarting the endpoint to reinitiate the stream. To
3514 * simplify the check, assume the host follows the USB spec if
3515 * it primed the endpoint more than once.
3517 if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3518 if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3519 dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3521 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3525 case DEPEVT_STREAM_NOSTREAM:
3526 if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3527 !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3528 (!DWC3_MST_CAPABLE(&dwc->hwparams) &&
3529 !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)))
3533 * If the host rejects a stream due to no active stream, by the
3534 * USB and xHCI spec, the endpoint will be put back to idle
3535 * state. When the host is ready (buffer added/updated), it will
3536 * prime the endpoint to inform the usb device controller. This
3537 * triggers the device controller to issue ERDY to restart the
3538 * stream. However, some hosts don't follow this and keep the
3539 * endpoint in the idle state. No prime will come despite host
3540 * streams are updated, and the device controller will not be
3541 * triggered to generate ERDY to move the next stream data. To
3542 * workaround this and maintain compatibility with various
3543 * hosts, force to reinitate the stream until the host is ready
3544 * instead of waiting for the host to prime the endpoint.
3546 if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3547 unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3549 dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3551 dep->flags |= DWC3_EP_DELAY_START;
3552 dwc3_stop_active_transfer(dep, true, true);
3559 dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3562 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3563 const struct dwc3_event_depevt *event)
3565 struct dwc3_ep *dep;
3566 u8 epnum = event->endpoint_number;
3568 dep = dwc->eps[epnum];
3570 if (!(dep->flags & DWC3_EP_ENABLED)) {
3571 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
3574 /* Handle only EPCMDCMPLT when EP disabled */
3575 if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
3579 if (epnum == 0 || epnum == 1) {
3580 dwc3_ep0_interrupt(dwc, event);
3584 switch (event->endpoint_event) {
3585 case DWC3_DEPEVT_XFERINPROGRESS:
3586 dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3588 case DWC3_DEPEVT_XFERNOTREADY:
3589 dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3591 case DWC3_DEPEVT_EPCMDCMPLT:
3592 dwc3_gadget_endpoint_command_complete(dep, event);
3594 case DWC3_DEPEVT_XFERCOMPLETE:
3595 dwc3_gadget_endpoint_transfer_complete(dep, event);
3597 case DWC3_DEPEVT_STREAMEVT:
3598 dwc3_gadget_endpoint_stream_event(dep, event);
3600 case DWC3_DEPEVT_RXTXFIFOEVT:
3605 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3607 if (dwc->async_callbacks && dwc->gadget_driver->disconnect) {
3608 spin_unlock(&dwc->lock);
3609 dwc->gadget_driver->disconnect(dwc->gadget);
3610 spin_lock(&dwc->lock);
3614 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3616 if (dwc->async_callbacks && dwc->gadget_driver->suspend) {
3617 spin_unlock(&dwc->lock);
3618 dwc->gadget_driver->suspend(dwc->gadget);
3619 spin_lock(&dwc->lock);
3623 static void dwc3_resume_gadget(struct dwc3 *dwc)
3625 if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3626 spin_unlock(&dwc->lock);
3627 dwc->gadget_driver->resume(dwc->gadget);
3628 spin_lock(&dwc->lock);
3632 static void dwc3_reset_gadget(struct dwc3 *dwc)
3634 if (!dwc->gadget_driver)
3637 if (dwc->async_callbacks && dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3638 spin_unlock(&dwc->lock);
3639 usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3640 spin_lock(&dwc->lock);
3644 void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3647 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3648 (dep->flags & DWC3_EP_DELAY_STOP) ||
3649 (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3653 * NOTICE: We are violating what the Databook says about the
3654 * EndTransfer command. Ideally we would _always_ wait for the
3655 * EndTransfer Command Completion IRQ, but that's causing too
3656 * much trouble synchronizing between us and gadget driver.
3658 * We have discussed this with the IP Provider and it was
3659 * suggested to giveback all requests here.
3661 * Note also that a similar handling was tested by Synopsys
3662 * (thanks a lot Paul) and nothing bad has come out of it.
3663 * In short, what we're doing is issuing EndTransfer with
3664 * CMDIOC bit set and delay kicking transfer until the
3665 * EndTransfer command had completed.
3667 * As of IP version 3.10a of the DWC_usb3 IP, the controller
3668 * supports a mode to work around the above limitation. The
3669 * software can poll the CMDACT bit in the DEPCMD register
3670 * after issuing a EndTransfer command. This mode is enabled
3671 * by writing GUCTL2[14]. This polling is already done in the
3672 * dwc3_send_gadget_ep_cmd() function so if the mode is
3673 * enabled, the EndTransfer command will have completed upon
3674 * returning from this function.
3676 * This mode is NOT available on the DWC_usb31 IP.
3679 __dwc3_stop_active_transfer(dep, force, interrupt);
3682 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3686 for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3687 struct dwc3_ep *dep;
3690 dep = dwc->eps[epnum];
3694 if (!(dep->flags & DWC3_EP_STALL))
3697 dep->flags &= ~DWC3_EP_STALL;
3699 ret = dwc3_send_clear_stall_ep_cmd(dep);
3704 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3708 dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3710 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3711 reg &= ~DWC3_DCTL_INITU1ENA;
3712 reg &= ~DWC3_DCTL_INITU2ENA;
3713 dwc3_gadget_dctl_write_safe(dwc, reg);
3715 dwc3_disconnect_gadget(dwc);
3717 dwc->gadget->speed = USB_SPEED_UNKNOWN;
3718 dwc->setup_packet_pending = false;
3719 usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3721 dwc->connected = false;
3724 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
3729 * Ideally, dwc3_reset_gadget() would trigger the function
3730 * drivers to stop any active transfers through ep disable.
3731 * However, for functions which defer ep disable, such as mass
3732 * storage, we will need to rely on the call to stop active
3733 * transfers here, and avoid allowing of request queuing.
3735 dwc->connected = false;
3738 * WORKAROUND: DWC3 revisions <1.88a have an issue which
3739 * would cause a missing Disconnect Event if there's a
3740 * pending Setup Packet in the FIFO.
3742 * There's no suggested workaround on the official Bug
3743 * report, which states that "unless the driver/application
3744 * is doing any special handling of a disconnect event,
3745 * there is no functional issue".
3747 * Unfortunately, it turns out that we _do_ some special
3748 * handling of a disconnect event, namely complete all
3749 * pending transfers, notify gadget driver of the
3750 * disconnection, and so on.
3752 * Our suggested workaround is to follow the Disconnect
3753 * Event steps here, instead, based on a setup_packet_pending
3754 * flag. Such flag gets set whenever we have a SETUP_PENDING
3755 * status for EP0 TRBs and gets cleared on XferComplete for the
3760 * STAR#9000466709: RTL: Device : Disconnect event not
3761 * generated if setup packet pending in FIFO
3763 if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
3764 if (dwc->setup_packet_pending)
3765 dwc3_gadget_disconnect_interrupt(dwc);
3768 dwc3_reset_gadget(dwc);
3770 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
3771 * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
3772 * needs to ensure that it sends "a DEPENDXFER command for any active
3775 dwc3_stop_active_transfers(dwc);
3776 dwc->connected = true;
3778 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3779 reg &= ~DWC3_DCTL_TSTCTRL_MASK;
3780 dwc3_gadget_dctl_write_safe(dwc, reg);
3781 dwc->test_mode = false;
3782 dwc3_clear_stall_all_ep(dwc);
3784 /* Reset device address to zero */
3785 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3786 reg &= ~(DWC3_DCFG_DEVADDR_MASK);
3787 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3790 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
3792 struct dwc3_ep *dep;
3798 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
3799 speed = reg & DWC3_DSTS_CONNECTSPD;
3802 if (DWC3_IP_IS(DWC32))
3803 lanes = DWC3_DSTS_CONNLANES(reg) + 1;
3805 dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
3808 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
3809 * each time on Connect Done.
3811 * Currently we always use the reset value. If any platform
3812 * wants to set this to a different value, we need to add a
3813 * setting and update GCTL.RAMCLKSEL here.
3817 case DWC3_DSTS_SUPERSPEED_PLUS:
3818 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3819 dwc->gadget->ep0->maxpacket = 512;
3820 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3823 dwc->gadget->ssp_rate = USB_SSP_GEN_2x2;
3825 dwc->gadget->ssp_rate = USB_SSP_GEN_2x1;
3827 case DWC3_DSTS_SUPERSPEED:
3829 * WORKAROUND: DWC3 revisions <1.90a have an issue which
3830 * would cause a missing USB3 Reset event.
3832 * In such situations, we should force a USB3 Reset
3833 * event by calling our dwc3_gadget_reset_interrupt()
3838 * STAR#9000483510: RTL: SS : USB3 reset event may
3839 * not be generated always when the link enters poll
3841 if (DWC3_VER_IS_PRIOR(DWC3, 190A))
3842 dwc3_gadget_reset_interrupt(dwc);
3844 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3845 dwc->gadget->ep0->maxpacket = 512;
3846 dwc->gadget->speed = USB_SPEED_SUPER;
3849 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3850 dwc->gadget->ssp_rate = USB_SSP_GEN_1x2;
3853 case DWC3_DSTS_HIGHSPEED:
3854 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3855 dwc->gadget->ep0->maxpacket = 64;
3856 dwc->gadget->speed = USB_SPEED_HIGH;
3858 case DWC3_DSTS_FULLSPEED:
3859 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3860 dwc->gadget->ep0->maxpacket = 64;
3861 dwc->gadget->speed = USB_SPEED_FULL;
3865 dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
3867 /* Enable USB2 LPM Capability */
3869 if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
3870 !dwc->usb2_gadget_lpm_disable &&
3871 (speed != DWC3_DSTS_SUPERSPEED) &&
3872 (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
3873 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3874 reg |= DWC3_DCFG_LPM_CAP;
3875 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3877 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3878 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
3880 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
3881 (dwc->is_utmi_l1_suspend << 4));
3884 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
3885 * DCFG.LPMCap is set, core responses with an ACK and the
3886 * BESL value in the LPM token is less than or equal to LPM
3889 WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
3890 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
3892 if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
3893 reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
3895 dwc3_gadget_dctl_write_safe(dwc, reg);
3897 if (dwc->usb2_gadget_lpm_disable) {
3898 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3899 reg &= ~DWC3_DCFG_LPM_CAP;
3900 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3903 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3904 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
3905 dwc3_gadget_dctl_write_safe(dwc, reg);
3909 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3911 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3916 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3918 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3923 * Configure PHY via GUSB3PIPECTLn if required.
3925 * Update GTXFIFOSIZn
3927 * In both cases reset values should be sufficient.
3931 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
3934 * TODO take core out of low power mode when that's
3938 if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3939 spin_unlock(&dwc->lock);
3940 dwc->gadget_driver->resume(dwc->gadget);
3941 spin_lock(&dwc->lock);
3945 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
3946 unsigned int evtinfo)
3948 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3949 unsigned int pwropt;
3952 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
3953 * Hibernation mode enabled which would show up when device detects
3954 * host-initiated U3 exit.
3956 * In that case, device will generate a Link State Change Interrupt
3957 * from U3 to RESUME which is only necessary if Hibernation is
3960 * There are no functional changes due to such spurious event and we
3961 * just need to ignore it.
3965 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
3968 pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
3969 if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
3970 (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
3971 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
3972 (next == DWC3_LINK_STATE_RESUME)) {
3978 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
3979 * on the link partner, the USB session might do multiple entry/exit
3980 * of low power states before a transfer takes place.
3982 * Due to this problem, we might experience lower throughput. The
3983 * suggested workaround is to disable DCTL[12:9] bits if we're
3984 * transitioning from U1/U2 to U0 and enable those bits again
3985 * after a transfer completes and there are no pending transfers
3986 * on any of the enabled endpoints.
3988 * This is the first half of that workaround.
3992 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
3993 * core send LGO_Ux entering U0
3995 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3996 if (next == DWC3_LINK_STATE_U0) {
4000 switch (dwc->link_state) {
4001 case DWC3_LINK_STATE_U1:
4002 case DWC3_LINK_STATE_U2:
4003 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4004 u1u2 = reg & (DWC3_DCTL_INITU2ENA
4005 | DWC3_DCTL_ACCEPTU2ENA
4006 | DWC3_DCTL_INITU1ENA
4007 | DWC3_DCTL_ACCEPTU1ENA);
4010 dwc->u1u2 = reg & u1u2;
4014 dwc3_gadget_dctl_write_safe(dwc, reg);
4024 case DWC3_LINK_STATE_U1:
4025 if (dwc->speed == USB_SPEED_SUPER)
4026 dwc3_suspend_gadget(dwc);
4028 case DWC3_LINK_STATE_U2:
4029 case DWC3_LINK_STATE_U3:
4030 dwc3_suspend_gadget(dwc);
4032 case DWC3_LINK_STATE_RESUME:
4033 dwc3_resume_gadget(dwc);
4040 dwc->link_state = next;
4043 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
4044 unsigned int evtinfo)
4046 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
4048 if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
4049 dwc3_suspend_gadget(dwc);
4051 dwc->link_state = next;
4054 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
4055 unsigned int evtinfo)
4057 unsigned int is_ss = evtinfo & BIT(4);
4060 * WORKAROUND: DWC3 revison 2.20a with hibernation support
4061 * have a known issue which can cause USB CV TD.9.23 to fail
4064 * Because of this issue, core could generate bogus hibernation
4065 * events which SW needs to ignore.
4069 * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
4070 * Device Fallback from SuperSpeed
4072 if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
4075 /* enter hibernation here */
4078 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
4079 const struct dwc3_event_devt *event)
4081 switch (event->type) {
4082 case DWC3_DEVICE_EVENT_DISCONNECT:
4083 dwc3_gadget_disconnect_interrupt(dwc);
4085 case DWC3_DEVICE_EVENT_RESET:
4086 dwc3_gadget_reset_interrupt(dwc);
4088 case DWC3_DEVICE_EVENT_CONNECT_DONE:
4089 dwc3_gadget_conndone_interrupt(dwc);
4091 case DWC3_DEVICE_EVENT_WAKEUP:
4092 dwc3_gadget_wakeup_interrupt(dwc);
4094 case DWC3_DEVICE_EVENT_HIBER_REQ:
4095 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
4096 "unexpected hibernation event\n"))
4099 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
4101 case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
4102 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
4104 case DWC3_DEVICE_EVENT_SUSPEND:
4105 /* It changed to be suspend event for version 2.30a and above */
4106 if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) {
4108 * Ignore suspend event until the gadget enters into
4109 * USB_STATE_CONFIGURED state.
4111 if (dwc->gadget->state >= USB_STATE_CONFIGURED)
4112 dwc3_gadget_suspend_interrupt(dwc,
4116 case DWC3_DEVICE_EVENT_SOF:
4117 case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
4118 case DWC3_DEVICE_EVENT_CMD_CMPL:
4119 case DWC3_DEVICE_EVENT_OVERFLOW:
4122 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
4126 static void dwc3_process_event_entry(struct dwc3 *dwc,
4127 const union dwc3_event *event)
4129 trace_dwc3_event(event->raw, dwc);
4131 if (!event->type.is_devspec)
4132 dwc3_endpoint_interrupt(dwc, &event->depevt);
4133 else if (event->type.type == DWC3_EVENT_TYPE_DEV)
4134 dwc3_gadget_interrupt(dwc, &event->devt);
4136 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
4139 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
4141 struct dwc3 *dwc = evt->dwc;
4142 irqreturn_t ret = IRQ_NONE;
4147 if (!(evt->flags & DWC3_EVENT_PENDING))
4151 union dwc3_event event;
4153 event.raw = *(u32 *) (evt->cache + evt->lpos);
4155 dwc3_process_event_entry(dwc, &event);
4158 * FIXME we wrap around correctly to the next entry as
4159 * almost all entries are 4 bytes in size. There is one
4160 * entry which has 12 bytes which is a regular entry
4161 * followed by 8 bytes data. ATM I don't know how
4162 * things are organized if we get next to the a
4163 * boundary so I worry about that once we try to handle
4166 evt->lpos = (evt->lpos + 4) % evt->length;
4171 evt->flags &= ~DWC3_EVENT_PENDING;
4174 /* Unmask interrupt */
4175 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4176 DWC3_GEVNTSIZ_SIZE(evt->length));
4178 if (dwc->imod_interval) {
4179 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
4180 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
4186 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
4188 struct dwc3_event_buffer *evt = _evt;
4189 struct dwc3 *dwc = evt->dwc;
4190 unsigned long flags;
4191 irqreturn_t ret = IRQ_NONE;
4194 spin_lock_irqsave(&dwc->lock, flags);
4195 ret = dwc3_process_event_buf(evt);
4196 spin_unlock_irqrestore(&dwc->lock, flags);
4202 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
4204 struct dwc3 *dwc = evt->dwc;
4208 if (pm_runtime_suspended(dwc->dev)) {
4209 pm_runtime_get(dwc->dev);
4210 disable_irq_nosync(dwc->irq_gadget);
4211 dwc->pending_events = true;
4216 * With PCIe legacy interrupt, test shows that top-half irq handler can
4217 * be called again after HW interrupt deassertion. Check if bottom-half
4218 * irq event handler completes before caching new event to prevent
4221 if (evt->flags & DWC3_EVENT_PENDING)
4224 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
4225 count &= DWC3_GEVNTCOUNT_MASK;
4230 evt->flags |= DWC3_EVENT_PENDING;
4232 /* Mask interrupt */
4233 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4234 DWC3_GEVNTSIZ_INTMASK | DWC3_GEVNTSIZ_SIZE(evt->length));
4236 amount = min(count, evt->length - evt->lpos);
4237 memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
4240 memcpy(evt->cache, evt->buf, count - amount);
4242 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
4244 return IRQ_WAKE_THREAD;
4247 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
4249 struct dwc3_event_buffer *evt = _evt;
4251 return dwc3_check_event_buf(evt);
4254 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
4256 struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
4259 irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
4263 if (irq == -EPROBE_DEFER)
4266 irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
4270 if (irq == -EPROBE_DEFER)
4273 irq = platform_get_irq(dwc3_pdev, 0);
4284 static void dwc_gadget_release(struct device *dev)
4286 struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
4292 * dwc3_gadget_init - initializes gadget related registers
4293 * @dwc: pointer to our controller context structure
4295 * Returns 0 on success otherwise negative errno.
4297 int dwc3_gadget_init(struct dwc3 *dwc)
4303 irq = dwc3_gadget_get_irq(dwc);
4309 dwc->irq_gadget = irq;
4311 dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
4312 sizeof(*dwc->ep0_trb) * 2,
4313 &dwc->ep0_trb_addr, GFP_KERNEL);
4314 if (!dwc->ep0_trb) {
4315 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
4320 dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
4321 if (!dwc->setup_buf) {
4326 dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
4327 &dwc->bounce_addr, GFP_KERNEL);
4333 init_completion(&dwc->ep0_in_setup);
4334 dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
4341 usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
4342 dev = &dwc->gadget->dev;
4343 dev->platform_data = dwc;
4344 dwc->gadget->ops = &dwc3_gadget_ops;
4345 dwc->gadget->speed = USB_SPEED_UNKNOWN;
4346 dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
4347 dwc->gadget->sg_supported = true;
4348 dwc->gadget->name = "dwc3-gadget";
4349 dwc->gadget->lpm_capable = !dwc->usb2_gadget_lpm_disable;
4352 * FIXME We might be setting max_speed to <SUPER, however versions
4353 * <2.20a of dwc3 have an issue with metastability (documented
4354 * elsewhere in this driver) which tells us we can't set max speed to
4355 * anything lower than SUPER.
4357 * Because gadget.max_speed is only used by composite.c and function
4358 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
4359 * to happen so we avoid sending SuperSpeed Capability descriptor
4360 * together with our BOS descriptor as that could confuse host into
4361 * thinking we can handle super speed.
4363 * Note that, in fact, we won't even support GetBOS requests when speed
4364 * is less than super speed because we don't have means, yet, to tell
4365 * composite.c that we are USB 2.0 + LPM ECN.
4367 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
4368 !dwc->dis_metastability_quirk)
4369 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
4372 dwc->gadget->max_speed = dwc->maximum_speed;
4373 dwc->gadget->max_ssp_rate = dwc->max_ssp_rate;
4376 * REVISIT: Here we should clear all pending IRQs to be
4377 * sure we're starting from a well known location.
4380 ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
4384 ret = usb_add_gadget(dwc->gadget);
4386 dev_err(dwc->dev, "failed to add gadget\n");
4390 if (DWC3_IP_IS(DWC32) && dwc->maximum_speed == USB_SPEED_SUPER_PLUS)
4391 dwc3_gadget_set_ssp_rate(dwc->gadget, dwc->max_ssp_rate);
4393 dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
4398 dwc3_gadget_free_endpoints(dwc);
4400 usb_put_gadget(dwc->gadget);
4403 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4407 kfree(dwc->setup_buf);
4410 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4411 dwc->ep0_trb, dwc->ep0_trb_addr);
4417 /* -------------------------------------------------------------------------- */
4419 void dwc3_gadget_exit(struct dwc3 *dwc)
4424 usb_del_gadget(dwc->gadget);
4425 dwc3_gadget_free_endpoints(dwc);
4426 usb_put_gadget(dwc->gadget);
4427 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4429 kfree(dwc->setup_buf);
4430 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4431 dwc->ep0_trb, dwc->ep0_trb_addr);
4434 int dwc3_gadget_suspend(struct dwc3 *dwc)
4436 if (!dwc->gadget_driver)
4439 dwc3_gadget_run_stop(dwc, false, false);
4440 dwc3_disconnect_gadget(dwc);
4441 __dwc3_gadget_stop(dwc);
4446 int dwc3_gadget_resume(struct dwc3 *dwc)
4450 if (!dwc->gadget_driver || !dwc->softconnect)
4453 ret = __dwc3_gadget_start(dwc);
4457 ret = dwc3_gadget_run_stop(dwc, true, false);
4464 __dwc3_gadget_stop(dwc);
4470 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4472 if (dwc->pending_events) {
4473 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4474 dwc->pending_events = false;
4475 enable_irq(dwc->irq_gadget);