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)
142 static void dwc3_ep0_reset_state(struct dwc3 *dwc)
146 if (dwc->ep0state != EP0_SETUP_PHASE) {
147 dir = !!dwc->ep0_expect_in;
148 if (dwc->ep0state == EP0_DATA_PHASE)
149 dwc3_ep0_end_control_data(dwc, dwc->eps[dir]);
151 dwc3_ep0_end_control_data(dwc, dwc->eps[!dir]);
153 dwc->eps[0]->trb_enqueue = 0;
154 dwc->eps[1]->trb_enqueue = 0;
156 dwc3_ep0_stall_and_restart(dwc);
161 * dwc3_ep_inc_trb - increment a trb index.
162 * @index: Pointer to the TRB index to increment.
164 * The index should never point to the link TRB. After incrementing,
165 * if it is point to the link TRB, wrap around to the beginning. The
166 * link TRB is always at the last TRB entry.
168 static void dwc3_ep_inc_trb(u8 *index)
171 if (*index == (DWC3_TRB_NUM - 1))
176 * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
177 * @dep: The endpoint whose enqueue pointer we're incrementing
179 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
181 dwc3_ep_inc_trb(&dep->trb_enqueue);
185 * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
186 * @dep: The endpoint whose enqueue pointer we're incrementing
188 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
190 dwc3_ep_inc_trb(&dep->trb_dequeue);
193 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
194 struct dwc3_request *req, int status)
196 struct dwc3 *dwc = dep->dwc;
198 list_del(&req->list);
200 req->needs_extra_trb = false;
202 if (req->request.status == -EINPROGRESS)
203 req->request.status = status;
206 usb_gadget_unmap_request_by_dev(dwc->sysdev,
207 &req->request, req->direction);
210 trace_dwc3_gadget_giveback(req);
213 pm_runtime_put(dwc->dev);
217 * dwc3_gadget_giveback - call struct usb_request's ->complete callback
218 * @dep: The endpoint to whom the request belongs to
219 * @req: The request we're giving back
220 * @status: completion code for the request
222 * Must be called with controller's lock held and interrupts disabled. This
223 * function will unmap @req and call its ->complete() callback to notify upper
224 * layers that it has completed.
226 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
229 struct dwc3 *dwc = dep->dwc;
231 dwc3_gadget_del_and_unmap_request(dep, req, status);
232 req->status = DWC3_REQUEST_STATUS_COMPLETED;
234 spin_unlock(&dwc->lock);
235 usb_gadget_giveback_request(&dep->endpoint, &req->request);
236 spin_lock(&dwc->lock);
240 * dwc3_send_gadget_generic_command - issue a generic command for the controller
241 * @dwc: pointer to the controller context
242 * @cmd: the command to be issued
243 * @param: command parameter
245 * Caller should take care of locking. Issue @cmd with a given @param to @dwc
246 * and wait for its completion.
248 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
256 dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
257 dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
260 reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
261 if (!(reg & DWC3_DGCMD_CMDACT)) {
262 status = DWC3_DGCMD_STATUS(reg);
274 trace_dwc3_gadget_generic_cmd(cmd, param, status);
279 static int __dwc3_gadget_wakeup(struct dwc3 *dwc, bool async);
282 * dwc3_send_gadget_ep_cmd - issue an endpoint command
283 * @dep: the endpoint to which the command is going to be issued
284 * @cmd: the command to be issued
285 * @params: parameters to the command
287 * Caller should handle locking. This function will issue @cmd with given
288 * @params to @dep and wait for its completion.
290 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd,
291 struct dwc3_gadget_ep_cmd_params *params)
293 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
294 struct dwc3 *dwc = dep->dwc;
296 u32 saved_config = 0;
303 * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or
304 * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an
307 * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY
308 * settings. Restore them after the command is completed.
310 * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2
312 if (dwc->gadget->speed <= USB_SPEED_HIGH ||
313 DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_ENDTRANSFER) {
314 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
315 if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
316 saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
317 reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
320 if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
321 saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
322 reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
326 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
329 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
333 * Initiate remote wakeup if the link state is in U3 when
334 * operating in SS/SSP or L1/L2 when operating in HS/FS. If the
335 * link state is in U1/U2, no remote wakeup is needed. The Start
336 * Transfer command will initiate the link recovery.
338 link_state = dwc3_gadget_get_link_state(dwc);
339 switch (link_state) {
340 case DWC3_LINK_STATE_U2:
341 if (dwc->gadget->speed >= USB_SPEED_SUPER)
345 case DWC3_LINK_STATE_U3:
346 ret = __dwc3_gadget_wakeup(dwc, false);
347 dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
354 * For some commands such as Update Transfer command, DEPCMDPARn
355 * registers are reserved. Since the driver often sends Update Transfer
356 * command, don't write to DEPCMDPARn to avoid register write delays and
357 * improve performance.
359 if (DWC3_DEPCMD_CMD(cmd) != DWC3_DEPCMD_UPDATETRANSFER) {
360 dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
361 dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
362 dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
366 * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
367 * not relying on XferNotReady, we can make use of a special "No
368 * Response Update Transfer" command where we should clear both CmdAct
371 * With this, we don't need to wait for command completion and can
372 * straight away issue further commands to the endpoint.
374 * NOTICE: We're making an assumption that control endpoints will never
375 * make use of Update Transfer command. This is a safe assumption
376 * because we can never have more than one request at a time with
377 * Control Endpoints. If anybody changes that assumption, this chunk
378 * needs to be updated accordingly.
380 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
381 !usb_endpoint_xfer_isoc(desc))
382 cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
384 cmd |= DWC3_DEPCMD_CMDACT;
386 dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
388 if (!(cmd & DWC3_DEPCMD_CMDACT) ||
389 (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_ENDTRANSFER &&
390 !(cmd & DWC3_DEPCMD_CMDIOC))) {
396 reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
397 if (!(reg & DWC3_DEPCMD_CMDACT)) {
398 cmd_status = DWC3_DEPCMD_STATUS(reg);
400 switch (cmd_status) {
404 case DEPEVT_TRANSFER_NO_RESOURCE:
405 dev_WARN(dwc->dev, "No resource for %s\n",
409 case DEPEVT_TRANSFER_BUS_EXPIRY:
411 * SW issues START TRANSFER command to
412 * isochronous ep with future frame interval. If
413 * future interval time has already passed when
414 * core receives the command, it will respond
415 * with an error status of 'Bus Expiry'.
417 * Instead of always returning -EINVAL, let's
418 * give a hint to the gadget driver that this is
419 * the case by returning -EAGAIN.
424 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
433 cmd_status = -ETIMEDOUT;
437 trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
439 if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
441 dep->flags |= DWC3_EP_TRANSFER_STARTED;
443 if (ret != -ETIMEDOUT)
444 dwc3_gadget_ep_get_transfer_index(dep);
448 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
450 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
456 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
458 struct dwc3 *dwc = dep->dwc;
459 struct dwc3_gadget_ep_cmd_params params;
460 u32 cmd = DWC3_DEPCMD_CLEARSTALL;
463 * As of core revision 2.60a the recommended programming model
464 * is to set the ClearPendIN bit when issuing a Clear Stall EP
465 * command for IN endpoints. This is to prevent an issue where
466 * some (non-compliant) hosts may not send ACK TPs for pending
467 * IN transfers due to a mishandled error condition. Synopsys
470 if (dep->direction &&
471 !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
472 (dwc->gadget->speed >= USB_SPEED_SUPER))
473 cmd |= DWC3_DEPCMD_CLEARPENDIN;
475 memset(¶ms, 0, sizeof(params));
477 return dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
480 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
481 struct dwc3_trb *trb)
483 u32 offset = (char *) trb - (char *) dep->trb_pool;
485 return dep->trb_pool_dma + offset;
488 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
490 struct dwc3 *dwc = dep->dwc;
495 dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
496 sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
497 &dep->trb_pool_dma, GFP_KERNEL);
498 if (!dep->trb_pool) {
499 dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
507 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
509 struct dwc3 *dwc = dep->dwc;
511 dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
512 dep->trb_pool, dep->trb_pool_dma);
514 dep->trb_pool = NULL;
515 dep->trb_pool_dma = 0;
518 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
520 struct dwc3_gadget_ep_cmd_params params;
522 memset(¶ms, 0x00, sizeof(params));
524 params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
526 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
531 * dwc3_gadget_start_config - configure ep resources
532 * @dep: endpoint that is being enabled
534 * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
535 * completion, it will set Transfer Resource for all available endpoints.
537 * The assignment of transfer resources cannot perfectly follow the data book
538 * due to the fact that the controller driver does not have all knowledge of the
539 * configuration in advance. It is given this information piecemeal by the
540 * composite gadget framework after every SET_CONFIGURATION and
541 * SET_INTERFACE. Trying to follow the databook programming model in this
542 * scenario can cause errors. For two reasons:
544 * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
545 * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
546 * incorrect in the scenario of multiple interfaces.
548 * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
549 * endpoint on alt setting (8.1.6).
551 * The following simplified method is used instead:
553 * All hardware endpoints can be assigned a transfer resource and this setting
554 * will stay persistent until either a core reset or hibernation. So whenever we
555 * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
556 * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
557 * guaranteed that there are as many transfer resources as endpoints.
559 * This function is called for each endpoint when it is being enabled but is
560 * triggered only when called for EP0-out, which always happens first, and which
561 * should only happen in one of the above conditions.
563 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
565 struct dwc3_gadget_ep_cmd_params params;
574 memset(¶ms, 0x00, sizeof(params));
575 cmd = DWC3_DEPCMD_DEPSTARTCFG;
578 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
582 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
583 struct dwc3_ep *dep = dwc->eps[i];
588 ret = dwc3_gadget_set_xfer_resource(dep);
596 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
598 const struct usb_ss_ep_comp_descriptor *comp_desc;
599 const struct usb_endpoint_descriptor *desc;
600 struct dwc3_gadget_ep_cmd_params params;
601 struct dwc3 *dwc = dep->dwc;
603 comp_desc = dep->endpoint.comp_desc;
604 desc = dep->endpoint.desc;
606 memset(¶ms, 0x00, sizeof(params));
608 params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
609 | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
611 /* Burst size is only needed in SuperSpeed mode */
612 if (dwc->gadget->speed >= USB_SPEED_SUPER) {
613 u32 burst = dep->endpoint.maxburst;
615 params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
618 params.param0 |= action;
619 if (action == DWC3_DEPCFG_ACTION_RESTORE)
620 params.param2 |= dep->saved_state;
622 if (usb_endpoint_xfer_control(desc))
623 params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
625 if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
626 params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
628 if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
629 params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
630 | DWC3_DEPCFG_XFER_COMPLETE_EN
631 | DWC3_DEPCFG_STREAM_EVENT_EN;
632 dep->stream_capable = true;
635 if (!usb_endpoint_xfer_control(desc))
636 params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
639 * We are doing 1:1 mapping for endpoints, meaning
640 * Physical Endpoints 2 maps to Logical Endpoint 2 and
641 * so on. We consider the direction bit as part of the physical
642 * endpoint number. So USB endpoint 0x81 is 0x03.
644 params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
647 * We must use the lower 16 TX FIFOs even though
651 params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
653 if (desc->bInterval) {
657 * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
659 * NOTE: The programming guide incorrectly stated bInterval_m1
660 * must be set to 0 when operating in fullspeed. Internally the
661 * controller does not have this limitation. See DWC_usb3x
662 * programming guide section 3.2.2.1.
664 bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
666 if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
667 dwc->gadget->speed == USB_SPEED_FULL)
668 dep->interval = desc->bInterval;
670 dep->interval = 1 << (desc->bInterval - 1);
672 params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
675 return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, ¶ms);
679 * dwc3_gadget_calc_tx_fifo_size - calculates the txfifo size value
680 * @dwc: pointer to the DWC3 context
681 * @mult: multiplier to be used when calculating the fifo_size
683 * Calculates the size value based on the equation below:
685 * DWC3 revision 280A and prior:
686 * fifo_size = mult * (max_packet / mdwidth) + 1;
688 * DWC3 revision 290A and onwards:
689 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
691 * The max packet size is set to 1024, as the txfifo requirements mainly apply
692 * to super speed USB use cases. However, it is safe to overestimate the fifo
693 * allocations for other scenarios, i.e. high speed USB.
695 static int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult)
697 int max_packet = 1024;
701 mdwidth = dwc3_mdwidth(dwc);
703 /* MDWIDTH is represented in bits, we need it in bytes */
706 if (DWC3_VER_IS_PRIOR(DWC3, 290A))
707 fifo_size = mult * (max_packet / mdwidth) + 1;
709 fifo_size = mult * ((max_packet + mdwidth) / mdwidth) + 1;
714 * dwc3_gadget_clear_tx_fifos - Clears txfifo allocation
715 * @dwc: pointer to the DWC3 context
717 * Iterates through all the endpoint registers and clears the previous txfifo
720 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc)
727 if (!dwc->do_fifo_resize)
730 /* Read ep0IN related TXFIFO size */
732 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
733 if (DWC3_IP_IS(DWC3))
734 fifo_depth = DWC3_GTXFIFOSIZ_TXFDEP(size);
736 fifo_depth = DWC31_GTXFIFOSIZ_TXFDEP(size);
738 dwc->last_fifo_depth = fifo_depth;
739 /* Clear existing TXFIFO for all IN eps except ep0 */
740 for (num = 3; num < min_t(int, dwc->num_eps, DWC3_ENDPOINTS_NUM);
743 /* Don't change TXFRAMNUM on usb31 version */
744 size = DWC3_IP_IS(DWC3) ? 0 :
745 dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1)) &
746 DWC31_GTXFIFOSIZ_TXFRAMNUM;
748 dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1), size);
749 dep->flags &= ~DWC3_EP_TXFIFO_RESIZED;
751 dwc->num_ep_resized = 0;
755 * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
756 * @dwc: pointer to our context structure
758 * This function will a best effort FIFO allocation in order
759 * to improve FIFO usage and throughput, while still allowing
760 * us to enable as many endpoints as possible.
762 * Keep in mind that this operation will be highly dependent
763 * on the configured size for RAM1 - which contains TxFifo -,
764 * the amount of endpoints enabled on coreConsultant tool, and
765 * the width of the Master Bus.
767 * In general, FIFO depths are represented with the following equation:
769 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
771 * In conjunction with dwc3_gadget_check_config(), this resizing logic will
772 * ensure that all endpoints will have enough internal memory for one max
773 * packet per endpoint.
775 static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep)
777 struct dwc3 *dwc = dep->dwc;
788 if (!dwc->do_fifo_resize)
791 /* resize IN endpoints except ep0 */
792 if (!usb_endpoint_dir_in(dep->endpoint.desc) || dep->number <= 1)
795 /* bail if already resized */
796 if (dep->flags & DWC3_EP_TXFIFO_RESIZED)
799 ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
801 if ((dep->endpoint.maxburst > 1 &&
802 usb_endpoint_xfer_bulk(dep->endpoint.desc)) ||
803 usb_endpoint_xfer_isoc(dep->endpoint.desc))
806 if (dep->endpoint.maxburst > 6 &&
807 (usb_endpoint_xfer_bulk(dep->endpoint.desc) ||
808 usb_endpoint_xfer_isoc(dep->endpoint.desc)) && DWC3_IP_IS(DWC31))
809 num_fifos = dwc->tx_fifo_resize_max_num;
811 /* FIFO size for a single buffer */
812 fifo = dwc3_gadget_calc_tx_fifo_size(dwc, 1);
814 /* Calculate the number of remaining EPs w/o any FIFO */
815 num_in_ep = dwc->max_cfg_eps;
816 num_in_ep -= dwc->num_ep_resized;
818 /* Reserve at least one FIFO for the number of IN EPs */
819 min_depth = num_in_ep * (fifo + 1);
820 remaining = ram1_depth - min_depth - dwc->last_fifo_depth;
821 remaining = max_t(int, 0, remaining);
823 * We've already reserved 1 FIFO per EP, so check what we can fit in
824 * addition to it. If there is not enough remaining space, allocate
825 * all the remaining space to the EP.
827 fifo_size = (num_fifos - 1) * fifo;
828 if (remaining < fifo_size)
829 fifo_size = remaining;
832 /* Last increment according to the TX FIFO size equation */
835 /* Check if TXFIFOs start at non-zero addr */
836 tmp = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
837 fifo_0_start = DWC3_GTXFIFOSIZ_TXFSTADDR(tmp);
839 fifo_size |= (fifo_0_start + (dwc->last_fifo_depth << 16));
840 if (DWC3_IP_IS(DWC3))
841 dwc->last_fifo_depth += DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
843 dwc->last_fifo_depth += DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
845 /* Check fifo size allocation doesn't exceed available RAM size. */
846 if (dwc->last_fifo_depth >= ram1_depth) {
847 dev_err(dwc->dev, "Fifosize(%d) > RAM size(%d) %s depth:%d\n",
848 dwc->last_fifo_depth, ram1_depth,
849 dep->endpoint.name, fifo_size);
850 if (DWC3_IP_IS(DWC3))
851 fifo_size = DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
853 fifo_size = DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
855 dwc->last_fifo_depth -= fifo_size;
859 dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1), fifo_size);
860 dep->flags |= DWC3_EP_TXFIFO_RESIZED;
861 dwc->num_ep_resized++;
867 * __dwc3_gadget_ep_enable - initializes a hw endpoint
868 * @dep: endpoint to be initialized
869 * @action: one of INIT, MODIFY or RESTORE
871 * Caller should take care of locking. Execute all necessary commands to
872 * initialize a HW endpoint so it can be used by a gadget driver.
874 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
876 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
877 struct dwc3 *dwc = dep->dwc;
882 if (!(dep->flags & DWC3_EP_ENABLED)) {
883 ret = dwc3_gadget_resize_tx_fifos(dep);
887 ret = dwc3_gadget_start_config(dep);
892 ret = dwc3_gadget_set_ep_config(dep, action);
896 if (!(dep->flags & DWC3_EP_ENABLED)) {
897 struct dwc3_trb *trb_st_hw;
898 struct dwc3_trb *trb_link;
900 dep->type = usb_endpoint_type(desc);
901 dep->flags |= DWC3_EP_ENABLED;
903 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
904 reg |= DWC3_DALEPENA_EP(dep->number);
905 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
907 dep->trb_dequeue = 0;
908 dep->trb_enqueue = 0;
910 if (usb_endpoint_xfer_control(desc))
913 /* Initialize the TRB ring */
914 memset(dep->trb_pool, 0,
915 sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
917 /* Link TRB. The HWO bit is never reset */
918 trb_st_hw = &dep->trb_pool[0];
920 trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
921 trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
922 trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
923 trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
924 trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
928 * Issue StartTransfer here with no-op TRB so we can always rely on No
929 * Response Update Transfer command.
931 if (usb_endpoint_xfer_bulk(desc) ||
932 usb_endpoint_xfer_int(desc)) {
933 struct dwc3_gadget_ep_cmd_params params;
934 struct dwc3_trb *trb;
938 memset(¶ms, 0, sizeof(params));
939 trb = &dep->trb_pool[0];
940 trb_dma = dwc3_trb_dma_offset(dep, trb);
942 params.param0 = upper_32_bits(trb_dma);
943 params.param1 = lower_32_bits(trb_dma);
945 cmd = DWC3_DEPCMD_STARTTRANSFER;
947 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
951 if (dep->stream_capable) {
953 * For streams, at start, there maybe a race where the
954 * host primes the endpoint before the function driver
955 * queues a request to initiate a stream. In that case,
956 * the controller will not see the prime to generate the
957 * ERDY and start stream. To workaround this, issue a
958 * no-op TRB as normal, but end it immediately. As a
959 * result, when the function driver queues the request,
960 * the next START_TRANSFER command will cause the
961 * controller to generate an ERDY to initiate the
964 dwc3_stop_active_transfer(dep, true, true);
967 * All stream eps will reinitiate stream on NoStream
968 * rejection until we can determine that the host can
969 * prime after the first transfer.
971 * However, if the controller is capable of
972 * TXF_FLUSH_BYPASS, then IN direction endpoints will
973 * automatically restart the stream without the driver
976 if (!dep->direction ||
977 !(dwc->hwparams.hwparams9 &
978 DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
979 dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
984 trace_dwc3_gadget_ep_enable(dep);
989 void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status)
991 struct dwc3_request *req;
993 dwc3_stop_active_transfer(dep, true, false);
995 /* If endxfer is delayed, avoid unmapping requests */
996 if (dep->flags & DWC3_EP_DELAY_STOP)
999 /* - giveback all requests to gadget driver */
1000 while (!list_empty(&dep->started_list)) {
1001 req = next_request(&dep->started_list);
1003 dwc3_gadget_giveback(dep, req, status);
1006 while (!list_empty(&dep->pending_list)) {
1007 req = next_request(&dep->pending_list);
1009 dwc3_gadget_giveback(dep, req, status);
1012 while (!list_empty(&dep->cancelled_list)) {
1013 req = next_request(&dep->cancelled_list);
1015 dwc3_gadget_giveback(dep, req, status);
1020 * __dwc3_gadget_ep_disable - disables a hw endpoint
1021 * @dep: the endpoint to disable
1023 * This function undoes what __dwc3_gadget_ep_enable did and also removes
1024 * requests which are currently being processed by the hardware and those which
1025 * are not yet scheduled.
1027 * Caller should take care of locking.
1029 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
1031 struct dwc3 *dwc = dep->dwc;
1035 trace_dwc3_gadget_ep_disable(dep);
1037 /* make sure HW endpoint isn't stalled */
1038 if (dep->flags & DWC3_EP_STALL)
1039 __dwc3_gadget_ep_set_halt(dep, 0, false);
1041 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
1042 reg &= ~DWC3_DALEPENA_EP(dep->number);
1043 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
1045 dwc3_remove_requests(dwc, dep, -ESHUTDOWN);
1047 dep->stream_capable = false;
1049 mask = DWC3_EP_TXFIFO_RESIZED;
1051 * dwc3_remove_requests() can exit early if DWC3 EP delayed stop is
1052 * set. Do not clear DEP flags, so that the end transfer command will
1053 * be reattempted during the next SETUP stage.
1055 if (dep->flags & DWC3_EP_DELAY_STOP)
1056 mask |= (DWC3_EP_DELAY_STOP | DWC3_EP_TRANSFER_STARTED);
1059 /* Clear out the ep descriptors for non-ep0 */
1060 if (dep->number > 1) {
1061 dep->endpoint.comp_desc = NULL;
1062 dep->endpoint.desc = NULL;
1068 /* -------------------------------------------------------------------------- */
1070 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
1071 const struct usb_endpoint_descriptor *desc)
1076 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
1081 /* -------------------------------------------------------------------------- */
1083 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
1084 const struct usb_endpoint_descriptor *desc)
1086 struct dwc3_ep *dep;
1088 unsigned long flags;
1091 if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
1092 pr_debug("dwc3: invalid parameters\n");
1096 if (!desc->wMaxPacketSize) {
1097 pr_debug("dwc3: missing wMaxPacketSize\n");
1101 dep = to_dwc3_ep(ep);
1104 if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
1105 "%s is already enabled\n",
1109 spin_lock_irqsave(&dwc->lock, flags);
1110 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1111 spin_unlock_irqrestore(&dwc->lock, flags);
1116 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
1118 struct dwc3_ep *dep;
1120 unsigned long flags;
1124 pr_debug("dwc3: invalid parameters\n");
1128 dep = to_dwc3_ep(ep);
1131 if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
1132 "%s is already disabled\n",
1136 spin_lock_irqsave(&dwc->lock, flags);
1137 ret = __dwc3_gadget_ep_disable(dep);
1138 spin_unlock_irqrestore(&dwc->lock, flags);
1143 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
1146 struct dwc3_request *req;
1147 struct dwc3_ep *dep = to_dwc3_ep(ep);
1149 req = kzalloc(sizeof(*req), gfp_flags);
1153 req->direction = dep->direction;
1154 req->epnum = dep->number;
1156 req->status = DWC3_REQUEST_STATUS_UNKNOWN;
1158 trace_dwc3_alloc_request(req);
1160 return &req->request;
1163 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
1164 struct usb_request *request)
1166 struct dwc3_request *req = to_dwc3_request(request);
1168 trace_dwc3_free_request(req);
1173 * dwc3_ep_prev_trb - returns the previous TRB in the ring
1174 * @dep: The endpoint with the TRB ring
1175 * @index: The index of the current TRB in the ring
1177 * Returns the TRB prior to the one pointed to by the index. If the
1178 * index is 0, we will wrap backwards, skip the link TRB, and return
1179 * the one just before that.
1181 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1186 tmp = DWC3_TRB_NUM - 1;
1188 return &dep->trb_pool[tmp - 1];
1191 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1196 * If the enqueue & dequeue are equal then the TRB ring is either full
1197 * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
1198 * pending to be processed by the driver.
1200 if (dep->trb_enqueue == dep->trb_dequeue) {
1202 * If there is any request remained in the started_list at
1203 * this point, that means there is no TRB available.
1205 if (!list_empty(&dep->started_list))
1208 return DWC3_TRB_NUM - 1;
1211 trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1212 trbs_left &= (DWC3_TRB_NUM - 1);
1214 if (dep->trb_dequeue < dep->trb_enqueue)
1221 * dwc3_prepare_one_trb - setup one TRB from one request
1222 * @dep: endpoint for which this request is prepared
1223 * @req: dwc3_request pointer
1224 * @trb_length: buffer size of the TRB
1225 * @chain: should this TRB be chained to the next?
1226 * @node: only for isochronous endpoints. First TRB needs different type.
1227 * @use_bounce_buffer: set to use bounce buffer
1228 * @must_interrupt: set to interrupt on TRB completion
1230 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1231 struct dwc3_request *req, unsigned int trb_length,
1232 unsigned int chain, unsigned int node, bool use_bounce_buffer,
1233 bool must_interrupt)
1235 struct dwc3_trb *trb;
1237 unsigned int stream_id = req->request.stream_id;
1238 unsigned int short_not_ok = req->request.short_not_ok;
1239 unsigned int no_interrupt = req->request.no_interrupt;
1240 unsigned int is_last = req->request.is_last;
1241 struct dwc3 *dwc = dep->dwc;
1242 struct usb_gadget *gadget = dwc->gadget;
1243 enum usb_device_speed speed = gadget->speed;
1245 if (use_bounce_buffer)
1246 dma = dep->dwc->bounce_addr;
1247 else if (req->request.num_sgs > 0)
1248 dma = sg_dma_address(req->start_sg);
1250 dma = req->request.dma;
1252 trb = &dep->trb_pool[dep->trb_enqueue];
1255 dwc3_gadget_move_started_request(req);
1257 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1262 trb->size = DWC3_TRB_SIZE_LENGTH(trb_length);
1263 trb->bpl = lower_32_bits(dma);
1264 trb->bph = upper_32_bits(dma);
1266 switch (usb_endpoint_type(dep->endpoint.desc)) {
1267 case USB_ENDPOINT_XFER_CONTROL:
1268 trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
1271 case USB_ENDPOINT_XFER_ISOC:
1273 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
1276 * USB Specification 2.0 Section 5.9.2 states that: "If
1277 * there is only a single transaction in the microframe,
1278 * only a DATA0 data packet PID is used. If there are
1279 * two transactions per microframe, DATA1 is used for
1280 * the first transaction data packet and DATA0 is used
1281 * for the second transaction data packet. If there are
1282 * three transactions per microframe, DATA2 is used for
1283 * the first transaction data packet, DATA1 is used for
1284 * the second, and DATA0 is used for the third."
1286 * IOW, we should satisfy the following cases:
1288 * 1) length <= maxpacket
1291 * 2) maxpacket < length <= (2 * maxpacket)
1294 * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1295 * - DATA2, DATA1, DATA0
1297 if (speed == USB_SPEED_HIGH) {
1298 struct usb_ep *ep = &dep->endpoint;
1299 unsigned int mult = 2;
1300 unsigned int maxp = usb_endpoint_maxp(ep->desc);
1302 if (req->request.length <= (2 * maxp))
1305 if (req->request.length <= maxp)
1308 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1311 trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1314 if (!no_interrupt && !chain)
1315 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1318 case USB_ENDPOINT_XFER_BULK:
1319 case USB_ENDPOINT_XFER_INT:
1320 trb->ctrl = DWC3_TRBCTL_NORMAL;
1324 * This is only possible with faulty memory because we
1325 * checked it already :)
1327 dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1328 usb_endpoint_type(dep->endpoint.desc));
1332 * Enable Continue on Short Packet
1333 * when endpoint is not a stream capable
1335 if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1336 if (!dep->stream_capable)
1337 trb->ctrl |= DWC3_TRB_CTRL_CSP;
1340 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1343 /* All TRBs setup for MST must set CSP=1 when LST=0 */
1344 if (dep->stream_capable && DWC3_MST_CAPABLE(&dwc->hwparams))
1345 trb->ctrl |= DWC3_TRB_CTRL_CSP;
1347 if ((!no_interrupt && !chain) || must_interrupt)
1348 trb->ctrl |= DWC3_TRB_CTRL_IOC;
1351 trb->ctrl |= DWC3_TRB_CTRL_CHN;
1352 else if (dep->stream_capable && is_last &&
1353 !DWC3_MST_CAPABLE(&dwc->hwparams))
1354 trb->ctrl |= DWC3_TRB_CTRL_LST;
1356 if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1357 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1360 * As per data book 4.2.3.2TRB Control Bit Rules section
1362 * The controller autonomously checks the HWO field of a TRB to determine if the
1363 * entire TRB is valid. Therefore, software must ensure that the rest of the TRB
1364 * is valid before setting the HWO field to '1'. In most systems, this means that
1365 * software must update the fourth DWORD of a TRB last.
1367 * However there is a possibility of CPU re-ordering here which can cause
1368 * controller to observe the HWO bit set prematurely.
1369 * Add a write memory barrier to prevent CPU re-ordering.
1372 trb->ctrl |= DWC3_TRB_CTRL_HWO;
1374 dwc3_ep_inc_enq(dep);
1376 trace_dwc3_prepare_trb(dep, trb);
1379 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1381 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1382 unsigned int rem = req->request.length % maxp;
1384 if ((req->request.length && req->request.zero && !rem &&
1385 !usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1386 (!req->direction && rem))
1393 * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1394 * @dep: The endpoint that the request belongs to
1395 * @req: The request to prepare
1396 * @entry_length: The last SG entry size
1397 * @node: Indicates whether this is not the first entry (for isoc only)
1399 * Return the number of TRBs prepared.
1401 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1402 struct dwc3_request *req, unsigned int entry_length,
1405 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1406 unsigned int rem = req->request.length % maxp;
1407 unsigned int num_trbs = 1;
1409 if (dwc3_needs_extra_trb(dep, req))
1412 if (dwc3_calc_trbs_left(dep) < num_trbs)
1415 req->needs_extra_trb = num_trbs > 1;
1417 /* Prepare a normal TRB */
1418 if (req->direction || req->request.length)
1419 dwc3_prepare_one_trb(dep, req, entry_length,
1420 req->needs_extra_trb, node, false, false);
1422 /* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1423 if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1424 dwc3_prepare_one_trb(dep, req,
1425 req->direction ? 0 : maxp - rem,
1426 false, 1, true, false);
1431 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1432 struct dwc3_request *req)
1434 struct scatterlist *sg = req->start_sg;
1435 struct scatterlist *s;
1437 unsigned int length = req->request.length;
1438 unsigned int remaining = req->request.num_mapped_sgs
1439 - req->num_queued_sgs;
1440 unsigned int num_trbs = req->num_trbs;
1441 bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1444 * If we resume preparing the request, then get the remaining length of
1445 * the request and resume where we left off.
1447 for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1448 length -= sg_dma_len(s);
1450 for_each_sg(sg, s, remaining, i) {
1451 unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1452 unsigned int trb_length;
1453 bool must_interrupt = false;
1454 bool last_sg = false;
1456 trb_length = min_t(unsigned int, length, sg_dma_len(s));
1458 length -= trb_length;
1461 * IOMMU driver is coalescing the list of sgs which shares a
1462 * page boundary into one and giving it to USB driver. With
1463 * this the number of sgs mapped is not equal to the number of
1464 * sgs passed. So mark the chain bit to false if it isthe last
1467 if ((i == remaining - 1) || !length)
1474 if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1478 * Look ahead to check if we have enough TRBs for the
1479 * next SG entry. If not, set interrupt on this TRB to
1480 * resume preparing the next SG entry when more TRBs are
1483 if (num_trbs_left == 1 || (needs_extra_trb &&
1484 num_trbs_left <= 2 &&
1485 sg_dma_len(sg_next(s)) >= length)) {
1486 struct dwc3_request *r;
1488 /* Check if previous requests already set IOC */
1489 list_for_each_entry(r, &dep->started_list, list) {
1490 if (r != req && !r->request.no_interrupt)
1494 must_interrupt = true;
1498 dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1503 * There can be a situation where all sgs in sglist are not
1504 * queued because of insufficient trb number. To handle this
1505 * case, update start_sg to next sg to be queued, so that
1506 * we have free trbs we can continue queuing from where we
1507 * previously stopped
1510 req->start_sg = sg_next(s);
1512 req->num_queued_sgs++;
1513 req->num_pending_sgs--;
1516 * The number of pending SG entries may not correspond to the
1517 * number of mapped SG entries. If all the data are queued, then
1518 * don't include unused SG entries.
1521 req->num_pending_sgs = 0;
1529 return req->num_trbs - num_trbs;
1532 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1533 struct dwc3_request *req)
1535 return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1539 * dwc3_prepare_trbs - setup TRBs from requests
1540 * @dep: endpoint for which requests are being prepared
1542 * The function goes through the requests list and sets up TRBs for the
1543 * transfers. The function returns once there are no more TRBs available or
1544 * it runs out of requests.
1546 * Returns the number of TRBs prepared or negative errno.
1548 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1550 struct dwc3_request *req, *n;
1553 BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1556 * We can get in a situation where there's a request in the started list
1557 * but there weren't enough TRBs to fully kick it in the first time
1558 * around, so it has been waiting for more TRBs to be freed up.
1560 * In that case, we should check if we have a request with pending_sgs
1561 * in the started list and prepare TRBs for that request first,
1562 * otherwise we will prepare TRBs completely out of order and that will
1565 list_for_each_entry(req, &dep->started_list, list) {
1566 if (req->num_pending_sgs > 0) {
1567 ret = dwc3_prepare_trbs_sg(dep, req);
1568 if (!ret || req->num_pending_sgs)
1572 if (!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(&dep->dwc->hwparams))
1585 list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1586 struct dwc3 *dwc = dep->dwc;
1588 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1593 req->sg = req->request.sg;
1594 req->start_sg = req->sg;
1595 req->num_queued_sgs = 0;
1596 req->num_pending_sgs = req->request.num_mapped_sgs;
1598 if (req->num_pending_sgs > 0) {
1599 ret = dwc3_prepare_trbs_sg(dep, req);
1600 if (req->num_pending_sgs)
1603 ret = dwc3_prepare_trbs_linear(dep, req);
1606 if (!ret || !dwc3_calc_trbs_left(dep))
1610 * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1611 * burst capability may try to read and use TRBs beyond the
1612 * active transfer instead of stopping.
1614 if (dep->stream_capable && req->request.is_last &&
1615 !DWC3_MST_CAPABLE(&dwc->hwparams))
1622 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1624 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1626 struct dwc3_gadget_ep_cmd_params params;
1627 struct dwc3_request *req;
1633 * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1634 * This happens when we need to stop and restart a transfer such as in
1635 * the case of reinitiating a stream or retrying an isoc transfer.
1637 ret = dwc3_prepare_trbs(dep);
1641 starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1644 * If there's no new TRB prepared and we don't need to restart a
1645 * transfer, there's no need to update the transfer.
1647 if (!ret && !starting)
1650 req = next_request(&dep->started_list);
1652 dep->flags |= DWC3_EP_PENDING_REQUEST;
1656 memset(¶ms, 0, sizeof(params));
1659 params.param0 = upper_32_bits(req->trb_dma);
1660 params.param1 = lower_32_bits(req->trb_dma);
1661 cmd = DWC3_DEPCMD_STARTTRANSFER;
1663 if (dep->stream_capable)
1664 cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1666 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1667 cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1669 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1670 DWC3_DEPCMD_PARAM(dep->resource_index);
1673 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1675 struct dwc3_request *tmp;
1680 dwc3_stop_active_transfer(dep, true, true);
1682 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1683 dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_DEQUEUED);
1685 /* If ep isn't started, then there's no end transfer pending */
1686 if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1687 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1692 if (dep->stream_capable && req->request.is_last &&
1693 !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1694 dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1699 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1703 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1704 return DWC3_DSTS_SOFFN(reg);
1708 * __dwc3_stop_active_transfer - stop the current active transfer
1709 * @dep: isoc endpoint
1710 * @force: set forcerm bit in the command
1711 * @interrupt: command complete interrupt after End Transfer command
1713 * When setting force, the ForceRM bit will be set. In that case
1714 * the controller won't update the TRB progress on command
1715 * completion. It also won't clear the HWO bit in the TRB.
1716 * The command will also not complete immediately in that case.
1718 static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt)
1720 struct dwc3 *dwc = dep->dwc;
1721 struct dwc3_gadget_ep_cmd_params params;
1725 cmd = DWC3_DEPCMD_ENDTRANSFER;
1726 cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
1727 cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
1728 cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
1729 memset(¶ms, 0, sizeof(params));
1730 ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1732 * If the End Transfer command was timed out while the device is
1733 * not in SETUP phase, it's possible that an incoming Setup packet
1734 * may prevent the command's completion. Let's retry when the
1735 * ep0state returns to EP0_SETUP_PHASE.
1737 if (ret == -ETIMEDOUT && dep->dwc->ep0state != EP0_SETUP_PHASE) {
1738 dep->flags |= DWC3_EP_DELAY_STOP;
1742 dep->resource_index = 0;
1745 if (!DWC3_IP_IS(DWC3) || DWC3_VER_IS_PRIOR(DWC3, 310A))
1747 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
1749 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1752 dep->flags &= ~DWC3_EP_DELAY_STOP;
1757 * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1758 * @dep: isoc endpoint
1760 * This function tests for the correct combination of BIT[15:14] from the 16-bit
1761 * microframe number reported by the XferNotReady event for the future frame
1762 * number to start the isoc transfer.
1764 * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1765 * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1766 * XferNotReady event are invalid. The driver uses this number to schedule the
1767 * isochronous transfer and passes it to the START TRANSFER command. Because
1768 * this number is invalid, the command may fail. If BIT[15:14] matches the
1769 * internal 16-bit microframe, the START TRANSFER command will pass and the
1770 * transfer will start at the scheduled time, if it is off by 1, the command
1771 * will still pass, but the transfer will start 2 seconds in the future. For all
1772 * other conditions, the START TRANSFER command will fail with bus-expiry.
1774 * In order to workaround this issue, we can test for the correct combination of
1775 * BIT[15:14] by sending START TRANSFER commands with different values of
1776 * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1777 * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1778 * As the result, within the 4 possible combinations for BIT[15:14], there will
1779 * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1780 * command status will result in a 2-second delay start. The smaller BIT[15:14]
1781 * value is the correct combination.
1783 * Since there are only 4 outcomes and the results are ordered, we can simply
1784 * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1785 * deduce the smaller successful combination.
1787 * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1788 * of BIT[15:14]. The correct combination is as follow:
1790 * if test0 fails and test1 passes, BIT[15:14] is 'b01
1791 * if test0 fails and test1 fails, BIT[15:14] is 'b10
1792 * if test0 passes and test1 fails, BIT[15:14] is 'b11
1793 * if test0 passes and test1 passes, BIT[15:14] is 'b00
1795 * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1798 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1804 while (dep->combo_num < 2) {
1805 struct dwc3_gadget_ep_cmd_params params;
1806 u32 test_frame_number;
1810 * Check if we can start isoc transfer on the next interval or
1811 * 4 uframes in the future with BIT[15:14] as dep->combo_num
1813 test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1814 test_frame_number |= dep->combo_num << 14;
1815 test_frame_number += max_t(u32, 4, dep->interval);
1817 params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1818 params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1820 cmd = DWC3_DEPCMD_STARTTRANSFER;
1821 cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1822 cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
1824 /* Redo if some other failure beside bus-expiry is received */
1825 if (cmd_status && cmd_status != -EAGAIN) {
1826 dep->start_cmd_status = 0;
1831 /* Store the first test status */
1832 if (dep->combo_num == 0)
1833 dep->start_cmd_status = cmd_status;
1838 * End the transfer if the START_TRANSFER command is successful
1839 * to wait for the next XferNotReady to test the command again
1841 if (cmd_status == 0) {
1842 dwc3_stop_active_transfer(dep, true, true);
1847 /* test0 and test1 are both completed at this point */
1848 test0 = (dep->start_cmd_status == 0);
1849 test1 = (cmd_status == 0);
1851 if (!test0 && test1)
1853 else if (!test0 && !test1)
1855 else if (test0 && !test1)
1857 else if (test0 && test1)
1860 dep->frame_number &= DWC3_FRNUMBER_MASK;
1861 dep->frame_number |= dep->combo_num << 14;
1862 dep->frame_number += max_t(u32, 4, dep->interval);
1864 /* Reinitialize test variables */
1865 dep->start_cmd_status = 0;
1868 return __dwc3_gadget_kick_transfer(dep);
1871 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1873 const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1874 struct dwc3 *dwc = dep->dwc;
1878 if (list_empty(&dep->pending_list) &&
1879 list_empty(&dep->started_list)) {
1880 dep->flags |= DWC3_EP_PENDING_REQUEST;
1884 if (!dwc->dis_start_transfer_quirk &&
1885 (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1886 DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1887 if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1888 return dwc3_gadget_start_isoc_quirk(dep);
1891 if (desc->bInterval <= 14 &&
1892 dwc->gadget->speed >= USB_SPEED_HIGH) {
1893 u32 frame = __dwc3_gadget_get_frame(dwc);
1894 bool rollover = frame <
1895 (dep->frame_number & DWC3_FRNUMBER_MASK);
1898 * frame_number is set from XferNotReady and may be already
1899 * out of date. DSTS only provides the lower 14 bit of the
1900 * current frame number. So add the upper two bits of
1901 * frame_number and handle a possible rollover.
1902 * This will provide the correct frame_number unless more than
1903 * rollover has happened since XferNotReady.
1906 dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1909 dep->frame_number += BIT(14);
1912 for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1913 int future_interval = i + 1;
1915 /* Give the controller at least 500us to schedule transfers */
1916 if (desc->bInterval < 3)
1917 future_interval += 3 - desc->bInterval;
1919 dep->frame_number = DWC3_ALIGN_FRAME(dep, future_interval);
1921 ret = __dwc3_gadget_kick_transfer(dep);
1927 * After a number of unsuccessful start attempts due to bus-expiry
1928 * status, issue END_TRANSFER command and retry on the next XferNotReady
1932 ret = __dwc3_stop_active_transfer(dep, false, true);
1937 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1939 struct dwc3 *dwc = dep->dwc;
1941 if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1942 dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
1947 if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1948 &req->request, req->dep->name))
1951 if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1952 "%s: request %pK already in flight\n",
1953 dep->name, &req->request))
1956 pm_runtime_get(dwc->dev);
1958 req->request.actual = 0;
1959 req->request.status = -EINPROGRESS;
1961 trace_dwc3_ep_queue(req);
1963 list_add_tail(&req->list, &dep->pending_list);
1964 req->status = DWC3_REQUEST_STATUS_QUEUED;
1966 if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1970 * Start the transfer only after the END_TRANSFER is completed
1971 * and endpoint STALL is cleared.
1973 if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1974 (dep->flags & DWC3_EP_WEDGE) ||
1975 (dep->flags & DWC3_EP_DELAY_STOP) ||
1976 (dep->flags & DWC3_EP_STALL)) {
1977 dep->flags |= DWC3_EP_DELAY_START;
1982 * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1983 * wait for a XferNotReady event so we will know what's the current
1984 * (micro-)frame number.
1986 * Without this trick, we are very, very likely gonna get Bus Expiry
1987 * errors which will force us issue EndTransfer command.
1989 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1990 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1991 if ((dep->flags & DWC3_EP_PENDING_REQUEST))
1992 return __dwc3_gadget_start_isoc(dep);
1998 __dwc3_gadget_kick_transfer(dep);
2003 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
2006 struct dwc3_request *req = to_dwc3_request(request);
2007 struct dwc3_ep *dep = to_dwc3_ep(ep);
2008 struct dwc3 *dwc = dep->dwc;
2010 unsigned long flags;
2014 spin_lock_irqsave(&dwc->lock, flags);
2015 ret = __dwc3_gadget_ep_queue(dep, req);
2016 spin_unlock_irqrestore(&dwc->lock, flags);
2021 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
2025 /* If req->trb is not set, then the request has not started */
2030 * If request was already started, this means we had to
2031 * stop the transfer. With that we also need to ignore
2032 * all TRBs used by the request, however TRBs can only
2033 * be modified after completion of END_TRANSFER
2034 * command. So what we do here is that we wait for
2035 * END_TRANSFER completion and only after that, we jump
2036 * over TRBs by clearing HWO and incrementing dequeue
2039 for (i = 0; i < req->num_trbs; i++) {
2040 struct dwc3_trb *trb;
2042 trb = &dep->trb_pool[dep->trb_dequeue];
2043 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2044 dwc3_ep_inc_deq(dep);
2050 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
2052 struct dwc3_request *req;
2053 struct dwc3 *dwc = dep->dwc;
2055 while (!list_empty(&dep->cancelled_list)) {
2056 req = next_request(&dep->cancelled_list);
2057 dwc3_gadget_ep_skip_trbs(dep, req);
2058 switch (req->status) {
2059 case DWC3_REQUEST_STATUS_DISCONNECTED:
2060 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
2062 case DWC3_REQUEST_STATUS_DEQUEUED:
2063 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2065 case DWC3_REQUEST_STATUS_STALLED:
2066 dwc3_gadget_giveback(dep, req, -EPIPE);
2069 dev_err(dwc->dev, "request cancelled with wrong reason:%d\n", req->status);
2070 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2074 * The endpoint is disabled, let the dwc3_remove_requests()
2075 * handle the cleanup.
2077 if (!dep->endpoint.desc)
2082 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
2083 struct usb_request *request)
2085 struct dwc3_request *req = to_dwc3_request(request);
2086 struct dwc3_request *r = NULL;
2088 struct dwc3_ep *dep = to_dwc3_ep(ep);
2089 struct dwc3 *dwc = dep->dwc;
2091 unsigned long flags;
2094 trace_dwc3_ep_dequeue(req);
2096 spin_lock_irqsave(&dwc->lock, flags);
2098 list_for_each_entry(r, &dep->cancelled_list, list) {
2103 list_for_each_entry(r, &dep->pending_list, list) {
2105 dwc3_gadget_giveback(dep, req, -ECONNRESET);
2110 list_for_each_entry(r, &dep->started_list, list) {
2112 struct dwc3_request *t;
2114 /* wait until it is processed */
2115 dwc3_stop_active_transfer(dep, true, true);
2118 * Remove any started request if the transfer is
2121 list_for_each_entry_safe(r, t, &dep->started_list, list)
2122 dwc3_gadget_move_cancelled_request(r,
2123 DWC3_REQUEST_STATUS_DEQUEUED);
2125 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2131 dev_err(dwc->dev, "request %pK was not queued to %s\n",
2135 spin_unlock_irqrestore(&dwc->lock, flags);
2140 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
2142 struct dwc3_gadget_ep_cmd_params params;
2143 struct dwc3 *dwc = dep->dwc;
2144 struct dwc3_request *req;
2145 struct dwc3_request *tmp;
2148 if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2149 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
2153 memset(¶ms, 0x00, sizeof(params));
2156 struct dwc3_trb *trb;
2158 unsigned int transfer_in_flight;
2159 unsigned int started;
2161 if (dep->number > 1)
2162 trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
2164 trb = &dwc->ep0_trb[dep->trb_enqueue];
2166 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
2167 started = !list_empty(&dep->started_list);
2169 if (!protocol && ((dep->direction && transfer_in_flight) ||
2170 (!dep->direction && started))) {
2174 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
2177 dev_err(dwc->dev, "failed to set STALL on %s\n",
2180 dep->flags |= DWC3_EP_STALL;
2183 * Don't issue CLEAR_STALL command to control endpoints. The
2184 * controller automatically clears the STALL when it receives
2187 if (dep->number <= 1) {
2188 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2192 dwc3_stop_active_transfer(dep, true, true);
2194 list_for_each_entry_safe(req, tmp, &dep->started_list, list)
2195 dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_STALLED);
2197 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING ||
2198 (dep->flags & DWC3_EP_DELAY_STOP)) {
2199 dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
2201 dwc->clear_stall_protocol = dep->number;
2206 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
2208 ret = dwc3_send_clear_stall_ep_cmd(dep);
2210 dev_err(dwc->dev, "failed to clear STALL on %s\n",
2215 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2217 if ((dep->flags & DWC3_EP_DELAY_START) &&
2218 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
2219 __dwc3_gadget_kick_transfer(dep);
2221 dep->flags &= ~DWC3_EP_DELAY_START;
2227 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
2229 struct dwc3_ep *dep = to_dwc3_ep(ep);
2230 struct dwc3 *dwc = dep->dwc;
2232 unsigned long flags;
2236 spin_lock_irqsave(&dwc->lock, flags);
2237 ret = __dwc3_gadget_ep_set_halt(dep, value, false);
2238 spin_unlock_irqrestore(&dwc->lock, flags);
2243 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
2245 struct dwc3_ep *dep = to_dwc3_ep(ep);
2246 struct dwc3 *dwc = dep->dwc;
2247 unsigned long flags;
2250 spin_lock_irqsave(&dwc->lock, flags);
2251 dep->flags |= DWC3_EP_WEDGE;
2253 if (dep->number == 0 || dep->number == 1)
2254 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
2256 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
2257 spin_unlock_irqrestore(&dwc->lock, flags);
2262 /* -------------------------------------------------------------------------- */
2264 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
2265 .bLength = USB_DT_ENDPOINT_SIZE,
2266 .bDescriptorType = USB_DT_ENDPOINT,
2267 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
2270 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
2271 .enable = dwc3_gadget_ep0_enable,
2272 .disable = dwc3_gadget_ep0_disable,
2273 .alloc_request = dwc3_gadget_ep_alloc_request,
2274 .free_request = dwc3_gadget_ep_free_request,
2275 .queue = dwc3_gadget_ep0_queue,
2276 .dequeue = dwc3_gadget_ep_dequeue,
2277 .set_halt = dwc3_gadget_ep0_set_halt,
2278 .set_wedge = dwc3_gadget_ep_set_wedge,
2281 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
2282 .enable = dwc3_gadget_ep_enable,
2283 .disable = dwc3_gadget_ep_disable,
2284 .alloc_request = dwc3_gadget_ep_alloc_request,
2285 .free_request = dwc3_gadget_ep_free_request,
2286 .queue = dwc3_gadget_ep_queue,
2287 .dequeue = dwc3_gadget_ep_dequeue,
2288 .set_halt = dwc3_gadget_ep_set_halt,
2289 .set_wedge = dwc3_gadget_ep_set_wedge,
2292 /* -------------------------------------------------------------------------- */
2294 static void dwc3_gadget_enable_linksts_evts(struct dwc3 *dwc, bool set)
2298 if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2301 reg = dwc3_readl(dwc->regs, DWC3_DEVTEN);
2303 reg |= DWC3_DEVTEN_ULSTCNGEN;
2305 reg &= ~DWC3_DEVTEN_ULSTCNGEN;
2307 dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2310 static int dwc3_gadget_get_frame(struct usb_gadget *g)
2312 struct dwc3 *dwc = gadget_to_dwc(g);
2314 return __dwc3_gadget_get_frame(dwc);
2317 static int __dwc3_gadget_wakeup(struct dwc3 *dwc, bool async)
2327 * According to the Databook Remote wakeup request should
2328 * be issued only when the device is in early suspend state.
2330 * We can check that via USB Link State bits in DSTS register.
2332 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2334 link_state = DWC3_DSTS_USBLNKST(reg);
2336 switch (link_state) {
2337 case DWC3_LINK_STATE_RESET:
2338 case DWC3_LINK_STATE_RX_DET: /* in HS, means Early Suspend */
2339 case DWC3_LINK_STATE_U3: /* in HS, means SUSPEND */
2340 case DWC3_LINK_STATE_U2: /* in HS, means Sleep (L1) */
2341 case DWC3_LINK_STATE_U1:
2342 case DWC3_LINK_STATE_RESUME:
2349 dwc3_gadget_enable_linksts_evts(dwc, true);
2351 ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
2353 dev_err(dwc->dev, "failed to put link in Recovery\n");
2354 dwc3_gadget_enable_linksts_evts(dwc, false);
2358 /* Recent versions do this automatically */
2359 if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
2360 /* write zeroes to Link Change Request */
2361 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2362 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
2363 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2367 * Since link status change events are enabled we will receive
2368 * an U0 event when wakeup is successful. So bail out.
2373 /* poll until Link State changes to ON */
2377 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2379 /* in HS, means ON */
2380 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2384 if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2385 dev_err(dwc->dev, "failed to send remote wakeup\n");
2392 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2394 struct dwc3 *dwc = gadget_to_dwc(g);
2395 unsigned long flags;
2398 if (!dwc->wakeup_configured) {
2399 dev_err(dwc->dev, "remote wakeup not configured\n");
2403 spin_lock_irqsave(&dwc->lock, flags);
2404 if (!dwc->gadget->wakeup_armed) {
2405 dev_err(dwc->dev, "not armed for remote wakeup\n");
2406 spin_unlock_irqrestore(&dwc->lock, flags);
2409 ret = __dwc3_gadget_wakeup(dwc, true);
2411 spin_unlock_irqrestore(&dwc->lock, flags);
2416 static void dwc3_resume_gadget(struct dwc3 *dwc);
2418 static int dwc3_gadget_func_wakeup(struct usb_gadget *g, int intf_id)
2420 struct dwc3 *dwc = gadget_to_dwc(g);
2421 unsigned long flags;
2425 if (!dwc->wakeup_configured) {
2426 dev_err(dwc->dev, "remote wakeup not configured\n");
2430 spin_lock_irqsave(&dwc->lock, flags);
2432 * If the link is in U3, signal for remote wakeup and wait for the
2433 * link to transition to U0 before sending device notification.
2435 link_state = dwc3_gadget_get_link_state(dwc);
2436 if (link_state == DWC3_LINK_STATE_U3) {
2437 ret = __dwc3_gadget_wakeup(dwc, false);
2439 spin_unlock_irqrestore(&dwc->lock, flags);
2442 dwc3_resume_gadget(dwc);
2443 dwc->suspended = false;
2444 dwc->link_state = DWC3_LINK_STATE_U0;
2447 ret = dwc3_send_gadget_generic_command(dwc, DWC3_DGCMD_DEV_NOTIFICATION,
2448 DWC3_DGCMDPAR_DN_FUNC_WAKE |
2449 DWC3_DGCMDPAR_INTF_SEL(intf_id));
2451 dev_err(dwc->dev, "function remote wakeup failed, ret:%d\n", ret);
2453 spin_unlock_irqrestore(&dwc->lock, flags);
2458 static int dwc3_gadget_set_remote_wakeup(struct usb_gadget *g, int set)
2460 struct dwc3 *dwc = gadget_to_dwc(g);
2461 unsigned long flags;
2463 spin_lock_irqsave(&dwc->lock, flags);
2464 dwc->wakeup_configured = !!set;
2465 spin_unlock_irqrestore(&dwc->lock, flags);
2470 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2473 struct dwc3 *dwc = gadget_to_dwc(g);
2474 unsigned long flags;
2476 spin_lock_irqsave(&dwc->lock, flags);
2477 g->is_selfpowered = !!is_selfpowered;
2478 spin_unlock_irqrestore(&dwc->lock, flags);
2483 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2487 for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2488 struct dwc3_ep *dep;
2490 dep = dwc->eps[epnum];
2494 dwc3_remove_requests(dwc, dep, -ESHUTDOWN);
2498 static void __dwc3_gadget_set_ssp_rate(struct dwc3 *dwc)
2500 enum usb_ssp_rate ssp_rate = dwc->gadget_ssp_rate;
2503 if (ssp_rate == USB_SSP_GEN_UNKNOWN)
2504 ssp_rate = dwc->max_ssp_rate;
2506 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2507 reg &= ~DWC3_DCFG_SPEED_MASK;
2508 reg &= ~DWC3_DCFG_NUMLANES(~0);
2510 if (ssp_rate == USB_SSP_GEN_1x2)
2511 reg |= DWC3_DCFG_SUPERSPEED;
2512 else if (dwc->max_ssp_rate != USB_SSP_GEN_1x2)
2513 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2515 if (ssp_rate != USB_SSP_GEN_2x1 &&
2516 dwc->max_ssp_rate != USB_SSP_GEN_2x1)
2517 reg |= DWC3_DCFG_NUMLANES(1);
2519 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2522 static void __dwc3_gadget_set_speed(struct dwc3 *dwc)
2524 enum usb_device_speed speed;
2527 speed = dwc->gadget_max_speed;
2528 if (speed == USB_SPEED_UNKNOWN || speed > dwc->maximum_speed)
2529 speed = dwc->maximum_speed;
2531 if (speed == USB_SPEED_SUPER_PLUS &&
2532 DWC3_IP_IS(DWC32)) {
2533 __dwc3_gadget_set_ssp_rate(dwc);
2537 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2538 reg &= ~(DWC3_DCFG_SPEED_MASK);
2541 * WORKAROUND: DWC3 revision < 2.20a have an issue
2542 * which would cause metastability state on Run/Stop
2543 * bit if we try to force the IP to USB2-only mode.
2545 * Because of that, we cannot configure the IP to any
2546 * speed other than the SuperSpeed
2550 * STAR#9000525659: Clock Domain Crossing on DCTL in
2553 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2554 !dwc->dis_metastability_quirk) {
2555 reg |= DWC3_DCFG_SUPERSPEED;
2558 case USB_SPEED_FULL:
2559 reg |= DWC3_DCFG_FULLSPEED;
2561 case USB_SPEED_HIGH:
2562 reg |= DWC3_DCFG_HIGHSPEED;
2564 case USB_SPEED_SUPER:
2565 reg |= DWC3_DCFG_SUPERSPEED;
2567 case USB_SPEED_SUPER_PLUS:
2568 if (DWC3_IP_IS(DWC3))
2569 reg |= DWC3_DCFG_SUPERSPEED;
2571 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2574 dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2576 if (DWC3_IP_IS(DWC3))
2577 reg |= DWC3_DCFG_SUPERSPEED;
2579 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2583 if (DWC3_IP_IS(DWC32) &&
2584 speed > USB_SPEED_UNKNOWN &&
2585 speed < USB_SPEED_SUPER_PLUS)
2586 reg &= ~DWC3_DCFG_NUMLANES(~0);
2588 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2591 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on)
2596 if (pm_runtime_suspended(dwc->dev))
2599 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2601 if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2602 reg &= ~DWC3_DCTL_TRGTULST_MASK;
2603 reg |= DWC3_DCTL_TRGTULST_RX_DET;
2606 if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2607 reg &= ~DWC3_DCTL_KEEP_CONNECT;
2608 reg |= DWC3_DCTL_RUN_STOP;
2610 __dwc3_gadget_set_speed(dwc);
2611 dwc->pullups_connected = true;
2613 reg &= ~DWC3_DCTL_RUN_STOP;
2615 dwc->pullups_connected = false;
2618 dwc3_gadget_dctl_write_safe(dwc, reg);
2621 usleep_range(1000, 2000);
2622 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2623 reg &= DWC3_DSTS_DEVCTRLHLT;
2624 } while (--timeout && !(!is_on ^ !reg));
2632 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2633 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2634 static int __dwc3_gadget_start(struct dwc3 *dwc);
2636 static int dwc3_gadget_soft_disconnect(struct dwc3 *dwc)
2638 unsigned long flags;
2641 spin_lock_irqsave(&dwc->lock, flags);
2642 dwc->connected = false;
2645 * Attempt to end pending SETUP status phase, and not wait for the
2646 * function to do so.
2648 if (dwc->delayed_status)
2649 dwc3_ep0_send_delayed_status(dwc);
2652 * In the Synopsys DesignWare Cores USB3 Databook Rev. 3.30a
2653 * Section 4.1.8 Table 4-7, it states that for a device-initiated
2654 * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2655 * command for any active transfers" before clearing the RunStop
2658 dwc3_stop_active_transfers(dwc);
2659 spin_unlock_irqrestore(&dwc->lock, flags);
2662 * Per databook, when we want to stop the gadget, if a control transfer
2663 * is still in process, complete it and get the core into setup phase.
2664 * In case the host is unresponsive to a SETUP transaction, forcefully
2665 * stall the transfer, and move back to the SETUP phase, so that any
2666 * pending endxfers can be executed.
2668 if (dwc->ep0state != EP0_SETUP_PHASE) {
2669 reinit_completion(&dwc->ep0_in_setup);
2671 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2672 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2674 dev_warn(dwc->dev, "wait for SETUP phase timed out\n");
2675 spin_lock_irqsave(&dwc->lock, flags);
2676 dwc3_ep0_reset_state(dwc);
2677 spin_unlock_irqrestore(&dwc->lock, flags);
2682 * Note: if the GEVNTCOUNT indicates events in the event buffer, the
2683 * driver needs to acknowledge them before the controller can halt.
2684 * Simply let the interrupt handler acknowledges and handle the
2685 * remaining event generated by the controller while polling for
2688 ret = dwc3_gadget_run_stop(dwc, false);
2691 * Stop the gadget after controller is halted, so that if needed, the
2692 * events to update EP0 state can still occur while the run/stop
2693 * routine polls for the halted state. DEVTEN is cleared as part of
2696 spin_lock_irqsave(&dwc->lock, flags);
2697 __dwc3_gadget_stop(dwc);
2698 spin_unlock_irqrestore(&dwc->lock, flags);
2703 static int dwc3_gadget_soft_connect(struct dwc3 *dwc)
2706 * In the Synopsys DWC_usb31 1.90a programming guide section
2707 * 4.1.9, it specifies that for a reconnect after a
2708 * device-initiated disconnect requires a core soft reset
2709 * (DCTL.CSftRst) before enabling the run/stop bit.
2711 dwc3_core_soft_reset(dwc);
2713 dwc3_event_buffers_setup(dwc);
2714 __dwc3_gadget_start(dwc);
2715 return dwc3_gadget_run_stop(dwc, true);
2718 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2720 struct dwc3 *dwc = gadget_to_dwc(g);
2725 dwc->softconnect = is_on;
2728 * Avoid issuing a runtime resume if the device is already in the
2729 * suspended state during gadget disconnect. DWC3 gadget was already
2730 * halted/stopped during runtime suspend.
2733 pm_runtime_barrier(dwc->dev);
2734 if (pm_runtime_suspended(dwc->dev))
2739 * Check the return value for successful resume, or error. For a
2740 * successful resume, the DWC3 runtime PM resume routine will handle
2741 * the run stop sequence, so avoid duplicate operations here.
2743 ret = pm_runtime_get_sync(dwc->dev);
2744 if (!ret || ret < 0) {
2745 pm_runtime_put(dwc->dev);
2749 if (dwc->pullups_connected == is_on) {
2750 pm_runtime_put(dwc->dev);
2754 synchronize_irq(dwc->irq_gadget);
2757 ret = dwc3_gadget_soft_disconnect(dwc);
2759 ret = dwc3_gadget_soft_connect(dwc);
2761 pm_runtime_put(dwc->dev);
2766 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2770 /* Enable all but Start and End of Frame IRQs */
2771 reg = (DWC3_DEVTEN_EVNTOVERFLOWEN |
2772 DWC3_DEVTEN_CMDCMPLTEN |
2773 DWC3_DEVTEN_ERRTICERREN |
2774 DWC3_DEVTEN_WKUPEVTEN |
2775 DWC3_DEVTEN_CONNECTDONEEN |
2776 DWC3_DEVTEN_USBRSTEN |
2777 DWC3_DEVTEN_DISCONNEVTEN);
2779 if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2780 reg |= DWC3_DEVTEN_ULSTCNGEN;
2782 /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2783 if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2784 reg |= DWC3_DEVTEN_U3L2L1SUSPEN;
2786 dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2789 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2791 /* mask all interrupts */
2792 dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2795 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2796 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2799 * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2800 * @dwc: pointer to our context structure
2802 * The following looks like complex but it's actually very simple. In order to
2803 * calculate the number of packets we can burst at once on OUT transfers, we're
2804 * gonna use RxFIFO size.
2806 * To calculate RxFIFO size we need two numbers:
2807 * MDWIDTH = size, in bits, of the internal memory bus
2808 * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2810 * Given these two numbers, the formula is simple:
2812 * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2814 * 24 bytes is for 3x SETUP packets
2815 * 16 bytes is a clock domain crossing tolerance
2817 * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2819 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2826 ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2827 mdwidth = dwc3_mdwidth(dwc);
2829 nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2830 nump = min_t(u32, nump, 16);
2833 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2834 reg &= ~DWC3_DCFG_NUMP_MASK;
2835 reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2836 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2839 static int __dwc3_gadget_start(struct dwc3 *dwc)
2841 struct dwc3_ep *dep;
2846 * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2847 * the core supports IMOD, disable it.
2849 if (dwc->imod_interval) {
2850 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2851 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2852 } else if (dwc3_has_imod(dwc)) {
2853 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2857 * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2858 * field instead of letting dwc3 itself calculate that automatically.
2860 * This way, we maximize the chances that we'll be able to get several
2861 * bursts of data without going through any sort of endpoint throttling.
2863 reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2864 if (DWC3_IP_IS(DWC3))
2865 reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2867 reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2869 dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2871 dwc3_gadget_setup_nump(dwc);
2874 * Currently the controller handles single stream only. So, Ignore
2875 * Packet Pending bit for stream selection and don't search for another
2876 * stream if the host sends Data Packet with PP=0 (for OUT direction) or
2877 * ACK with NumP=0 and PP=0 (for IN direction). This slightly improves
2878 * the stream performance.
2880 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2881 reg |= DWC3_DCFG_IGNSTRMPP;
2882 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2884 /* Enable MST by default if the device is capable of MST */
2885 if (DWC3_MST_CAPABLE(&dwc->hwparams)) {
2886 reg = dwc3_readl(dwc->regs, DWC3_DCFG1);
2887 reg &= ~DWC3_DCFG1_DIS_MST_ENH;
2888 dwc3_writel(dwc->regs, DWC3_DCFG1, reg);
2891 /* Start with SuperSpeed Default */
2892 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2896 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2898 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2904 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2906 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2910 /* begin to receive SETUP packets */
2911 dwc->ep0state = EP0_SETUP_PHASE;
2912 dwc->ep0_bounced = false;
2913 dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2914 dwc->delayed_status = false;
2915 dwc3_ep0_out_start(dwc);
2917 dwc3_gadget_enable_irq(dwc);
2922 __dwc3_gadget_ep_disable(dwc->eps[0]);
2928 static int dwc3_gadget_start(struct usb_gadget *g,
2929 struct usb_gadget_driver *driver)
2931 struct dwc3 *dwc = gadget_to_dwc(g);
2932 unsigned long flags;
2936 irq = dwc->irq_gadget;
2937 ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2938 IRQF_SHARED, "dwc3", dwc->ev_buf);
2940 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2945 spin_lock_irqsave(&dwc->lock, flags);
2946 dwc->gadget_driver = driver;
2947 spin_unlock_irqrestore(&dwc->lock, flags);
2952 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2954 dwc3_gadget_disable_irq(dwc);
2955 __dwc3_gadget_ep_disable(dwc->eps[0]);
2956 __dwc3_gadget_ep_disable(dwc->eps[1]);
2959 static int dwc3_gadget_stop(struct usb_gadget *g)
2961 struct dwc3 *dwc = gadget_to_dwc(g);
2962 unsigned long flags;
2964 spin_lock_irqsave(&dwc->lock, flags);
2965 dwc->gadget_driver = NULL;
2966 dwc->max_cfg_eps = 0;
2967 spin_unlock_irqrestore(&dwc->lock, flags);
2969 free_irq(dwc->irq_gadget, dwc->ev_buf);
2974 static void dwc3_gadget_config_params(struct usb_gadget *g,
2975 struct usb_dcd_config_params *params)
2977 struct dwc3 *dwc = gadget_to_dwc(g);
2979 params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2980 params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2982 /* Recommended BESL */
2983 if (!dwc->dis_enblslpm_quirk) {
2985 * If the recommended BESL baseline is 0 or if the BESL deep is
2986 * less than 2, Microsoft's Windows 10 host usb stack will issue
2987 * a usb reset immediately after it receives the extended BOS
2988 * descriptor and the enumeration will fail. To maintain
2989 * compatibility with the Windows' usb stack, let's set the
2990 * recommended BESL baseline to 1 and clamp the BESL deep to be
2993 params->besl_baseline = 1;
2994 if (dwc->is_utmi_l1_suspend)
2996 clamp_t(u8, dwc->hird_threshold, 2, 15);
2999 /* U1 Device exit Latency */
3000 if (dwc->dis_u1_entry_quirk)
3001 params->bU1devExitLat = 0;
3003 params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
3005 /* U2 Device exit Latency */
3006 if (dwc->dis_u2_entry_quirk)
3007 params->bU2DevExitLat = 0;
3009 params->bU2DevExitLat =
3010 cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
3013 static void dwc3_gadget_set_speed(struct usb_gadget *g,
3014 enum usb_device_speed speed)
3016 struct dwc3 *dwc = gadget_to_dwc(g);
3017 unsigned long flags;
3019 spin_lock_irqsave(&dwc->lock, flags);
3020 dwc->gadget_max_speed = speed;
3021 spin_unlock_irqrestore(&dwc->lock, flags);
3024 static void dwc3_gadget_set_ssp_rate(struct usb_gadget *g,
3025 enum usb_ssp_rate rate)
3027 struct dwc3 *dwc = gadget_to_dwc(g);
3028 unsigned long flags;
3030 spin_lock_irqsave(&dwc->lock, flags);
3031 dwc->gadget_max_speed = USB_SPEED_SUPER_PLUS;
3032 dwc->gadget_ssp_rate = rate;
3033 spin_unlock_irqrestore(&dwc->lock, flags);
3036 static int dwc3_gadget_vbus_draw(struct usb_gadget *g, unsigned int mA)
3038 struct dwc3 *dwc = gadget_to_dwc(g);
3039 union power_supply_propval val = {0};
3043 return usb_phy_set_power(dwc->usb2_phy, mA);
3048 val.intval = 1000 * mA;
3049 ret = power_supply_set_property(dwc->usb_psy, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
3055 * dwc3_gadget_check_config - ensure dwc3 can support the USB configuration
3056 * @g: pointer to the USB gadget
3058 * Used to record the maximum number of endpoints being used in a USB composite
3059 * device. (across all configurations) This is to be used in the calculation
3060 * of the TXFIFO sizes when resizing internal memory for individual endpoints.
3061 * It will help ensured that the resizing logic reserves enough space for at
3062 * least one max packet.
3064 static int dwc3_gadget_check_config(struct usb_gadget *g)
3066 struct dwc3 *dwc = gadget_to_dwc(g);
3072 if (!dwc->do_fifo_resize)
3075 list_for_each_entry(ep, &g->ep_list, ep_list) {
3076 /* Only interested in the IN endpoints */
3077 if (ep->claimed && (ep->address & USB_DIR_IN))
3081 if (ep_num <= dwc->max_cfg_eps)
3084 /* Update the max number of eps in the composition */
3085 dwc->max_cfg_eps = ep_num;
3087 fifo_size = dwc3_gadget_calc_tx_fifo_size(dwc, dwc->max_cfg_eps);
3088 /* Based on the equation, increment by one for every ep */
3089 fifo_size += dwc->max_cfg_eps;
3091 /* Check if we can fit a single fifo per endpoint */
3092 ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
3093 if (fifo_size > ram1_depth)
3099 static void dwc3_gadget_async_callbacks(struct usb_gadget *g, bool enable)
3101 struct dwc3 *dwc = gadget_to_dwc(g);
3102 unsigned long flags;
3104 spin_lock_irqsave(&dwc->lock, flags);
3105 dwc->async_callbacks = enable;
3106 spin_unlock_irqrestore(&dwc->lock, flags);
3109 static const struct usb_gadget_ops dwc3_gadget_ops = {
3110 .get_frame = dwc3_gadget_get_frame,
3111 .wakeup = dwc3_gadget_wakeup,
3112 .func_wakeup = dwc3_gadget_func_wakeup,
3113 .set_remote_wakeup = dwc3_gadget_set_remote_wakeup,
3114 .set_selfpowered = dwc3_gadget_set_selfpowered,
3115 .pullup = dwc3_gadget_pullup,
3116 .udc_start = dwc3_gadget_start,
3117 .udc_stop = dwc3_gadget_stop,
3118 .udc_set_speed = dwc3_gadget_set_speed,
3119 .udc_set_ssp_rate = dwc3_gadget_set_ssp_rate,
3120 .get_config_params = dwc3_gadget_config_params,
3121 .vbus_draw = dwc3_gadget_vbus_draw,
3122 .check_config = dwc3_gadget_check_config,
3123 .udc_async_callbacks = dwc3_gadget_async_callbacks,
3126 /* -------------------------------------------------------------------------- */
3128 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
3130 struct dwc3 *dwc = dep->dwc;
3132 usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
3133 dep->endpoint.maxburst = 1;
3134 dep->endpoint.ops = &dwc3_gadget_ep0_ops;
3135 if (!dep->direction)
3136 dwc->gadget->ep0 = &dep->endpoint;
3138 dep->endpoint.caps.type_control = true;
3143 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
3145 struct dwc3 *dwc = dep->dwc;
3150 mdwidth = dwc3_mdwidth(dwc);
3152 /* MDWIDTH is represented in bits, we need it in bytes */
3155 size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
3156 if (DWC3_IP_IS(DWC3))
3157 size = DWC3_GTXFIFOSIZ_TXFDEP(size);
3159 size = DWC31_GTXFIFOSIZ_TXFDEP(size);
3162 * maxpacket size is determined as part of the following, after assuming
3163 * a mult value of one maxpacket:
3164 * DWC3 revision 280A and prior:
3165 * fifo_size = mult * (max_packet / mdwidth) + 1;
3166 * maxpacket = mdwidth * (fifo_size - 1);
3168 * DWC3 revision 290A and onwards:
3169 * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
3170 * maxpacket = mdwidth * ((fifo_size - 1) - 1) - mdwidth;
3172 if (DWC3_VER_IS_PRIOR(DWC3, 290A))
3173 maxpacket = mdwidth * (size - 1);
3175 maxpacket = mdwidth * ((size - 1) - 1) - mdwidth;
3177 /* Functionally, space for one max packet is sufficient */
3178 size = min_t(int, maxpacket, 1024);
3179 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3181 dep->endpoint.max_streams = 16;
3182 dep->endpoint.ops = &dwc3_gadget_ep_ops;
3183 list_add_tail(&dep->endpoint.ep_list,
3184 &dwc->gadget->ep_list);
3185 dep->endpoint.caps.type_iso = true;
3186 dep->endpoint.caps.type_bulk = true;
3187 dep->endpoint.caps.type_int = true;
3189 return dwc3_alloc_trb_pool(dep);
3192 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
3194 struct dwc3 *dwc = dep->dwc;
3198 mdwidth = dwc3_mdwidth(dwc);
3200 /* MDWIDTH is represented in bits, convert to bytes */
3203 /* All OUT endpoints share a single RxFIFO space */
3204 size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
3205 if (DWC3_IP_IS(DWC3))
3206 size = DWC3_GRXFIFOSIZ_RXFDEP(size);
3208 size = DWC31_GRXFIFOSIZ_RXFDEP(size);
3210 /* FIFO depth is in MDWDITH bytes */
3214 * To meet performance requirement, a minimum recommended RxFIFO size
3215 * is defined as follow:
3216 * RxFIFO size >= (3 x MaxPacketSize) +
3217 * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
3219 * Then calculate the max packet limit as below.
3221 size -= (3 * 8) + 16;
3227 usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3228 dep->endpoint.max_streams = 16;
3229 dep->endpoint.ops = &dwc3_gadget_ep_ops;
3230 list_add_tail(&dep->endpoint.ep_list,
3231 &dwc->gadget->ep_list);
3232 dep->endpoint.caps.type_iso = true;
3233 dep->endpoint.caps.type_bulk = true;
3234 dep->endpoint.caps.type_int = true;
3236 return dwc3_alloc_trb_pool(dep);
3239 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
3241 struct dwc3_ep *dep;
3242 bool direction = epnum & 1;
3244 u8 num = epnum >> 1;
3246 dep = kzalloc(sizeof(*dep), GFP_KERNEL);
3251 dep->number = epnum;
3252 dep->direction = direction;
3253 dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
3254 dwc->eps[epnum] = dep;
3256 dep->start_cmd_status = 0;
3258 snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
3259 direction ? "in" : "out");
3261 dep->endpoint.name = dep->name;
3263 if (!(dep->number > 1)) {
3264 dep->endpoint.desc = &dwc3_gadget_ep0_desc;
3265 dep->endpoint.comp_desc = NULL;
3269 ret = dwc3_gadget_init_control_endpoint(dep);
3271 ret = dwc3_gadget_init_in_endpoint(dep);
3273 ret = dwc3_gadget_init_out_endpoint(dep);
3278 dep->endpoint.caps.dir_in = direction;
3279 dep->endpoint.caps.dir_out = !direction;
3281 INIT_LIST_HEAD(&dep->pending_list);
3282 INIT_LIST_HEAD(&dep->started_list);
3283 INIT_LIST_HEAD(&dep->cancelled_list);
3285 dwc3_debugfs_create_endpoint_dir(dep);
3290 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
3294 INIT_LIST_HEAD(&dwc->gadget->ep_list);
3296 for (epnum = 0; epnum < total; epnum++) {
3299 ret = dwc3_gadget_init_endpoint(dwc, epnum);
3307 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
3309 struct dwc3_ep *dep;
3312 for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3313 dep = dwc->eps[epnum];
3317 * Physical endpoints 0 and 1 are special; they form the
3318 * bi-directional USB endpoint 0.
3320 * For those two physical endpoints, we don't allocate a TRB
3321 * pool nor do we add them the endpoints list. Due to that, we
3322 * shouldn't do these two operations otherwise we would end up
3323 * with all sorts of bugs when removing dwc3.ko.
3325 if (epnum != 0 && epnum != 1) {
3326 dwc3_free_trb_pool(dep);
3327 list_del(&dep->endpoint.ep_list);
3330 dwc3_debugfs_remove_endpoint_dir(dep);
3335 /* -------------------------------------------------------------------------- */
3337 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
3338 struct dwc3_request *req, struct dwc3_trb *trb,
3339 const struct dwc3_event_depevt *event, int status, int chain)
3343 dwc3_ep_inc_deq(dep);
3345 trace_dwc3_complete_trb(dep, trb);
3349 * If we're in the middle of series of chained TRBs and we
3350 * receive a short transfer along the way, DWC3 will skip
3351 * through all TRBs including the last TRB in the chain (the
3352 * where CHN bit is zero. DWC3 will also avoid clearing HWO
3353 * bit and SW has to do it manually.
3355 * We're going to do that here to avoid problems of HW trying
3356 * to use bogus TRBs for transfers.
3358 if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
3359 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3362 * For isochronous transfers, the first TRB in a service interval must
3363 * have the Isoc-First type. Track and report its interval frame number.
3365 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3366 (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
3367 unsigned int frame_number;
3369 frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
3370 frame_number &= ~(dep->interval - 1);
3371 req->request.frame_number = frame_number;
3375 * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
3376 * this TRB points to the bounce buffer address, it's a MPS alignment
3377 * TRB. Don't add it to req->remaining calculation.
3379 if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
3380 trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
3381 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3385 count = trb->size & DWC3_TRB_SIZE_MASK;
3386 req->remaining += count;
3388 if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
3391 if (event->status & DEPEVT_STATUS_SHORT && !chain)
3394 if ((trb->ctrl & DWC3_TRB_CTRL_ISP_IMI) &&
3395 DWC3_TRB_SIZE_TRBSTS(trb->size) == DWC3_TRBSTS_MISSED_ISOC)
3398 if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
3399 (trb->ctrl & DWC3_TRB_CTRL_LST))
3405 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
3406 struct dwc3_request *req, const struct dwc3_event_depevt *event,
3409 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3410 struct scatterlist *sg = req->sg;
3411 struct scatterlist *s;
3412 unsigned int num_queued = req->num_queued_sgs;
3416 for_each_sg(sg, s, num_queued, i) {
3417 trb = &dep->trb_pool[dep->trb_dequeue];
3419 req->sg = sg_next(s);
3420 req->num_queued_sgs--;
3422 ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
3423 trb, event, status, true);
3431 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
3432 struct dwc3_request *req, const struct dwc3_event_depevt *event,
3435 struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3437 return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
3438 event, status, false);
3441 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
3443 return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
3446 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
3447 const struct dwc3_event_depevt *event,
3448 struct dwc3_request *req, int status)
3453 if (req->request.num_mapped_sgs)
3454 ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
3457 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3460 req->request.actual = req->request.length - req->remaining;
3462 if (!dwc3_gadget_ep_request_completed(req))
3465 if (req->needs_extra_trb) {
3466 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3468 req->needs_extra_trb = false;
3472 * The event status only reflects the status of the TRB with IOC set.
3473 * For the requests that don't set interrupt on completion, the driver
3474 * needs to check and return the status of the completed TRBs associated
3475 * with the request. Use the status of the last TRB of the request.
3477 if (req->request.no_interrupt) {
3478 struct dwc3_trb *trb;
3480 trb = dwc3_ep_prev_trb(dep, dep->trb_dequeue);
3481 switch (DWC3_TRB_SIZE_TRBSTS(trb->size)) {
3482 case DWC3_TRBSTS_MISSED_ISOC:
3483 /* Isoc endpoint only */
3484 request_status = -EXDEV;
3486 case DWC3_TRB_STS_XFER_IN_PROG:
3487 /* Applicable when End Transfer with ForceRM=0 */
3488 case DWC3_TRBSTS_SETUP_PENDING:
3489 /* Control endpoint only */
3490 case DWC3_TRBSTS_OK:
3496 request_status = status;
3499 dwc3_gadget_giveback(dep, req, request_status);
3505 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
3506 const struct dwc3_event_depevt *event, int status)
3508 struct dwc3_request *req;
3510 while (!list_empty(&dep->started_list)) {
3513 req = next_request(&dep->started_list);
3514 ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
3519 * The endpoint is disabled, let the dwc3_remove_requests()
3520 * handle the cleanup.
3522 if (!dep->endpoint.desc)
3527 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
3529 struct dwc3_request *req;
3530 struct dwc3 *dwc = dep->dwc;
3532 if (!dep->endpoint.desc || !dwc->pullups_connected ||
3536 if (!list_empty(&dep->pending_list))
3540 * We only need to check the first entry of the started list. We can
3541 * assume the completed requests are removed from the started list.
3543 req = next_request(&dep->started_list);
3547 return !dwc3_gadget_ep_request_completed(req);
3550 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
3551 const struct dwc3_event_depevt *event)
3553 dep->frame_number = event->parameters;
3556 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
3557 const struct dwc3_event_depevt *event, int status)
3559 struct dwc3 *dwc = dep->dwc;
3560 bool no_started_trb = true;
3562 dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
3564 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3567 if (!dep->endpoint.desc)
3568 return no_started_trb;
3570 if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3571 list_empty(&dep->started_list) &&
3572 (list_empty(&dep->pending_list) || status == -EXDEV))
3573 dwc3_stop_active_transfer(dep, true, true);
3574 else if (dwc3_gadget_ep_should_continue(dep))
3575 if (__dwc3_gadget_kick_transfer(dep) == 0)
3576 no_started_trb = false;
3580 * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
3581 * See dwc3_gadget_linksts_change_interrupt() for 1st half.
3583 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3587 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
3590 if (!(dep->flags & DWC3_EP_ENABLED))
3593 if (!list_empty(&dep->started_list))
3594 return no_started_trb;
3597 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3599 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
3604 return no_started_trb;
3607 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
3608 const struct dwc3_event_depevt *event)
3612 if (!dep->endpoint.desc)
3615 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
3616 dwc3_gadget_endpoint_frame_from_event(dep, event);
3618 if (event->status & DEPEVT_STATUS_BUSERR)
3619 status = -ECONNRESET;
3621 if (event->status & DEPEVT_STATUS_MISSED_ISOC)
3624 dwc3_gadget_endpoint_trbs_complete(dep, event, status);
3627 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
3628 const struct dwc3_event_depevt *event)
3632 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3634 if (event->status & DEPEVT_STATUS_BUSERR)
3635 status = -ECONNRESET;
3637 if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
3638 dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
3641 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
3642 const struct dwc3_event_depevt *event)
3644 dwc3_gadget_endpoint_frame_from_event(dep, event);
3647 * The XferNotReady event is generated only once before the endpoint
3648 * starts. It will be generated again when END_TRANSFER command is
3649 * issued. For some controller versions, the XferNotReady event may be
3650 * generated while the END_TRANSFER command is still in process. Ignore
3651 * it and wait for the next XferNotReady event after the command is
3654 if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3657 (void) __dwc3_gadget_start_isoc(dep);
3660 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
3661 const struct dwc3_event_depevt *event)
3663 u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
3665 if (cmd != DWC3_DEPCMD_ENDTRANSFER)
3669 * The END_TRANSFER command will cause the controller to generate a
3670 * NoStream Event, and it's not due to the host DP NoStream rejection.
3671 * Ignore the next NoStream event.
3673 if (dep->stream_capable)
3674 dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3676 dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
3677 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3678 dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3680 if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3681 struct dwc3 *dwc = dep->dwc;
3683 dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3684 if (dwc3_send_clear_stall_ep_cmd(dep)) {
3685 struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3687 dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3688 if (dwc->delayed_status)
3689 __dwc3_gadget_ep0_set_halt(ep0, 1);
3693 dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3694 if (dwc->clear_stall_protocol == dep->number)
3695 dwc3_ep0_send_delayed_status(dwc);
3698 if ((dep->flags & DWC3_EP_DELAY_START) &&
3699 !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3700 __dwc3_gadget_kick_transfer(dep);
3702 dep->flags &= ~DWC3_EP_DELAY_START;
3705 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3706 const struct dwc3_event_depevt *event)
3708 struct dwc3 *dwc = dep->dwc;
3710 if (event->status == DEPEVT_STREAMEVT_FOUND) {
3711 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3715 /* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3716 switch (event->parameters) {
3717 case DEPEVT_STREAM_PRIME:
3719 * If the host can properly transition the endpoint state from
3720 * idle to prime after a NoStream rejection, there's no need to
3721 * force restarting the endpoint to reinitiate the stream. To
3722 * simplify the check, assume the host follows the USB spec if
3723 * it primed the endpoint more than once.
3725 if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3726 if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3727 dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3729 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3733 case DEPEVT_STREAM_NOSTREAM:
3734 if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3735 !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3736 (!DWC3_MST_CAPABLE(&dwc->hwparams) &&
3737 !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)))
3741 * If the host rejects a stream due to no active stream, by the
3742 * USB and xHCI spec, the endpoint will be put back to idle
3743 * state. When the host is ready (buffer added/updated), it will
3744 * prime the endpoint to inform the usb device controller. This
3745 * triggers the device controller to issue ERDY to restart the
3746 * stream. However, some hosts don't follow this and keep the
3747 * endpoint in the idle state. No prime will come despite host
3748 * streams are updated, and the device controller will not be
3749 * triggered to generate ERDY to move the next stream data. To
3750 * workaround this and maintain compatibility with various
3751 * hosts, force to reinitiate the stream until the host is ready
3752 * instead of waiting for the host to prime the endpoint.
3754 if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3755 unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3757 dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3759 dep->flags |= DWC3_EP_DELAY_START;
3760 dwc3_stop_active_transfer(dep, true, true);
3767 dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3770 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3771 const struct dwc3_event_depevt *event)
3773 struct dwc3_ep *dep;
3774 u8 epnum = event->endpoint_number;
3776 dep = dwc->eps[epnum];
3778 if (!(dep->flags & DWC3_EP_ENABLED)) {
3779 if ((epnum > 1) && !(dep->flags & DWC3_EP_TRANSFER_STARTED))
3782 /* Handle only EPCMDCMPLT when EP disabled */
3783 if ((event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT) &&
3784 !(epnum <= 1 && event->endpoint_event == DWC3_DEPEVT_XFERCOMPLETE))
3788 if (epnum == 0 || epnum == 1) {
3789 dwc3_ep0_interrupt(dwc, event);
3793 switch (event->endpoint_event) {
3794 case DWC3_DEPEVT_XFERINPROGRESS:
3795 dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3797 case DWC3_DEPEVT_XFERNOTREADY:
3798 dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3800 case DWC3_DEPEVT_EPCMDCMPLT:
3801 dwc3_gadget_endpoint_command_complete(dep, event);
3803 case DWC3_DEPEVT_XFERCOMPLETE:
3804 dwc3_gadget_endpoint_transfer_complete(dep, event);
3806 case DWC3_DEPEVT_STREAMEVT:
3807 dwc3_gadget_endpoint_stream_event(dep, event);
3809 case DWC3_DEPEVT_RXTXFIFOEVT:
3814 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3816 if (dwc->async_callbacks && dwc->gadget_driver->disconnect) {
3817 spin_unlock(&dwc->lock);
3818 dwc->gadget_driver->disconnect(dwc->gadget);
3819 spin_lock(&dwc->lock);
3823 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3825 if (dwc->async_callbacks && dwc->gadget_driver->suspend) {
3826 spin_unlock(&dwc->lock);
3827 dwc->gadget_driver->suspend(dwc->gadget);
3828 spin_lock(&dwc->lock);
3832 static void dwc3_resume_gadget(struct dwc3 *dwc)
3834 if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3835 spin_unlock(&dwc->lock);
3836 dwc->gadget_driver->resume(dwc->gadget);
3837 spin_lock(&dwc->lock);
3841 static void dwc3_reset_gadget(struct dwc3 *dwc)
3843 if (!dwc->gadget_driver)
3846 if (dwc->async_callbacks && dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3847 spin_unlock(&dwc->lock);
3848 usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3849 spin_lock(&dwc->lock);
3853 void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3856 struct dwc3 *dwc = dep->dwc;
3859 * Only issue End Transfer command to the control endpoint of a started
3860 * Data Phase. Typically we should only do so in error cases such as
3861 * invalid/unexpected direction as described in the control transfer
3862 * flow of the programming guide.
3864 if (dep->number <= 1 && dwc->ep0state != EP0_DATA_PHASE)
3867 if (interrupt && (dep->flags & DWC3_EP_DELAY_STOP))
3870 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3871 (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3875 * If a Setup packet is received but yet to DMA out, the controller will
3876 * not process the End Transfer command of any endpoint. Polling of its
3877 * DEPCMD.CmdAct may block setting up TRB for Setup packet, causing a
3878 * timeout. Delay issuing the End Transfer command until the Setup TRB is
3881 if (dwc->ep0state != EP0_SETUP_PHASE && !dwc->delayed_status) {
3882 dep->flags |= DWC3_EP_DELAY_STOP;
3887 * NOTICE: We are violating what the Databook says about the
3888 * EndTransfer command. Ideally we would _always_ wait for the
3889 * EndTransfer Command Completion IRQ, but that's causing too
3890 * much trouble synchronizing between us and gadget driver.
3892 * We have discussed this with the IP Provider and it was
3893 * suggested to giveback all requests here.
3895 * Note also that a similar handling was tested by Synopsys
3896 * (thanks a lot Paul) and nothing bad has come out of it.
3897 * In short, what we're doing is issuing EndTransfer with
3898 * CMDIOC bit set and delay kicking transfer until the
3899 * EndTransfer command had completed.
3901 * As of IP version 3.10a of the DWC_usb3 IP, the controller
3902 * supports a mode to work around the above limitation. The
3903 * software can poll the CMDACT bit in the DEPCMD register
3904 * after issuing a EndTransfer command. This mode is enabled
3905 * by writing GUCTL2[14]. This polling is already done in the
3906 * dwc3_send_gadget_ep_cmd() function so if the mode is
3907 * enabled, the EndTransfer command will have completed upon
3908 * returning from this function.
3910 * This mode is NOT available on the DWC_usb31 IP. In this
3911 * case, if the IOC bit is not set, then delay by 1ms
3912 * after issuing the EndTransfer command. This allows for the
3913 * controller to handle the command completely before DWC3
3914 * remove requests attempts to unmap USB request buffers.
3917 __dwc3_stop_active_transfer(dep, force, interrupt);
3920 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3924 for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3925 struct dwc3_ep *dep;
3928 dep = dwc->eps[epnum];
3932 if (!(dep->flags & DWC3_EP_STALL))
3935 dep->flags &= ~DWC3_EP_STALL;
3937 ret = dwc3_send_clear_stall_ep_cmd(dep);
3942 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3946 dwc->suspended = false;
3948 dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3950 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3951 reg &= ~DWC3_DCTL_INITU1ENA;
3952 reg &= ~DWC3_DCTL_INITU2ENA;
3953 dwc3_gadget_dctl_write_safe(dwc, reg);
3955 dwc->connected = false;
3957 dwc3_disconnect_gadget(dwc);
3959 dwc->gadget->speed = USB_SPEED_UNKNOWN;
3960 dwc->setup_packet_pending = false;
3961 dwc->gadget->wakeup_armed = false;
3962 dwc3_gadget_enable_linksts_evts(dwc, false);
3963 usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3965 dwc3_ep0_reset_state(dwc);
3968 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
3972 dwc->suspended = false;
3975 * Ideally, dwc3_reset_gadget() would trigger the function
3976 * drivers to stop any active transfers through ep disable.
3977 * However, for functions which defer ep disable, such as mass
3978 * storage, we will need to rely on the call to stop active
3979 * transfers here, and avoid allowing of request queuing.
3981 dwc->connected = false;
3984 * WORKAROUND: DWC3 revisions <1.88a have an issue which
3985 * would cause a missing Disconnect Event if there's a
3986 * pending Setup Packet in the FIFO.
3988 * There's no suggested workaround on the official Bug
3989 * report, which states that "unless the driver/application
3990 * is doing any special handling of a disconnect event,
3991 * there is no functional issue".
3993 * Unfortunately, it turns out that we _do_ some special
3994 * handling of a disconnect event, namely complete all
3995 * pending transfers, notify gadget driver of the
3996 * disconnection, and so on.
3998 * Our suggested workaround is to follow the Disconnect
3999 * Event steps here, instead, based on a setup_packet_pending
4000 * flag. Such flag gets set whenever we have a SETUP_PENDING
4001 * status for EP0 TRBs and gets cleared on XferComplete for the
4006 * STAR#9000466709: RTL: Device : Disconnect event not
4007 * generated if setup packet pending in FIFO
4009 if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
4010 if (dwc->setup_packet_pending)
4011 dwc3_gadget_disconnect_interrupt(dwc);
4014 dwc3_reset_gadget(dwc);
4017 * From SNPS databook section 8.1.2, the EP0 should be in setup
4018 * phase. So ensure that EP0 is in setup phase by issuing a stall
4019 * and restart if EP0 is not in setup phase.
4021 dwc3_ep0_reset_state(dwc);
4024 * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
4025 * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
4026 * needs to ensure that it sends "a DEPENDXFER command for any active
4029 dwc3_stop_active_transfers(dwc);
4030 dwc->connected = true;
4032 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4033 reg &= ~DWC3_DCTL_TSTCTRL_MASK;
4034 dwc3_gadget_dctl_write_safe(dwc, reg);
4035 dwc->test_mode = false;
4036 dwc->gadget->wakeup_armed = false;
4037 dwc3_gadget_enable_linksts_evts(dwc, false);
4038 dwc3_clear_stall_all_ep(dwc);
4040 /* Reset device address to zero */
4041 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
4042 reg &= ~(DWC3_DCFG_DEVADDR_MASK);
4043 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
4046 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
4048 struct dwc3_ep *dep;
4054 if (!dwc->softconnect)
4057 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
4058 speed = reg & DWC3_DSTS_CONNECTSPD;
4061 if (DWC3_IP_IS(DWC32))
4062 lanes = DWC3_DSTS_CONNLANES(reg) + 1;
4064 dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
4067 * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
4068 * each time on Connect Done.
4070 * Currently we always use the reset value. If any platform
4071 * wants to set this to a different value, we need to add a
4072 * setting and update GCTL.RAMCLKSEL here.
4076 case DWC3_DSTS_SUPERSPEED_PLUS:
4077 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
4078 dwc->gadget->ep0->maxpacket = 512;
4079 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
4082 dwc->gadget->ssp_rate = USB_SSP_GEN_2x2;
4084 dwc->gadget->ssp_rate = USB_SSP_GEN_2x1;
4086 case DWC3_DSTS_SUPERSPEED:
4088 * WORKAROUND: DWC3 revisions <1.90a have an issue which
4089 * would cause a missing USB3 Reset event.
4091 * In such situations, we should force a USB3 Reset
4092 * event by calling our dwc3_gadget_reset_interrupt()
4097 * STAR#9000483510: RTL: SS : USB3 reset event may
4098 * not be generated always when the link enters poll
4100 if (DWC3_VER_IS_PRIOR(DWC3, 190A))
4101 dwc3_gadget_reset_interrupt(dwc);
4103 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
4104 dwc->gadget->ep0->maxpacket = 512;
4105 dwc->gadget->speed = USB_SPEED_SUPER;
4108 dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
4109 dwc->gadget->ssp_rate = USB_SSP_GEN_1x2;
4112 case DWC3_DSTS_HIGHSPEED:
4113 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
4114 dwc->gadget->ep0->maxpacket = 64;
4115 dwc->gadget->speed = USB_SPEED_HIGH;
4117 case DWC3_DSTS_FULLSPEED:
4118 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
4119 dwc->gadget->ep0->maxpacket = 64;
4120 dwc->gadget->speed = USB_SPEED_FULL;
4124 dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
4126 /* Enable USB2 LPM Capability */
4128 if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
4129 !dwc->usb2_gadget_lpm_disable &&
4130 (speed != DWC3_DSTS_SUPERSPEED) &&
4131 (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
4132 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
4133 reg |= DWC3_DCFG_LPM_CAP;
4134 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
4136 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4137 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
4139 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
4140 (dwc->is_utmi_l1_suspend << 4));
4143 * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
4144 * DCFG.LPMCap is set, core responses with an ACK and the
4145 * BESL value in the LPM token is less than or equal to LPM
4148 WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
4149 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
4151 if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
4152 reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
4154 dwc3_gadget_dctl_write_safe(dwc, reg);
4156 if (dwc->usb2_gadget_lpm_disable) {
4157 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
4158 reg &= ~DWC3_DCFG_LPM_CAP;
4159 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
4162 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4163 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
4164 dwc3_gadget_dctl_write_safe(dwc, reg);
4168 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
4170 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
4175 ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
4177 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
4182 * Configure PHY via GUSB3PIPECTLn if required.
4184 * Update GTXFIFOSIZn
4186 * In both cases reset values should be sufficient.
4190 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc, unsigned int evtinfo)
4192 dwc->suspended = false;
4195 * TODO take core out of low power mode when that's
4199 if (dwc->async_callbacks && dwc->gadget_driver->resume) {
4200 spin_unlock(&dwc->lock);
4201 dwc->gadget_driver->resume(dwc->gadget);
4202 spin_lock(&dwc->lock);
4205 dwc->link_state = evtinfo & DWC3_LINK_STATE_MASK;
4208 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
4209 unsigned int evtinfo)
4211 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
4212 unsigned int pwropt;
4215 * WORKAROUND: DWC3 < 2.50a have an issue when configured without
4216 * Hibernation mode enabled which would show up when device detects
4217 * host-initiated U3 exit.
4219 * In that case, device will generate a Link State Change Interrupt
4220 * from U3 to RESUME which is only necessary if Hibernation is
4223 * There are no functional changes due to such spurious event and we
4224 * just need to ignore it.
4228 * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
4231 pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
4232 if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
4233 (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
4234 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
4235 (next == DWC3_LINK_STATE_RESUME)) {
4241 * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
4242 * on the link partner, the USB session might do multiple entry/exit
4243 * of low power states before a transfer takes place.
4245 * Due to this problem, we might experience lower throughput. The
4246 * suggested workaround is to disable DCTL[12:9] bits if we're
4247 * transitioning from U1/U2 to U0 and enable those bits again
4248 * after a transfer completes and there are no pending transfers
4249 * on any of the enabled endpoints.
4251 * This is the first half of that workaround.
4255 * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
4256 * core send LGO_Ux entering U0
4258 if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
4259 if (next == DWC3_LINK_STATE_U0) {
4263 switch (dwc->link_state) {
4264 case DWC3_LINK_STATE_U1:
4265 case DWC3_LINK_STATE_U2:
4266 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4267 u1u2 = reg & (DWC3_DCTL_INITU2ENA
4268 | DWC3_DCTL_ACCEPTU2ENA
4269 | DWC3_DCTL_INITU1ENA
4270 | DWC3_DCTL_ACCEPTU1ENA);
4273 dwc->u1u2 = reg & u1u2;
4277 dwc3_gadget_dctl_write_safe(dwc, reg);
4287 case DWC3_LINK_STATE_U0:
4288 if (dwc->gadget->wakeup_armed) {
4289 dwc3_gadget_enable_linksts_evts(dwc, false);
4290 dwc3_resume_gadget(dwc);
4291 dwc->suspended = false;
4294 case DWC3_LINK_STATE_U1:
4295 if (dwc->speed == USB_SPEED_SUPER)
4296 dwc3_suspend_gadget(dwc);
4298 case DWC3_LINK_STATE_U2:
4299 case DWC3_LINK_STATE_U3:
4300 dwc3_suspend_gadget(dwc);
4302 case DWC3_LINK_STATE_RESUME:
4303 dwc3_resume_gadget(dwc);
4310 dwc->link_state = next;
4313 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
4314 unsigned int evtinfo)
4316 enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
4318 if (!dwc->suspended && next == DWC3_LINK_STATE_U3) {
4319 dwc->suspended = true;
4320 dwc3_suspend_gadget(dwc);
4323 dwc->link_state = next;
4326 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
4327 const struct dwc3_event_devt *event)
4329 switch (event->type) {
4330 case DWC3_DEVICE_EVENT_DISCONNECT:
4331 dwc3_gadget_disconnect_interrupt(dwc);
4333 case DWC3_DEVICE_EVENT_RESET:
4334 dwc3_gadget_reset_interrupt(dwc);
4336 case DWC3_DEVICE_EVENT_CONNECT_DONE:
4337 dwc3_gadget_conndone_interrupt(dwc);
4339 case DWC3_DEVICE_EVENT_WAKEUP:
4340 dwc3_gadget_wakeup_interrupt(dwc, event->event_info);
4342 case DWC3_DEVICE_EVENT_HIBER_REQ:
4343 dev_WARN_ONCE(dwc->dev, true, "unexpected hibernation event\n");
4345 case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
4346 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
4348 case DWC3_DEVICE_EVENT_SUSPEND:
4349 /* It changed to be suspend event for version 2.30a and above */
4350 if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
4351 dwc3_gadget_suspend_interrupt(dwc, event->event_info);
4353 case DWC3_DEVICE_EVENT_SOF:
4354 case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
4355 case DWC3_DEVICE_EVENT_CMD_CMPL:
4356 case DWC3_DEVICE_EVENT_OVERFLOW:
4359 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
4363 static void dwc3_process_event_entry(struct dwc3 *dwc,
4364 const union dwc3_event *event)
4366 trace_dwc3_event(event->raw, dwc);
4368 if (!event->type.is_devspec)
4369 dwc3_endpoint_interrupt(dwc, &event->depevt);
4370 else if (event->type.type == DWC3_EVENT_TYPE_DEV)
4371 dwc3_gadget_interrupt(dwc, &event->devt);
4373 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
4376 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
4378 struct dwc3 *dwc = evt->dwc;
4379 irqreturn_t ret = IRQ_NONE;
4384 if (!(evt->flags & DWC3_EVENT_PENDING))
4388 union dwc3_event event;
4390 event.raw = *(u32 *) (evt->cache + evt->lpos);
4392 dwc3_process_event_entry(dwc, &event);
4395 * FIXME we wrap around correctly to the next entry as
4396 * almost all entries are 4 bytes in size. There is one
4397 * entry which has 12 bytes which is a regular entry
4398 * followed by 8 bytes data. ATM I don't know how
4399 * things are organized if we get next to the a
4400 * boundary so I worry about that once we try to handle
4403 evt->lpos = (evt->lpos + 4) % evt->length;
4410 /* Unmask interrupt */
4411 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4412 DWC3_GEVNTSIZ_SIZE(evt->length));
4414 if (dwc->imod_interval) {
4415 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
4416 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
4419 /* Keep the clearing of DWC3_EVENT_PENDING at the end */
4420 evt->flags &= ~DWC3_EVENT_PENDING;
4425 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
4427 struct dwc3_event_buffer *evt = _evt;
4428 struct dwc3 *dwc = evt->dwc;
4429 unsigned long flags;
4430 irqreturn_t ret = IRQ_NONE;
4433 spin_lock_irqsave(&dwc->lock, flags);
4434 ret = dwc3_process_event_buf(evt);
4435 spin_unlock_irqrestore(&dwc->lock, flags);
4441 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
4443 struct dwc3 *dwc = evt->dwc;
4447 if (pm_runtime_suspended(dwc->dev)) {
4448 pm_runtime_get(dwc->dev);
4449 disable_irq_nosync(dwc->irq_gadget);
4450 dwc->pending_events = true;
4455 * With PCIe legacy interrupt, test shows that top-half irq handler can
4456 * be called again after HW interrupt deassertion. Check if bottom-half
4457 * irq event handler completes before caching new event to prevent
4460 if (evt->flags & DWC3_EVENT_PENDING)
4463 count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
4464 count &= DWC3_GEVNTCOUNT_MASK;
4469 evt->flags |= DWC3_EVENT_PENDING;
4471 /* Mask interrupt */
4472 dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4473 DWC3_GEVNTSIZ_INTMASK | DWC3_GEVNTSIZ_SIZE(evt->length));
4475 amount = min(count, evt->length - evt->lpos);
4476 memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
4479 memcpy(evt->cache, evt->buf, count - amount);
4481 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
4483 return IRQ_WAKE_THREAD;
4486 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
4488 struct dwc3_event_buffer *evt = _evt;
4490 return dwc3_check_event_buf(evt);
4493 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
4495 struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
4498 irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
4502 if (irq == -EPROBE_DEFER)
4505 irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
4509 if (irq == -EPROBE_DEFER)
4512 irq = platform_get_irq(dwc3_pdev, 0);
4518 static void dwc_gadget_release(struct device *dev)
4520 struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
4526 * dwc3_gadget_init - initializes gadget related registers
4527 * @dwc: pointer to our controller context structure
4529 * Returns 0 on success otherwise negative errno.
4531 int dwc3_gadget_init(struct dwc3 *dwc)
4537 irq = dwc3_gadget_get_irq(dwc);
4543 dwc->irq_gadget = irq;
4545 dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
4546 sizeof(*dwc->ep0_trb) * 2,
4547 &dwc->ep0_trb_addr, GFP_KERNEL);
4548 if (!dwc->ep0_trb) {
4549 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
4554 dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
4555 if (!dwc->setup_buf) {
4560 dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
4561 &dwc->bounce_addr, GFP_KERNEL);
4567 init_completion(&dwc->ep0_in_setup);
4568 dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
4575 usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
4576 dev = &dwc->gadget->dev;
4577 dev->platform_data = dwc;
4578 dwc->gadget->ops = &dwc3_gadget_ops;
4579 dwc->gadget->speed = USB_SPEED_UNKNOWN;
4580 dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
4581 dwc->gadget->sg_supported = true;
4582 dwc->gadget->name = "dwc3-gadget";
4583 dwc->gadget->lpm_capable = !dwc->usb2_gadget_lpm_disable;
4584 dwc->gadget->wakeup_capable = true;
4587 * FIXME We might be setting max_speed to <SUPER, however versions
4588 * <2.20a of dwc3 have an issue with metastability (documented
4589 * elsewhere in this driver) which tells us we can't set max speed to
4590 * anything lower than SUPER.
4592 * Because gadget.max_speed is only used by composite.c and function
4593 * drivers (i.e. it won't go into dwc3's registers) we are allowing this
4594 * to happen so we avoid sending SuperSpeed Capability descriptor
4595 * together with our BOS descriptor as that could confuse host into
4596 * thinking we can handle super speed.
4598 * Note that, in fact, we won't even support GetBOS requests when speed
4599 * is less than super speed because we don't have means, yet, to tell
4600 * composite.c that we are USB 2.0 + LPM ECN.
4602 if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
4603 !dwc->dis_metastability_quirk)
4604 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
4607 dwc->gadget->max_speed = dwc->maximum_speed;
4608 dwc->gadget->max_ssp_rate = dwc->max_ssp_rate;
4611 * REVISIT: Here we should clear all pending IRQs to be
4612 * sure we're starting from a well known location.
4615 ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
4619 ret = usb_add_gadget(dwc->gadget);
4621 dev_err(dwc->dev, "failed to add gadget\n");
4625 if (DWC3_IP_IS(DWC32) && dwc->maximum_speed == USB_SPEED_SUPER_PLUS)
4626 dwc3_gadget_set_ssp_rate(dwc->gadget, dwc->max_ssp_rate);
4628 dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
4633 dwc3_gadget_free_endpoints(dwc);
4635 usb_put_gadget(dwc->gadget);
4638 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4642 kfree(dwc->setup_buf);
4645 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4646 dwc->ep0_trb, dwc->ep0_trb_addr);
4652 /* -------------------------------------------------------------------------- */
4654 void dwc3_gadget_exit(struct dwc3 *dwc)
4659 usb_del_gadget(dwc->gadget);
4660 dwc3_gadget_free_endpoints(dwc);
4661 usb_put_gadget(dwc->gadget);
4662 dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4664 kfree(dwc->setup_buf);
4665 dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4666 dwc->ep0_trb, dwc->ep0_trb_addr);
4669 int dwc3_gadget_suspend(struct dwc3 *dwc)
4671 unsigned long flags;
4674 if (!dwc->gadget_driver)
4677 ret = dwc3_gadget_soft_disconnect(dwc);
4681 spin_lock_irqsave(&dwc->lock, flags);
4682 dwc3_disconnect_gadget(dwc);
4683 spin_unlock_irqrestore(&dwc->lock, flags);
4689 * Attempt to reset the controller's state. Likely no
4690 * communication can be established until the host
4691 * performs a port reset.
4693 if (dwc->softconnect)
4694 dwc3_gadget_soft_connect(dwc);
4699 int dwc3_gadget_resume(struct dwc3 *dwc)
4701 if (!dwc->gadget_driver || !dwc->softconnect)
4704 return dwc3_gadget_soft_connect(dwc);
4707 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4709 if (dwc->pending_events) {
4710 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4711 dwc->pending_events = false;
4712 enable_irq(dwc->irq_gadget);