Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
0004  *
0005  * Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com
0006  *
0007  * Authors: Felipe Balbi <balbi@ti.com>,
0008  *      Sebastian Andrzej Siewior <bigeasy@linutronix.de>
0009  */
0010 
0011 #include <linux/kernel.h>
0012 #include <linux/delay.h>
0013 #include <linux/slab.h>
0014 #include <linux/spinlock.h>
0015 #include <linux/platform_device.h>
0016 #include <linux/pm_runtime.h>
0017 #include <linux/interrupt.h>
0018 #include <linux/io.h>
0019 #include <linux/list.h>
0020 #include <linux/dma-mapping.h>
0021 
0022 #include <linux/usb/ch9.h>
0023 #include <linux/usb/gadget.h>
0024 
0025 #include "debug.h"
0026 #include "core.h"
0027 #include "gadget.h"
0028 #include "io.h"
0029 
0030 #define DWC3_ALIGN_FRAME(d, n)  (((d)->frame_number + ((d)->interval * (n))) \
0031                     & ~((d)->interval - 1))
0032 
0033 /**
0034  * dwc3_gadget_set_test_mode - enables usb2 test modes
0035  * @dwc: pointer to our context structure
0036  * @mode: the mode to set (J, K SE0 NAK, Force Enable)
0037  *
0038  * Caller should take care of locking. This function will return 0 on
0039  * success or -EINVAL if wrong Test Selector is passed.
0040  */
0041 int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
0042 {
0043     u32     reg;
0044 
0045     reg = dwc3_readl(dwc->regs, DWC3_DCTL);
0046     reg &= ~DWC3_DCTL_TSTCTRL_MASK;
0047 
0048     switch (mode) {
0049     case USB_TEST_J:
0050     case USB_TEST_K:
0051     case USB_TEST_SE0_NAK:
0052     case USB_TEST_PACKET:
0053     case USB_TEST_FORCE_ENABLE:
0054         reg |= mode << 1;
0055         break;
0056     default:
0057         return -EINVAL;
0058     }
0059 
0060     dwc3_gadget_dctl_write_safe(dwc, reg);
0061 
0062     return 0;
0063 }
0064 
0065 /**
0066  * dwc3_gadget_get_link_state - gets current state of usb link
0067  * @dwc: pointer to our context structure
0068  *
0069  * Caller should take care of locking. This function will
0070  * return the link state on success (>= 0) or -ETIMEDOUT.
0071  */
0072 int dwc3_gadget_get_link_state(struct dwc3 *dwc)
0073 {
0074     u32     reg;
0075 
0076     reg = dwc3_readl(dwc->regs, DWC3_DSTS);
0077 
0078     return DWC3_DSTS_USBLNKST(reg);
0079 }
0080 
0081 /**
0082  * dwc3_gadget_set_link_state - sets usb link to a particular state
0083  * @dwc: pointer to our context structure
0084  * @state: the state to put link into
0085  *
0086  * Caller should take care of locking. This function will
0087  * return 0 on success or -ETIMEDOUT.
0088  */
0089 int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
0090 {
0091     int     retries = 10000;
0092     u32     reg;
0093 
0094     /*
0095      * Wait until device controller is ready. Only applies to 1.94a and
0096      * later RTL.
0097      */
0098     if (!DWC3_VER_IS_PRIOR(DWC3, 194A)) {
0099         while (--retries) {
0100             reg = dwc3_readl(dwc->regs, DWC3_DSTS);
0101             if (reg & DWC3_DSTS_DCNRD)
0102                 udelay(5);
0103             else
0104                 break;
0105         }
0106 
0107         if (retries <= 0)
0108             return -ETIMEDOUT;
0109     }
0110 
0111     reg = dwc3_readl(dwc->regs, DWC3_DCTL);
0112     reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
0113 
0114     /* set no action before sending new link state change */
0115     dwc3_writel(dwc->regs, DWC3_DCTL, reg);
0116 
0117     /* set requested state */
0118     reg |= DWC3_DCTL_ULSTCHNGREQ(state);
0119     dwc3_writel(dwc->regs, DWC3_DCTL, reg);
0120 
0121     /*
0122      * The following code is racy when called from dwc3_gadget_wakeup,
0123      * and is not needed, at least on newer versions
0124      */
0125     if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
0126         return 0;
0127 
0128     /* wait for a change in DSTS */
0129     retries = 10000;
0130     while (--retries) {
0131         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
0132 
0133         if (DWC3_DSTS_USBLNKST(reg) == state)
0134             return 0;
0135 
0136         udelay(5);
0137     }
0138 
0139     return -ETIMEDOUT;
0140 }
0141 
0142 /**
0143  * dwc3_ep_inc_trb - increment a trb index.
0144  * @index: Pointer to the TRB index to increment.
0145  *
0146  * The index should never point to the link TRB. After incrementing,
0147  * if it is point to the link TRB, wrap around to the beginning. The
0148  * link TRB is always at the last TRB entry.
0149  */
0150 static void dwc3_ep_inc_trb(u8 *index)
0151 {
0152     (*index)++;
0153     if (*index == (DWC3_TRB_NUM - 1))
0154         *index = 0;
0155 }
0156 
0157 /**
0158  * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
0159  * @dep: The endpoint whose enqueue pointer we're incrementing
0160  */
0161 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
0162 {
0163     dwc3_ep_inc_trb(&dep->trb_enqueue);
0164 }
0165 
0166 /**
0167  * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
0168  * @dep: The endpoint whose enqueue pointer we're incrementing
0169  */
0170 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
0171 {
0172     dwc3_ep_inc_trb(&dep->trb_dequeue);
0173 }
0174 
0175 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
0176         struct dwc3_request *req, int status)
0177 {
0178     struct dwc3         *dwc = dep->dwc;
0179 
0180     list_del(&req->list);
0181     req->remaining = 0;
0182     req->needs_extra_trb = false;
0183 
0184     if (req->request.status == -EINPROGRESS)
0185         req->request.status = status;
0186 
0187     if (req->trb)
0188         usb_gadget_unmap_request_by_dev(dwc->sysdev,
0189                 &req->request, req->direction);
0190 
0191     req->trb = NULL;
0192     trace_dwc3_gadget_giveback(req);
0193 
0194     if (dep->number > 1)
0195         pm_runtime_put(dwc->dev);
0196 }
0197 
0198 /**
0199  * dwc3_gadget_giveback - call struct usb_request's ->complete callback
0200  * @dep: The endpoint to whom the request belongs to
0201  * @req: The request we're giving back
0202  * @status: completion code for the request
0203  *
0204  * Must be called with controller's lock held and interrupts disabled. This
0205  * function will unmap @req and call its ->complete() callback to notify upper
0206  * layers that it has completed.
0207  */
0208 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
0209         int status)
0210 {
0211     struct dwc3         *dwc = dep->dwc;
0212 
0213     dwc3_gadget_del_and_unmap_request(dep, req, status);
0214     req->status = DWC3_REQUEST_STATUS_COMPLETED;
0215 
0216     spin_unlock(&dwc->lock);
0217     usb_gadget_giveback_request(&dep->endpoint, &req->request);
0218     spin_lock(&dwc->lock);
0219 }
0220 
0221 /**
0222  * dwc3_send_gadget_generic_command - issue a generic command for the controller
0223  * @dwc: pointer to the controller context
0224  * @cmd: the command to be issued
0225  * @param: command parameter
0226  *
0227  * Caller should take care of locking. Issue @cmd with a given @param to @dwc
0228  * and wait for its completion.
0229  */
0230 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
0231         u32 param)
0232 {
0233     u32     timeout = 500;
0234     int     status = 0;
0235     int     ret = 0;
0236     u32     reg;
0237 
0238     dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
0239     dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
0240 
0241     do {
0242         reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
0243         if (!(reg & DWC3_DGCMD_CMDACT)) {
0244             status = DWC3_DGCMD_STATUS(reg);
0245             if (status)
0246                 ret = -EINVAL;
0247             break;
0248         }
0249     } while (--timeout);
0250 
0251     if (!timeout) {
0252         ret = -ETIMEDOUT;
0253         status = -ETIMEDOUT;
0254     }
0255 
0256     trace_dwc3_gadget_generic_cmd(cmd, param, status);
0257 
0258     return ret;
0259 }
0260 
0261 static int __dwc3_gadget_wakeup(struct dwc3 *dwc);
0262 
0263 /**
0264  * dwc3_send_gadget_ep_cmd - issue an endpoint command
0265  * @dep: the endpoint to which the command is going to be issued
0266  * @cmd: the command to be issued
0267  * @params: parameters to the command
0268  *
0269  * Caller should handle locking. This function will issue @cmd with given
0270  * @params to @dep and wait for its completion.
0271  */
0272 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd,
0273         struct dwc3_gadget_ep_cmd_params *params)
0274 {
0275     const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
0276     struct dwc3     *dwc = dep->dwc;
0277     u32         timeout = 5000;
0278     u32         saved_config = 0;
0279     u32         reg;
0280 
0281     int         cmd_status = 0;
0282     int         ret = -EINVAL;
0283 
0284     /*
0285      * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or
0286      * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an
0287      * endpoint command.
0288      *
0289      * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY
0290      * settings. Restore them after the command is completed.
0291      *
0292      * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2
0293      */
0294     if (dwc->gadget->speed <= USB_SPEED_HIGH) {
0295         reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
0296         if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
0297             saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
0298             reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
0299         }
0300 
0301         if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
0302             saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
0303             reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
0304         }
0305 
0306         if (saved_config)
0307             dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
0308     }
0309 
0310     if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
0311         int link_state;
0312 
0313         /*
0314          * Initiate remote wakeup if the link state is in U3 when
0315          * operating in SS/SSP or L1/L2 when operating in HS/FS. If the
0316          * link state is in U1/U2, no remote wakeup is needed. The Start
0317          * Transfer command will initiate the link recovery.
0318          */
0319         link_state = dwc3_gadget_get_link_state(dwc);
0320         switch (link_state) {
0321         case DWC3_LINK_STATE_U2:
0322             if (dwc->gadget->speed >= USB_SPEED_SUPER)
0323                 break;
0324 
0325             fallthrough;
0326         case DWC3_LINK_STATE_U3:
0327             ret = __dwc3_gadget_wakeup(dwc);
0328             dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
0329                     ret);
0330             break;
0331         }
0332     }
0333 
0334     /*
0335      * For some commands such as Update Transfer command, DEPCMDPARn
0336      * registers are reserved. Since the driver often sends Update Transfer
0337      * command, don't write to DEPCMDPARn to avoid register write delays and
0338      * improve performance.
0339      */
0340     if (DWC3_DEPCMD_CMD(cmd) != DWC3_DEPCMD_UPDATETRANSFER) {
0341         dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
0342         dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
0343         dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
0344     }
0345 
0346     /*
0347      * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
0348      * not relying on XferNotReady, we can make use of a special "No
0349      * Response Update Transfer" command where we should clear both CmdAct
0350      * and CmdIOC bits.
0351      *
0352      * With this, we don't need to wait for command completion and can
0353      * straight away issue further commands to the endpoint.
0354      *
0355      * NOTICE: We're making an assumption that control endpoints will never
0356      * make use of Update Transfer command. This is a safe assumption
0357      * because we can never have more than one request at a time with
0358      * Control Endpoints. If anybody changes that assumption, this chunk
0359      * needs to be updated accordingly.
0360      */
0361     if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
0362             !usb_endpoint_xfer_isoc(desc))
0363         cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
0364     else
0365         cmd |= DWC3_DEPCMD_CMDACT;
0366 
0367     dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
0368 
0369     if (!(cmd & DWC3_DEPCMD_CMDACT)) {
0370         ret = 0;
0371         goto skip_status;
0372     }
0373 
0374     do {
0375         reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
0376         if (!(reg & DWC3_DEPCMD_CMDACT)) {
0377             cmd_status = DWC3_DEPCMD_STATUS(reg);
0378 
0379             switch (cmd_status) {
0380             case 0:
0381                 ret = 0;
0382                 break;
0383             case DEPEVT_TRANSFER_NO_RESOURCE:
0384                 dev_WARN(dwc->dev, "No resource for %s\n",
0385                      dep->name);
0386                 ret = -EINVAL;
0387                 break;
0388             case DEPEVT_TRANSFER_BUS_EXPIRY:
0389                 /*
0390                  * SW issues START TRANSFER command to
0391                  * isochronous ep with future frame interval. If
0392                  * future interval time has already passed when
0393                  * core receives the command, it will respond
0394                  * with an error status of 'Bus Expiry'.
0395                  *
0396                  * Instead of always returning -EINVAL, let's
0397                  * give a hint to the gadget driver that this is
0398                  * the case by returning -EAGAIN.
0399                  */
0400                 ret = -EAGAIN;
0401                 break;
0402             default:
0403                 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
0404             }
0405 
0406             break;
0407         }
0408     } while (--timeout);
0409 
0410     if (timeout == 0) {
0411         ret = -ETIMEDOUT;
0412         cmd_status = -ETIMEDOUT;
0413     }
0414 
0415 skip_status:
0416     trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
0417 
0418     if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
0419         if (ret == 0)
0420             dep->flags |= DWC3_EP_TRANSFER_STARTED;
0421 
0422         if (ret != -ETIMEDOUT)
0423             dwc3_gadget_ep_get_transfer_index(dep);
0424     }
0425 
0426     if (saved_config) {
0427         reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
0428         reg |= saved_config;
0429         dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
0430     }
0431 
0432     return ret;
0433 }
0434 
0435 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
0436 {
0437     struct dwc3 *dwc = dep->dwc;
0438     struct dwc3_gadget_ep_cmd_params params;
0439     u32 cmd = DWC3_DEPCMD_CLEARSTALL;
0440 
0441     /*
0442      * As of core revision 2.60a the recommended programming model
0443      * is to set the ClearPendIN bit when issuing a Clear Stall EP
0444      * command for IN endpoints. This is to prevent an issue where
0445      * some (non-compliant) hosts may not send ACK TPs for pending
0446      * IN transfers due to a mishandled error condition. Synopsys
0447      * STAR 9000614252.
0448      */
0449     if (dep->direction &&
0450         !DWC3_VER_IS_PRIOR(DWC3, 260A) &&
0451         (dwc->gadget->speed >= USB_SPEED_SUPER))
0452         cmd |= DWC3_DEPCMD_CLEARPENDIN;
0453 
0454     memset(&params, 0, sizeof(params));
0455 
0456     return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
0457 }
0458 
0459 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
0460         struct dwc3_trb *trb)
0461 {
0462     u32     offset = (char *) trb - (char *) dep->trb_pool;
0463 
0464     return dep->trb_pool_dma + offset;
0465 }
0466 
0467 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
0468 {
0469     struct dwc3     *dwc = dep->dwc;
0470 
0471     if (dep->trb_pool)
0472         return 0;
0473 
0474     dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
0475             sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
0476             &dep->trb_pool_dma, GFP_KERNEL);
0477     if (!dep->trb_pool) {
0478         dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
0479                 dep->name);
0480         return -ENOMEM;
0481     }
0482 
0483     return 0;
0484 }
0485 
0486 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
0487 {
0488     struct dwc3     *dwc = dep->dwc;
0489 
0490     dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
0491             dep->trb_pool, dep->trb_pool_dma);
0492 
0493     dep->trb_pool = NULL;
0494     dep->trb_pool_dma = 0;
0495 }
0496 
0497 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
0498 {
0499     struct dwc3_gadget_ep_cmd_params params;
0500 
0501     memset(&params, 0x00, sizeof(params));
0502 
0503     params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
0504 
0505     return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
0506             &params);
0507 }
0508 
0509 /**
0510  * dwc3_gadget_start_config - configure ep resources
0511  * @dep: endpoint that is being enabled
0512  *
0513  * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
0514  * completion, it will set Transfer Resource for all available endpoints.
0515  *
0516  * The assignment of transfer resources cannot perfectly follow the data book
0517  * due to the fact that the controller driver does not have all knowledge of the
0518  * configuration in advance. It is given this information piecemeal by the
0519  * composite gadget framework after every SET_CONFIGURATION and
0520  * SET_INTERFACE. Trying to follow the databook programming model in this
0521  * scenario can cause errors. For two reasons:
0522  *
0523  * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
0524  * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
0525  * incorrect in the scenario of multiple interfaces.
0526  *
0527  * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
0528  * endpoint on alt setting (8.1.6).
0529  *
0530  * The following simplified method is used instead:
0531  *
0532  * All hardware endpoints can be assigned a transfer resource and this setting
0533  * will stay persistent until either a core reset or hibernation. So whenever we
0534  * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
0535  * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
0536  * guaranteed that there are as many transfer resources as endpoints.
0537  *
0538  * This function is called for each endpoint when it is being enabled but is
0539  * triggered only when called for EP0-out, which always happens first, and which
0540  * should only happen in one of the above conditions.
0541  */
0542 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
0543 {
0544     struct dwc3_gadget_ep_cmd_params params;
0545     struct dwc3     *dwc;
0546     u32         cmd;
0547     int         i;
0548     int         ret;
0549 
0550     if (dep->number)
0551         return 0;
0552 
0553     memset(&params, 0x00, sizeof(params));
0554     cmd = DWC3_DEPCMD_DEPSTARTCFG;
0555     dwc = dep->dwc;
0556 
0557     ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
0558     if (ret)
0559         return ret;
0560 
0561     for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
0562         struct dwc3_ep *dep = dwc->eps[i];
0563 
0564         if (!dep)
0565             continue;
0566 
0567         ret = dwc3_gadget_set_xfer_resource(dep);
0568         if (ret)
0569             return ret;
0570     }
0571 
0572     return 0;
0573 }
0574 
0575 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
0576 {
0577     const struct usb_ss_ep_comp_descriptor *comp_desc;
0578     const struct usb_endpoint_descriptor *desc;
0579     struct dwc3_gadget_ep_cmd_params params;
0580     struct dwc3 *dwc = dep->dwc;
0581 
0582     comp_desc = dep->endpoint.comp_desc;
0583     desc = dep->endpoint.desc;
0584 
0585     memset(&params, 0x00, sizeof(params));
0586 
0587     params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
0588         | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
0589 
0590     /* Burst size is only needed in SuperSpeed mode */
0591     if (dwc->gadget->speed >= USB_SPEED_SUPER) {
0592         u32 burst = dep->endpoint.maxburst;
0593 
0594         params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
0595     }
0596 
0597     params.param0 |= action;
0598     if (action == DWC3_DEPCFG_ACTION_RESTORE)
0599         params.param2 |= dep->saved_state;
0600 
0601     if (usb_endpoint_xfer_control(desc))
0602         params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
0603 
0604     if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
0605         params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
0606 
0607     if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
0608         params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
0609             | DWC3_DEPCFG_XFER_COMPLETE_EN
0610             | DWC3_DEPCFG_STREAM_EVENT_EN;
0611         dep->stream_capable = true;
0612     }
0613 
0614     if (!usb_endpoint_xfer_control(desc))
0615         params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
0616 
0617     /*
0618      * We are doing 1:1 mapping for endpoints, meaning
0619      * Physical Endpoints 2 maps to Logical Endpoint 2 and
0620      * so on. We consider the direction bit as part of the physical
0621      * endpoint number. So USB endpoint 0x81 is 0x03.
0622      */
0623     params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
0624 
0625     /*
0626      * We must use the lower 16 TX FIFOs even though
0627      * HW might have more
0628      */
0629     if (dep->direction)
0630         params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
0631 
0632     if (desc->bInterval) {
0633         u8 bInterval_m1;
0634 
0635         /*
0636          * Valid range for DEPCFG.bInterval_m1 is from 0 to 13.
0637          *
0638          * NOTE: The programming guide incorrectly stated bInterval_m1
0639          * must be set to 0 when operating in fullspeed. Internally the
0640          * controller does not have this limitation. See DWC_usb3x
0641          * programming guide section 3.2.2.1.
0642          */
0643         bInterval_m1 = min_t(u8, desc->bInterval - 1, 13);
0644 
0645         if (usb_endpoint_type(desc) == USB_ENDPOINT_XFER_INT &&
0646             dwc->gadget->speed == USB_SPEED_FULL)
0647             dep->interval = desc->bInterval;
0648         else
0649             dep->interval = 1 << (desc->bInterval - 1);
0650 
0651         params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(bInterval_m1);
0652     }
0653 
0654     return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
0655 }
0656 
0657 /**
0658  * dwc3_gadget_calc_tx_fifo_size - calculates the txfifo size value
0659  * @dwc: pointer to the DWC3 context
0660  * @mult: multiplier to be used when calculating the fifo_size
0661  *
0662  * Calculates the size value based on the equation below:
0663  *
0664  * DWC3 revision 280A and prior:
0665  * fifo_size = mult * (max_packet / mdwidth) + 1;
0666  *
0667  * DWC3 revision 290A and onwards:
0668  * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
0669  *
0670  * The max packet size is set to 1024, as the txfifo requirements mainly apply
0671  * to super speed USB use cases.  However, it is safe to overestimate the fifo
0672  * allocations for other scenarios, i.e. high speed USB.
0673  */
0674 static int dwc3_gadget_calc_tx_fifo_size(struct dwc3 *dwc, int mult)
0675 {
0676     int max_packet = 1024;
0677     int fifo_size;
0678     int mdwidth;
0679 
0680     mdwidth = dwc3_mdwidth(dwc);
0681 
0682     /* MDWIDTH is represented in bits, we need it in bytes */
0683     mdwidth >>= 3;
0684 
0685     if (DWC3_VER_IS_PRIOR(DWC3, 290A))
0686         fifo_size = mult * (max_packet / mdwidth) + 1;
0687     else
0688         fifo_size = mult * ((max_packet + mdwidth) / mdwidth) + 1;
0689     return fifo_size;
0690 }
0691 
0692 /**
0693  * dwc3_gadget_clear_tx_fifos - Clears txfifo allocation
0694  * @dwc: pointer to the DWC3 context
0695  *
0696  * Iterates through all the endpoint registers and clears the previous txfifo
0697  * allocations.
0698  */
0699 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc)
0700 {
0701     struct dwc3_ep *dep;
0702     int fifo_depth;
0703     int size;
0704     int num;
0705 
0706     if (!dwc->do_fifo_resize)
0707         return;
0708 
0709     /* Read ep0IN related TXFIFO size */
0710     dep = dwc->eps[1];
0711     size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
0712     if (DWC3_IP_IS(DWC3))
0713         fifo_depth = DWC3_GTXFIFOSIZ_TXFDEP(size);
0714     else
0715         fifo_depth = DWC31_GTXFIFOSIZ_TXFDEP(size);
0716 
0717     dwc->last_fifo_depth = fifo_depth;
0718     /* Clear existing TXFIFO for all IN eps except ep0 */
0719     for (num = 3; num < min_t(int, dwc->num_eps, DWC3_ENDPOINTS_NUM);
0720          num += 2) {
0721         dep = dwc->eps[num];
0722         /* Don't change TXFRAMNUM on usb31 version */
0723         size = DWC3_IP_IS(DWC3) ? 0 :
0724             dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1)) &
0725                    DWC31_GTXFIFOSIZ_TXFRAMNUM;
0726 
0727         dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(num >> 1), size);
0728         dep->flags &= ~DWC3_EP_TXFIFO_RESIZED;
0729     }
0730     dwc->num_ep_resized = 0;
0731 }
0732 
0733 /*
0734  * dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
0735  * @dwc: pointer to our context structure
0736  *
0737  * This function will a best effort FIFO allocation in order
0738  * to improve FIFO usage and throughput, while still allowing
0739  * us to enable as many endpoints as possible.
0740  *
0741  * Keep in mind that this operation will be highly dependent
0742  * on the configured size for RAM1 - which contains TxFifo -,
0743  * the amount of endpoints enabled on coreConsultant tool, and
0744  * the width of the Master Bus.
0745  *
0746  * In general, FIFO depths are represented with the following equation:
0747  *
0748  * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
0749  *
0750  * In conjunction with dwc3_gadget_check_config(), this resizing logic will
0751  * ensure that all endpoints will have enough internal memory for one max
0752  * packet per endpoint.
0753  */
0754 static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep)
0755 {
0756     struct dwc3 *dwc = dep->dwc;
0757     int fifo_0_start;
0758     int ram1_depth;
0759     int fifo_size;
0760     int min_depth;
0761     int num_in_ep;
0762     int remaining;
0763     int num_fifos = 1;
0764     int fifo;
0765     int tmp;
0766 
0767     if (!dwc->do_fifo_resize)
0768         return 0;
0769 
0770     /* resize IN endpoints except ep0 */
0771     if (!usb_endpoint_dir_in(dep->endpoint.desc) || dep->number <= 1)
0772         return 0;
0773 
0774     /* bail if already resized */
0775     if (dep->flags & DWC3_EP_TXFIFO_RESIZED)
0776         return 0;
0777 
0778     ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
0779 
0780     if ((dep->endpoint.maxburst > 1 &&
0781          usb_endpoint_xfer_bulk(dep->endpoint.desc)) ||
0782         usb_endpoint_xfer_isoc(dep->endpoint.desc))
0783         num_fifos = 3;
0784 
0785     if (dep->endpoint.maxburst > 6 &&
0786         (usb_endpoint_xfer_bulk(dep->endpoint.desc) ||
0787          usb_endpoint_xfer_isoc(dep->endpoint.desc)) && DWC3_IP_IS(DWC31))
0788         num_fifos = dwc->tx_fifo_resize_max_num;
0789 
0790     /* FIFO size for a single buffer */
0791     fifo = dwc3_gadget_calc_tx_fifo_size(dwc, 1);
0792 
0793     /* Calculate the number of remaining EPs w/o any FIFO */
0794     num_in_ep = dwc->max_cfg_eps;
0795     num_in_ep -= dwc->num_ep_resized;
0796 
0797     /* Reserve at least one FIFO for the number of IN EPs */
0798     min_depth = num_in_ep * (fifo + 1);
0799     remaining = ram1_depth - min_depth - dwc->last_fifo_depth;
0800     remaining = max_t(int, 0, remaining);
0801     /*
0802      * We've already reserved 1 FIFO per EP, so check what we can fit in
0803      * addition to it.  If there is not enough remaining space, allocate
0804      * all the remaining space to the EP.
0805      */
0806     fifo_size = (num_fifos - 1) * fifo;
0807     if (remaining < fifo_size)
0808         fifo_size = remaining;
0809 
0810     fifo_size += fifo;
0811     /* Last increment according to the TX FIFO size equation */
0812     fifo_size++;
0813 
0814     /* Check if TXFIFOs start at non-zero addr */
0815     tmp = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(0));
0816     fifo_0_start = DWC3_GTXFIFOSIZ_TXFSTADDR(tmp);
0817 
0818     fifo_size |= (fifo_0_start + (dwc->last_fifo_depth << 16));
0819     if (DWC3_IP_IS(DWC3))
0820         dwc->last_fifo_depth += DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
0821     else
0822         dwc->last_fifo_depth += DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
0823 
0824     /* Check fifo size allocation doesn't exceed available RAM size. */
0825     if (dwc->last_fifo_depth >= ram1_depth) {
0826         dev_err(dwc->dev, "Fifosize(%d) > RAM size(%d) %s depth:%d\n",
0827             dwc->last_fifo_depth, ram1_depth,
0828             dep->endpoint.name, fifo_size);
0829         if (DWC3_IP_IS(DWC3))
0830             fifo_size = DWC3_GTXFIFOSIZ_TXFDEP(fifo_size);
0831         else
0832             fifo_size = DWC31_GTXFIFOSIZ_TXFDEP(fifo_size);
0833 
0834         dwc->last_fifo_depth -= fifo_size;
0835         return -ENOMEM;
0836     }
0837 
0838     dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1), fifo_size);
0839     dep->flags |= DWC3_EP_TXFIFO_RESIZED;
0840     dwc->num_ep_resized++;
0841 
0842     return 0;
0843 }
0844 
0845 /**
0846  * __dwc3_gadget_ep_enable - initializes a hw endpoint
0847  * @dep: endpoint to be initialized
0848  * @action: one of INIT, MODIFY or RESTORE
0849  *
0850  * Caller should take care of locking. Execute all necessary commands to
0851  * initialize a HW endpoint so it can be used by a gadget driver.
0852  */
0853 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
0854 {
0855     const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
0856     struct dwc3     *dwc = dep->dwc;
0857 
0858     u32         reg;
0859     int         ret;
0860 
0861     if (!(dep->flags & DWC3_EP_ENABLED)) {
0862         ret = dwc3_gadget_resize_tx_fifos(dep);
0863         if (ret)
0864             return ret;
0865 
0866         ret = dwc3_gadget_start_config(dep);
0867         if (ret)
0868             return ret;
0869     }
0870 
0871     ret = dwc3_gadget_set_ep_config(dep, action);
0872     if (ret)
0873         return ret;
0874 
0875     if (!(dep->flags & DWC3_EP_ENABLED)) {
0876         struct dwc3_trb *trb_st_hw;
0877         struct dwc3_trb *trb_link;
0878 
0879         dep->type = usb_endpoint_type(desc);
0880         dep->flags |= DWC3_EP_ENABLED;
0881 
0882         reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
0883         reg |= DWC3_DALEPENA_EP(dep->number);
0884         dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
0885 
0886         dep->trb_dequeue = 0;
0887         dep->trb_enqueue = 0;
0888 
0889         if (usb_endpoint_xfer_control(desc))
0890             goto out;
0891 
0892         /* Initialize the TRB ring */
0893         memset(dep->trb_pool, 0,
0894                sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
0895 
0896         /* Link TRB. The HWO bit is never reset */
0897         trb_st_hw = &dep->trb_pool[0];
0898 
0899         trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
0900         trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
0901         trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
0902         trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
0903         trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
0904     }
0905 
0906     /*
0907      * Issue StartTransfer here with no-op TRB so we can always rely on No
0908      * Response Update Transfer command.
0909      */
0910     if (usb_endpoint_xfer_bulk(desc) ||
0911             usb_endpoint_xfer_int(desc)) {
0912         struct dwc3_gadget_ep_cmd_params params;
0913         struct dwc3_trb *trb;
0914         dma_addr_t trb_dma;
0915         u32 cmd;
0916 
0917         memset(&params, 0, sizeof(params));
0918         trb = &dep->trb_pool[0];
0919         trb_dma = dwc3_trb_dma_offset(dep, trb);
0920 
0921         params.param0 = upper_32_bits(trb_dma);
0922         params.param1 = lower_32_bits(trb_dma);
0923 
0924         cmd = DWC3_DEPCMD_STARTTRANSFER;
0925 
0926         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
0927         if (ret < 0)
0928             return ret;
0929 
0930         if (dep->stream_capable) {
0931             /*
0932              * For streams, at start, there maybe a race where the
0933              * host primes the endpoint before the function driver
0934              * queues a request to initiate a stream. In that case,
0935              * the controller will not see the prime to generate the
0936              * ERDY and start stream. To workaround this, issue a
0937              * no-op TRB as normal, but end it immediately. As a
0938              * result, when the function driver queues the request,
0939              * the next START_TRANSFER command will cause the
0940              * controller to generate an ERDY to initiate the
0941              * stream.
0942              */
0943             dwc3_stop_active_transfer(dep, true, true);
0944 
0945             /*
0946              * All stream eps will reinitiate stream on NoStream
0947              * rejection until we can determine that the host can
0948              * prime after the first transfer.
0949              *
0950              * However, if the controller is capable of
0951              * TXF_FLUSH_BYPASS, then IN direction endpoints will
0952              * automatically restart the stream without the driver
0953              * initiation.
0954              */
0955             if (!dep->direction ||
0956                 !(dwc->hwparams.hwparams9 &
0957                   DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
0958                 dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
0959         }
0960     }
0961 
0962 out:
0963     trace_dwc3_gadget_ep_enable(dep);
0964 
0965     return 0;
0966 }
0967 
0968 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
0969 {
0970     struct dwc3_request     *req;
0971 
0972     dwc3_stop_active_transfer(dep, true, false);
0973 
0974     /* - giveback all requests to gadget driver */
0975     while (!list_empty(&dep->started_list)) {
0976         req = next_request(&dep->started_list);
0977 
0978         dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
0979     }
0980 
0981     while (!list_empty(&dep->pending_list)) {
0982         req = next_request(&dep->pending_list);
0983 
0984         dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
0985     }
0986 
0987     while (!list_empty(&dep->cancelled_list)) {
0988         req = next_request(&dep->cancelled_list);
0989 
0990         dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
0991     }
0992 }
0993 
0994 /**
0995  * __dwc3_gadget_ep_disable - disables a hw endpoint
0996  * @dep: the endpoint to disable
0997  *
0998  * This function undoes what __dwc3_gadget_ep_enable did and also removes
0999  * requests which are currently being processed by the hardware and those which
1000  * are not yet scheduled.
1001  *
1002  * Caller should take care of locking.
1003  */
1004 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
1005 {
1006     struct dwc3     *dwc = dep->dwc;
1007     u32         reg;
1008 
1009     trace_dwc3_gadget_ep_disable(dep);
1010 
1011     /* make sure HW endpoint isn't stalled */
1012     if (dep->flags & DWC3_EP_STALL)
1013         __dwc3_gadget_ep_set_halt(dep, 0, false);
1014 
1015     reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
1016     reg &= ~DWC3_DALEPENA_EP(dep->number);
1017     dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
1018 
1019     /* Clear out the ep descriptors for non-ep0 */
1020     if (dep->number > 1) {
1021         dep->endpoint.comp_desc = NULL;
1022         dep->endpoint.desc = NULL;
1023     }
1024 
1025     dwc3_remove_requests(dwc, dep);
1026 
1027     dep->stream_capable = false;
1028     dep->type = 0;
1029     dep->flags &= DWC3_EP_TXFIFO_RESIZED;
1030 
1031     return 0;
1032 }
1033 
1034 /* -------------------------------------------------------------------------- */
1035 
1036 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
1037         const struct usb_endpoint_descriptor *desc)
1038 {
1039     return -EINVAL;
1040 }
1041 
1042 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
1043 {
1044     return -EINVAL;
1045 }
1046 
1047 /* -------------------------------------------------------------------------- */
1048 
1049 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
1050         const struct usb_endpoint_descriptor *desc)
1051 {
1052     struct dwc3_ep          *dep;
1053     struct dwc3         *dwc;
1054     unsigned long           flags;
1055     int             ret;
1056 
1057     if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
1058         pr_debug("dwc3: invalid parameters\n");
1059         return -EINVAL;
1060     }
1061 
1062     if (!desc->wMaxPacketSize) {
1063         pr_debug("dwc3: missing wMaxPacketSize\n");
1064         return -EINVAL;
1065     }
1066 
1067     dep = to_dwc3_ep(ep);
1068     dwc = dep->dwc;
1069 
1070     if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
1071                     "%s is already enabled\n",
1072                     dep->name))
1073         return 0;
1074 
1075     spin_lock_irqsave(&dwc->lock, flags);
1076     ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1077     spin_unlock_irqrestore(&dwc->lock, flags);
1078 
1079     return ret;
1080 }
1081 
1082 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
1083 {
1084     struct dwc3_ep          *dep;
1085     struct dwc3         *dwc;
1086     unsigned long           flags;
1087     int             ret;
1088 
1089     if (!ep) {
1090         pr_debug("dwc3: invalid parameters\n");
1091         return -EINVAL;
1092     }
1093 
1094     dep = to_dwc3_ep(ep);
1095     dwc = dep->dwc;
1096 
1097     if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
1098                     "%s is already disabled\n",
1099                     dep->name))
1100         return 0;
1101 
1102     spin_lock_irqsave(&dwc->lock, flags);
1103     ret = __dwc3_gadget_ep_disable(dep);
1104     spin_unlock_irqrestore(&dwc->lock, flags);
1105 
1106     return ret;
1107 }
1108 
1109 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
1110         gfp_t gfp_flags)
1111 {
1112     struct dwc3_request     *req;
1113     struct dwc3_ep          *dep = to_dwc3_ep(ep);
1114 
1115     req = kzalloc(sizeof(*req), gfp_flags);
1116     if (!req)
1117         return NULL;
1118 
1119     req->direction  = dep->direction;
1120     req->epnum  = dep->number;
1121     req->dep    = dep;
1122     req->status = DWC3_REQUEST_STATUS_UNKNOWN;
1123 
1124     trace_dwc3_alloc_request(req);
1125 
1126     return &req->request;
1127 }
1128 
1129 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
1130         struct usb_request *request)
1131 {
1132     struct dwc3_request     *req = to_dwc3_request(request);
1133 
1134     trace_dwc3_free_request(req);
1135     kfree(req);
1136 }
1137 
1138 /**
1139  * dwc3_ep_prev_trb - returns the previous TRB in the ring
1140  * @dep: The endpoint with the TRB ring
1141  * @index: The index of the current TRB in the ring
1142  *
1143  * Returns the TRB prior to the one pointed to by the index. If the
1144  * index is 0, we will wrap backwards, skip the link TRB, and return
1145  * the one just before that.
1146  */
1147 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
1148 {
1149     u8 tmp = index;
1150 
1151     if (!tmp)
1152         tmp = DWC3_TRB_NUM - 1;
1153 
1154     return &dep->trb_pool[tmp - 1];
1155 }
1156 
1157 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
1158 {
1159     u8          trbs_left;
1160 
1161     /*
1162      * If the enqueue & dequeue are equal then the TRB ring is either full
1163      * or empty. It's considered full when there are DWC3_TRB_NUM-1 of TRBs
1164      * pending to be processed by the driver.
1165      */
1166     if (dep->trb_enqueue == dep->trb_dequeue) {
1167         /*
1168          * If there is any request remained in the started_list at
1169          * this point, that means there is no TRB available.
1170          */
1171         if (!list_empty(&dep->started_list))
1172             return 0;
1173 
1174         return DWC3_TRB_NUM - 1;
1175     }
1176 
1177     trbs_left = dep->trb_dequeue - dep->trb_enqueue;
1178     trbs_left &= (DWC3_TRB_NUM - 1);
1179 
1180     if (dep->trb_dequeue < dep->trb_enqueue)
1181         trbs_left--;
1182 
1183     return trbs_left;
1184 }
1185 
1186 /**
1187  * dwc3_prepare_one_trb - setup one TRB from one request
1188  * @dep: endpoint for which this request is prepared
1189  * @req: dwc3_request pointer
1190  * @trb_length: buffer size of the TRB
1191  * @chain: should this TRB be chained to the next?
1192  * @node: only for isochronous endpoints. First TRB needs different type.
1193  * @use_bounce_buffer: set to use bounce buffer
1194  * @must_interrupt: set to interrupt on TRB completion
1195  */
1196 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1197         struct dwc3_request *req, unsigned int trb_length,
1198         unsigned int chain, unsigned int node, bool use_bounce_buffer,
1199         bool must_interrupt)
1200 {
1201     struct dwc3_trb     *trb;
1202     dma_addr_t      dma;
1203     unsigned int        stream_id = req->request.stream_id;
1204     unsigned int        short_not_ok = req->request.short_not_ok;
1205     unsigned int        no_interrupt = req->request.no_interrupt;
1206     unsigned int        is_last = req->request.is_last;
1207     struct dwc3     *dwc = dep->dwc;
1208     struct usb_gadget   *gadget = dwc->gadget;
1209     enum usb_device_speed   speed = gadget->speed;
1210 
1211     if (use_bounce_buffer)
1212         dma = dep->dwc->bounce_addr;
1213     else if (req->request.num_sgs > 0)
1214         dma = sg_dma_address(req->start_sg);
1215     else
1216         dma = req->request.dma;
1217 
1218     trb = &dep->trb_pool[dep->trb_enqueue];
1219 
1220     if (!req->trb) {
1221         dwc3_gadget_move_started_request(req);
1222         req->trb = trb;
1223         req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1224     }
1225 
1226     req->num_trbs++;
1227 
1228     trb->size = DWC3_TRB_SIZE_LENGTH(trb_length);
1229     trb->bpl = lower_32_bits(dma);
1230     trb->bph = upper_32_bits(dma);
1231 
1232     switch (usb_endpoint_type(dep->endpoint.desc)) {
1233     case USB_ENDPOINT_XFER_CONTROL:
1234         trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
1235         break;
1236 
1237     case USB_ENDPOINT_XFER_ISOC:
1238         if (!node) {
1239             trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
1240 
1241             /*
1242              * USB Specification 2.0 Section 5.9.2 states that: "If
1243              * there is only a single transaction in the microframe,
1244              * only a DATA0 data packet PID is used.  If there are
1245              * two transactions per microframe, DATA1 is used for
1246              * the first transaction data packet and DATA0 is used
1247              * for the second transaction data packet.  If there are
1248              * three transactions per microframe, DATA2 is used for
1249              * the first transaction data packet, DATA1 is used for
1250              * the second, and DATA0 is used for the third."
1251              *
1252              * IOW, we should satisfy the following cases:
1253              *
1254              * 1) length <= maxpacket
1255              *  - DATA0
1256              *
1257              * 2) maxpacket < length <= (2 * maxpacket)
1258              *  - DATA1, DATA0
1259              *
1260              * 3) (2 * maxpacket) < length <= (3 * maxpacket)
1261              *  - DATA2, DATA1, DATA0
1262              */
1263             if (speed == USB_SPEED_HIGH) {
1264                 struct usb_ep *ep = &dep->endpoint;
1265                 unsigned int mult = 2;
1266                 unsigned int maxp = usb_endpoint_maxp(ep->desc);
1267 
1268                 if (req->request.length <= (2 * maxp))
1269                     mult--;
1270 
1271                 if (req->request.length <= maxp)
1272                     mult--;
1273 
1274                 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
1275             }
1276         } else {
1277             trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
1278         }
1279 
1280         /* always enable Interrupt on Missed ISOC */
1281         trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1282         break;
1283 
1284     case USB_ENDPOINT_XFER_BULK:
1285     case USB_ENDPOINT_XFER_INT:
1286         trb->ctrl = DWC3_TRBCTL_NORMAL;
1287         break;
1288     default:
1289         /*
1290          * This is only possible with faulty memory because we
1291          * checked it already :)
1292          */
1293         dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
1294                 usb_endpoint_type(dep->endpoint.desc));
1295     }
1296 
1297     /*
1298      * Enable Continue on Short Packet
1299      * when endpoint is not a stream capable
1300      */
1301     if (usb_endpoint_dir_out(dep->endpoint.desc)) {
1302         if (!dep->stream_capable)
1303             trb->ctrl |= DWC3_TRB_CTRL_CSP;
1304 
1305         if (short_not_ok)
1306             trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
1307     }
1308 
1309     /* All TRBs setup for MST must set CSP=1 when LST=0 */
1310     if (dep->stream_capable && DWC3_MST_CAPABLE(&dwc->hwparams))
1311         trb->ctrl |= DWC3_TRB_CTRL_CSP;
1312 
1313     if ((!no_interrupt && !chain) || must_interrupt)
1314         trb->ctrl |= DWC3_TRB_CTRL_IOC;
1315 
1316     if (chain)
1317         trb->ctrl |= DWC3_TRB_CTRL_CHN;
1318     else if (dep->stream_capable && is_last &&
1319          !DWC3_MST_CAPABLE(&dwc->hwparams))
1320         trb->ctrl |= DWC3_TRB_CTRL_LST;
1321 
1322     if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1323         trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1324 
1325     /*
1326      * As per data book 4.2.3.2TRB Control Bit Rules section
1327      *
1328      * The controller autonomously checks the HWO field of a TRB to determine if the
1329      * entire TRB is valid. Therefore, software must ensure that the rest of the TRB
1330      * is valid before setting the HWO field to '1'. In most systems, this means that
1331      * software must update the fourth DWORD of a TRB last.
1332      *
1333      * However there is a possibility of CPU re-ordering here which can cause
1334      * controller to observe the HWO bit set prematurely.
1335      * Add a write memory barrier to prevent CPU re-ordering.
1336      */
1337     wmb();
1338     trb->ctrl |= DWC3_TRB_CTRL_HWO;
1339 
1340     dwc3_ep_inc_enq(dep);
1341 
1342     trace_dwc3_prepare_trb(dep, trb);
1343 }
1344 
1345 static bool dwc3_needs_extra_trb(struct dwc3_ep *dep, struct dwc3_request *req)
1346 {
1347     unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1348     unsigned int rem = req->request.length % maxp;
1349 
1350     if ((req->request.length && req->request.zero && !rem &&
1351             !usb_endpoint_xfer_isoc(dep->endpoint.desc)) ||
1352             (!req->direction && rem))
1353         return true;
1354 
1355     return false;
1356 }
1357 
1358 /**
1359  * dwc3_prepare_last_sg - prepare TRBs for the last SG entry
1360  * @dep: The endpoint that the request belongs to
1361  * @req: The request to prepare
1362  * @entry_length: The last SG entry size
1363  * @node: Indicates whether this is not the first entry (for isoc only)
1364  *
1365  * Return the number of TRBs prepared.
1366  */
1367 static int dwc3_prepare_last_sg(struct dwc3_ep *dep,
1368         struct dwc3_request *req, unsigned int entry_length,
1369         unsigned int node)
1370 {
1371     unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1372     unsigned int rem = req->request.length % maxp;
1373     unsigned int num_trbs = 1;
1374 
1375     if (dwc3_needs_extra_trb(dep, req))
1376         num_trbs++;
1377 
1378     if (dwc3_calc_trbs_left(dep) < num_trbs)
1379         return 0;
1380 
1381     req->needs_extra_trb = num_trbs > 1;
1382 
1383     /* Prepare a normal TRB */
1384     if (req->direction || req->request.length)
1385         dwc3_prepare_one_trb(dep, req, entry_length,
1386                 req->needs_extra_trb, node, false, false);
1387 
1388     /* Prepare extra TRBs for ZLP and MPS OUT transfer alignment */
1389     if ((!req->direction && !req->request.length) || req->needs_extra_trb)
1390         dwc3_prepare_one_trb(dep, req,
1391                 req->direction ? 0 : maxp - rem,
1392                 false, 1, true, false);
1393 
1394     return num_trbs;
1395 }
1396 
1397 static int dwc3_prepare_trbs_sg(struct dwc3_ep *dep,
1398         struct dwc3_request *req)
1399 {
1400     struct scatterlist *sg = req->start_sg;
1401     struct scatterlist *s;
1402     int     i;
1403     unsigned int length = req->request.length;
1404     unsigned int remaining = req->request.num_mapped_sgs
1405         - req->num_queued_sgs;
1406     unsigned int num_trbs = req->num_trbs;
1407     bool needs_extra_trb = dwc3_needs_extra_trb(dep, req);
1408 
1409     /*
1410      * If we resume preparing the request, then get the remaining length of
1411      * the request and resume where we left off.
1412      */
1413     for_each_sg(req->request.sg, s, req->num_queued_sgs, i)
1414         length -= sg_dma_len(s);
1415 
1416     for_each_sg(sg, s, remaining, i) {
1417         unsigned int num_trbs_left = dwc3_calc_trbs_left(dep);
1418         unsigned int trb_length;
1419         bool must_interrupt = false;
1420         bool last_sg = false;
1421 
1422         trb_length = min_t(unsigned int, length, sg_dma_len(s));
1423 
1424         length -= trb_length;
1425 
1426         /*
1427          * IOMMU driver is coalescing the list of sgs which shares a
1428          * page boundary into one and giving it to USB driver. With
1429          * this the number of sgs mapped is not equal to the number of
1430          * sgs passed. So mark the chain bit to false if it isthe last
1431          * mapped sg.
1432          */
1433         if ((i == remaining - 1) || !length)
1434             last_sg = true;
1435 
1436         if (!num_trbs_left)
1437             break;
1438 
1439         if (last_sg) {
1440             if (!dwc3_prepare_last_sg(dep, req, trb_length, i))
1441                 break;
1442         } else {
1443             /*
1444              * Look ahead to check if we have enough TRBs for the
1445              * next SG entry. If not, set interrupt on this TRB to
1446              * resume preparing the next SG entry when more TRBs are
1447              * free.
1448              */
1449             if (num_trbs_left == 1 || (needs_extra_trb &&
1450                     num_trbs_left <= 2 &&
1451                     sg_dma_len(sg_next(s)) >= length))
1452                 must_interrupt = true;
1453 
1454             dwc3_prepare_one_trb(dep, req, trb_length, 1, i, false,
1455                     must_interrupt);
1456         }
1457 
1458         /*
1459          * There can be a situation where all sgs in sglist are not
1460          * queued because of insufficient trb number. To handle this
1461          * case, update start_sg to next sg to be queued, so that
1462          * we have free trbs we can continue queuing from where we
1463          * previously stopped
1464          */
1465         if (!last_sg)
1466             req->start_sg = sg_next(s);
1467 
1468         req->num_queued_sgs++;
1469         req->num_pending_sgs--;
1470 
1471         /*
1472          * The number of pending SG entries may not correspond to the
1473          * number of mapped SG entries. If all the data are queued, then
1474          * don't include unused SG entries.
1475          */
1476         if (length == 0) {
1477             req->num_pending_sgs = 0;
1478             break;
1479         }
1480 
1481         if (must_interrupt)
1482             break;
1483     }
1484 
1485     return req->num_trbs - num_trbs;
1486 }
1487 
1488 static int dwc3_prepare_trbs_linear(struct dwc3_ep *dep,
1489         struct dwc3_request *req)
1490 {
1491     return dwc3_prepare_last_sg(dep, req, req->request.length, 0);
1492 }
1493 
1494 /*
1495  * dwc3_prepare_trbs - setup TRBs from requests
1496  * @dep: endpoint for which requests are being prepared
1497  *
1498  * The function goes through the requests list and sets up TRBs for the
1499  * transfers. The function returns once there are no more TRBs available or
1500  * it runs out of requests.
1501  *
1502  * Returns the number of TRBs prepared or negative errno.
1503  */
1504 static int dwc3_prepare_trbs(struct dwc3_ep *dep)
1505 {
1506     struct dwc3_request *req, *n;
1507     int         ret = 0;
1508 
1509     BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1510 
1511     /*
1512      * We can get in a situation where there's a request in the started list
1513      * but there weren't enough TRBs to fully kick it in the first time
1514      * around, so it has been waiting for more TRBs to be freed up.
1515      *
1516      * In that case, we should check if we have a request with pending_sgs
1517      * in the started list and prepare TRBs for that request first,
1518      * otherwise we will prepare TRBs completely out of order and that will
1519      * break things.
1520      */
1521     list_for_each_entry(req, &dep->started_list, list) {
1522         if (req->num_pending_sgs > 0) {
1523             ret = dwc3_prepare_trbs_sg(dep, req);
1524             if (!ret || req->num_pending_sgs)
1525                 return ret;
1526         }
1527 
1528         if (!dwc3_calc_trbs_left(dep))
1529             return ret;
1530 
1531         /*
1532          * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1533          * burst capability may try to read and use TRBs beyond the
1534          * active transfer instead of stopping.
1535          */
1536         if (dep->stream_capable && req->request.is_last &&
1537             !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1538             return ret;
1539     }
1540 
1541     list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1542         struct dwc3 *dwc = dep->dwc;
1543 
1544         ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1545                             dep->direction);
1546         if (ret)
1547             return ret;
1548 
1549         req->sg         = req->request.sg;
1550         req->start_sg       = req->sg;
1551         req->num_queued_sgs = 0;
1552         req->num_pending_sgs    = req->request.num_mapped_sgs;
1553 
1554         if (req->num_pending_sgs > 0) {
1555             ret = dwc3_prepare_trbs_sg(dep, req);
1556             if (req->num_pending_sgs)
1557                 return ret;
1558         } else {
1559             ret = dwc3_prepare_trbs_linear(dep, req);
1560         }
1561 
1562         if (!ret || !dwc3_calc_trbs_left(dep))
1563             return ret;
1564 
1565         /*
1566          * Don't prepare beyond a transfer. In DWC_usb32, its transfer
1567          * burst capability may try to read and use TRBs beyond the
1568          * active transfer instead of stopping.
1569          */
1570         if (dep->stream_capable && req->request.is_last &&
1571             !DWC3_MST_CAPABLE(&dwc->hwparams))
1572             return ret;
1573     }
1574 
1575     return ret;
1576 }
1577 
1578 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep);
1579 
1580 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1581 {
1582     struct dwc3_gadget_ep_cmd_params params;
1583     struct dwc3_request     *req;
1584     int             starting;
1585     int             ret;
1586     u32             cmd;
1587 
1588     /*
1589      * Note that it's normal to have no new TRBs prepared (i.e. ret == 0).
1590      * This happens when we need to stop and restart a transfer such as in
1591      * the case of reinitiating a stream or retrying an isoc transfer.
1592      */
1593     ret = dwc3_prepare_trbs(dep);
1594     if (ret < 0)
1595         return ret;
1596 
1597     starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1598 
1599     /*
1600      * If there's no new TRB prepared and we don't need to restart a
1601      * transfer, there's no need to update the transfer.
1602      */
1603     if (!ret && !starting)
1604         return ret;
1605 
1606     req = next_request(&dep->started_list);
1607     if (!req) {
1608         dep->flags |= DWC3_EP_PENDING_REQUEST;
1609         return 0;
1610     }
1611 
1612     memset(&params, 0, sizeof(params));
1613 
1614     if (starting) {
1615         params.param0 = upper_32_bits(req->trb_dma);
1616         params.param1 = lower_32_bits(req->trb_dma);
1617         cmd = DWC3_DEPCMD_STARTTRANSFER;
1618 
1619         if (dep->stream_capable)
1620             cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1621 
1622         if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1623             cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1624     } else {
1625         cmd = DWC3_DEPCMD_UPDATETRANSFER |
1626             DWC3_DEPCMD_PARAM(dep->resource_index);
1627     }
1628 
1629     ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1630     if (ret < 0) {
1631         struct dwc3_request *tmp;
1632 
1633         if (ret == -EAGAIN)
1634             return ret;
1635 
1636         dwc3_stop_active_transfer(dep, true, true);
1637 
1638         list_for_each_entry_safe(req, tmp, &dep->started_list, list)
1639             dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_DEQUEUED);
1640 
1641         /* If ep isn't started, then there's no end transfer pending */
1642         if (!(dep->flags & DWC3_EP_END_TRANSFER_PENDING))
1643             dwc3_gadget_ep_cleanup_cancelled_requests(dep);
1644 
1645         return ret;
1646     }
1647 
1648     if (dep->stream_capable && req->request.is_last &&
1649         !DWC3_MST_CAPABLE(&dep->dwc->hwparams))
1650         dep->flags |= DWC3_EP_WAIT_TRANSFER_COMPLETE;
1651 
1652     return 0;
1653 }
1654 
1655 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1656 {
1657     u32         reg;
1658 
1659     reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1660     return DWC3_DSTS_SOFFN(reg);
1661 }
1662 
1663 /**
1664  * __dwc3_stop_active_transfer - stop the current active transfer
1665  * @dep: isoc endpoint
1666  * @force: set forcerm bit in the command
1667  * @interrupt: command complete interrupt after End Transfer command
1668  *
1669  * When setting force, the ForceRM bit will be set. In that case
1670  * the controller won't update the TRB progress on command
1671  * completion. It also won't clear the HWO bit in the TRB.
1672  * The command will also not complete immediately in that case.
1673  */
1674 static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool interrupt)
1675 {
1676     struct dwc3_gadget_ep_cmd_params params;
1677     u32 cmd;
1678     int ret;
1679 
1680     cmd = DWC3_DEPCMD_ENDTRANSFER;
1681     cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
1682     cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
1683     cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
1684     memset(&params, 0, sizeof(params));
1685     ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1686     WARN_ON_ONCE(ret);
1687     dep->resource_index = 0;
1688 
1689     if (!interrupt)
1690         dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
1691     else if (!ret)
1692         dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
1693 
1694     return ret;
1695 }
1696 
1697 /**
1698  * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1699  * @dep: isoc endpoint
1700  *
1701  * This function tests for the correct combination of BIT[15:14] from the 16-bit
1702  * microframe number reported by the XferNotReady event for the future frame
1703  * number to start the isoc transfer.
1704  *
1705  * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1706  * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1707  * XferNotReady event are invalid. The driver uses this number to schedule the
1708  * isochronous transfer and passes it to the START TRANSFER command. Because
1709  * this number is invalid, the command may fail. If BIT[15:14] matches the
1710  * internal 16-bit microframe, the START TRANSFER command will pass and the
1711  * transfer will start at the scheduled time, if it is off by 1, the command
1712  * will still pass, but the transfer will start 2 seconds in the future. For all
1713  * other conditions, the START TRANSFER command will fail with bus-expiry.
1714  *
1715  * In order to workaround this issue, we can test for the correct combination of
1716  * BIT[15:14] by sending START TRANSFER commands with different values of
1717  * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1718  * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1719  * As the result, within the 4 possible combinations for BIT[15:14], there will
1720  * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1721  * command status will result in a 2-second delay start. The smaller BIT[15:14]
1722  * value is the correct combination.
1723  *
1724  * Since there are only 4 outcomes and the results are ordered, we can simply
1725  * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1726  * deduce the smaller successful combination.
1727  *
1728  * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1729  * of BIT[15:14]. The correct combination is as follow:
1730  *
1731  * if test0 fails and test1 passes, BIT[15:14] is 'b01
1732  * if test0 fails and test1 fails, BIT[15:14] is 'b10
1733  * if test0 passes and test1 fails, BIT[15:14] is 'b11
1734  * if test0 passes and test1 passes, BIT[15:14] is 'b00
1735  *
1736  * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1737  * endpoints.
1738  */
1739 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1740 {
1741     int cmd_status = 0;
1742     bool test0;
1743     bool test1;
1744 
1745     while (dep->combo_num < 2) {
1746         struct dwc3_gadget_ep_cmd_params params;
1747         u32 test_frame_number;
1748         u32 cmd;
1749 
1750         /*
1751          * Check if we can start isoc transfer on the next interval or
1752          * 4 uframes in the future with BIT[15:14] as dep->combo_num
1753          */
1754         test_frame_number = dep->frame_number & DWC3_FRNUMBER_MASK;
1755         test_frame_number |= dep->combo_num << 14;
1756         test_frame_number += max_t(u32, 4, dep->interval);
1757 
1758         params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1759         params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1760 
1761         cmd = DWC3_DEPCMD_STARTTRANSFER;
1762         cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1763         cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1764 
1765         /* Redo if some other failure beside bus-expiry is received */
1766         if (cmd_status && cmd_status != -EAGAIN) {
1767             dep->start_cmd_status = 0;
1768             dep->combo_num = 0;
1769             return 0;
1770         }
1771 
1772         /* Store the first test status */
1773         if (dep->combo_num == 0)
1774             dep->start_cmd_status = cmd_status;
1775 
1776         dep->combo_num++;
1777 
1778         /*
1779          * End the transfer if the START_TRANSFER command is successful
1780          * to wait for the next XferNotReady to test the command again
1781          */
1782         if (cmd_status == 0) {
1783             dwc3_stop_active_transfer(dep, true, true);
1784             return 0;
1785         }
1786     }
1787 
1788     /* test0 and test1 are both completed at this point */
1789     test0 = (dep->start_cmd_status == 0);
1790     test1 = (cmd_status == 0);
1791 
1792     if (!test0 && test1)
1793         dep->combo_num = 1;
1794     else if (!test0 && !test1)
1795         dep->combo_num = 2;
1796     else if (test0 && !test1)
1797         dep->combo_num = 3;
1798     else if (test0 && test1)
1799         dep->combo_num = 0;
1800 
1801     dep->frame_number &= DWC3_FRNUMBER_MASK;
1802     dep->frame_number |= dep->combo_num << 14;
1803     dep->frame_number += max_t(u32, 4, dep->interval);
1804 
1805     /* Reinitialize test variables */
1806     dep->start_cmd_status = 0;
1807     dep->combo_num = 0;
1808 
1809     return __dwc3_gadget_kick_transfer(dep);
1810 }
1811 
1812 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1813 {
1814     const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
1815     struct dwc3 *dwc = dep->dwc;
1816     int ret;
1817     int i;
1818 
1819     if (list_empty(&dep->pending_list) &&
1820         list_empty(&dep->started_list)) {
1821         dep->flags |= DWC3_EP_PENDING_REQUEST;
1822         return -EAGAIN;
1823     }
1824 
1825     if (!dwc->dis_start_transfer_quirk &&
1826         (DWC3_VER_IS_PRIOR(DWC31, 170A) ||
1827          DWC3_VER_TYPE_IS_WITHIN(DWC31, 170A, EA01, EA06))) {
1828         if (dwc->gadget->speed <= USB_SPEED_HIGH && dep->direction)
1829             return dwc3_gadget_start_isoc_quirk(dep);
1830     }
1831 
1832     if (desc->bInterval <= 14 &&
1833         dwc->gadget->speed >= USB_SPEED_HIGH) {
1834         u32 frame = __dwc3_gadget_get_frame(dwc);
1835         bool rollover = frame <
1836                 (dep->frame_number & DWC3_FRNUMBER_MASK);
1837 
1838         /*
1839          * frame_number is set from XferNotReady and may be already
1840          * out of date. DSTS only provides the lower 14 bit of the
1841          * current frame number. So add the upper two bits of
1842          * frame_number and handle a possible rollover.
1843          * This will provide the correct frame_number unless more than
1844          * rollover has happened since XferNotReady.
1845          */
1846 
1847         dep->frame_number = (dep->frame_number & ~DWC3_FRNUMBER_MASK) |
1848                      frame;
1849         if (rollover)
1850             dep->frame_number += BIT(14);
1851     }
1852 
1853     for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1854         int future_interval = i + 1;
1855 
1856         /* Give the controller at least 500us to schedule transfers */
1857         if (desc->bInterval < 3)
1858             future_interval += 3 - desc->bInterval;
1859 
1860         dep->frame_number = DWC3_ALIGN_FRAME(dep, future_interval);
1861 
1862         ret = __dwc3_gadget_kick_transfer(dep);
1863         if (ret != -EAGAIN)
1864             break;
1865     }
1866 
1867     /*
1868      * After a number of unsuccessful start attempts due to bus-expiry
1869      * status, issue END_TRANSFER command and retry on the next XferNotReady
1870      * event.
1871      */
1872     if (ret == -EAGAIN)
1873         ret = __dwc3_stop_active_transfer(dep, false, true);
1874 
1875     return ret;
1876 }
1877 
1878 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1879 {
1880     struct dwc3     *dwc = dep->dwc;
1881 
1882     if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
1883         dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
1884                 dep->name);
1885         return -ESHUTDOWN;
1886     }
1887 
1888     if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1889                 &req->request, req->dep->name))
1890         return -EINVAL;
1891 
1892     if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1893                 "%s: request %pK already in flight\n",
1894                 dep->name, &req->request))
1895         return -EINVAL;
1896 
1897     pm_runtime_get(dwc->dev);
1898 
1899     req->request.actual = 0;
1900     req->request.status = -EINPROGRESS;
1901 
1902     trace_dwc3_ep_queue(req);
1903 
1904     list_add_tail(&req->list, &dep->pending_list);
1905     req->status = DWC3_REQUEST_STATUS_QUEUED;
1906 
1907     if (dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)
1908         return 0;
1909 
1910     /*
1911      * Start the transfer only after the END_TRANSFER is completed
1912      * and endpoint STALL is cleared.
1913      */
1914     if ((dep->flags & DWC3_EP_END_TRANSFER_PENDING) ||
1915         (dep->flags & DWC3_EP_WEDGE) ||
1916         (dep->flags & DWC3_EP_DELAY_STOP) ||
1917         (dep->flags & DWC3_EP_STALL)) {
1918         dep->flags |= DWC3_EP_DELAY_START;
1919         return 0;
1920     }
1921 
1922     /*
1923      * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1924      * wait for a XferNotReady event so we will know what's the current
1925      * (micro-)frame number.
1926      *
1927      * Without this trick, we are very, very likely gonna get Bus Expiry
1928      * errors which will force us issue EndTransfer command.
1929      */
1930     if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1931         if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1932             if ((dep->flags & DWC3_EP_PENDING_REQUEST))
1933                 return __dwc3_gadget_start_isoc(dep);
1934 
1935             return 0;
1936         }
1937     }
1938 
1939     __dwc3_gadget_kick_transfer(dep);
1940 
1941     return 0;
1942 }
1943 
1944 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1945     gfp_t gfp_flags)
1946 {
1947     struct dwc3_request     *req = to_dwc3_request(request);
1948     struct dwc3_ep          *dep = to_dwc3_ep(ep);
1949     struct dwc3         *dwc = dep->dwc;
1950 
1951     unsigned long           flags;
1952 
1953     int             ret;
1954 
1955     spin_lock_irqsave(&dwc->lock, flags);
1956     ret = __dwc3_gadget_ep_queue(dep, req);
1957     spin_unlock_irqrestore(&dwc->lock, flags);
1958 
1959     return ret;
1960 }
1961 
1962 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
1963 {
1964     int i;
1965 
1966     /* If req->trb is not set, then the request has not started */
1967     if (!req->trb)
1968         return;
1969 
1970     /*
1971      * If request was already started, this means we had to
1972      * stop the transfer. With that we also need to ignore
1973      * all TRBs used by the request, however TRBs can only
1974      * be modified after completion of END_TRANSFER
1975      * command. So what we do here is that we wait for
1976      * END_TRANSFER completion and only after that, we jump
1977      * over TRBs by clearing HWO and incrementing dequeue
1978      * pointer.
1979      */
1980     for (i = 0; i < req->num_trbs; i++) {
1981         struct dwc3_trb *trb;
1982 
1983         trb = &dep->trb_pool[dep->trb_dequeue];
1984         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1985         dwc3_ep_inc_deq(dep);
1986     }
1987 
1988     req->num_trbs = 0;
1989 }
1990 
1991 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
1992 {
1993     struct dwc3_request     *req;
1994     struct dwc3         *dwc = dep->dwc;
1995 
1996     while (!list_empty(&dep->cancelled_list)) {
1997         req = next_request(&dep->cancelled_list);
1998         dwc3_gadget_ep_skip_trbs(dep, req);
1999         switch (req->status) {
2000         case DWC3_REQUEST_STATUS_DISCONNECTED:
2001             dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
2002             break;
2003         case DWC3_REQUEST_STATUS_DEQUEUED:
2004             dwc3_gadget_giveback(dep, req, -ECONNRESET);
2005             break;
2006         case DWC3_REQUEST_STATUS_STALLED:
2007             dwc3_gadget_giveback(dep, req, -EPIPE);
2008             break;
2009         default:
2010             dev_err(dwc->dev, "request cancelled with wrong reason:%d\n", req->status);
2011             dwc3_gadget_giveback(dep, req, -ECONNRESET);
2012             break;
2013         }
2014         /*
2015          * The endpoint is disabled, let the dwc3_remove_requests()
2016          * handle the cleanup.
2017          */
2018         if (!dep->endpoint.desc)
2019             break;
2020     }
2021 }
2022 
2023 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
2024         struct usb_request *request)
2025 {
2026     struct dwc3_request     *req = to_dwc3_request(request);
2027     struct dwc3_request     *r = NULL;
2028 
2029     struct dwc3_ep          *dep = to_dwc3_ep(ep);
2030     struct dwc3         *dwc = dep->dwc;
2031 
2032     unsigned long           flags;
2033     int             ret = 0;
2034 
2035     trace_dwc3_ep_dequeue(req);
2036 
2037     spin_lock_irqsave(&dwc->lock, flags);
2038 
2039     list_for_each_entry(r, &dep->cancelled_list, list) {
2040         if (r == req)
2041             goto out;
2042     }
2043 
2044     list_for_each_entry(r, &dep->pending_list, list) {
2045         if (r == req) {
2046             dwc3_gadget_giveback(dep, req, -ECONNRESET);
2047             goto out;
2048         }
2049     }
2050 
2051     list_for_each_entry(r, &dep->started_list, list) {
2052         if (r == req) {
2053             struct dwc3_request *t;
2054 
2055             /* wait until it is processed */
2056             dwc3_stop_active_transfer(dep, true, true);
2057 
2058             /*
2059              * Remove any started request if the transfer is
2060              * cancelled.
2061              */
2062             list_for_each_entry_safe(r, t, &dep->started_list, list)
2063                 dwc3_gadget_move_cancelled_request(r,
2064                         DWC3_REQUEST_STATUS_DEQUEUED);
2065 
2066             dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
2067 
2068             goto out;
2069         }
2070     }
2071 
2072     dev_err(dwc->dev, "request %pK was not queued to %s\n",
2073         request, ep->name);
2074     ret = -EINVAL;
2075 out:
2076     spin_unlock_irqrestore(&dwc->lock, flags);
2077 
2078     return ret;
2079 }
2080 
2081 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
2082 {
2083     struct dwc3_gadget_ep_cmd_params    params;
2084     struct dwc3             *dwc = dep->dwc;
2085     struct dwc3_request         *req;
2086     struct dwc3_request         *tmp;
2087     int                 ret;
2088 
2089     if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
2090         dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
2091         return -EINVAL;
2092     }
2093 
2094     memset(&params, 0x00, sizeof(params));
2095 
2096     if (value) {
2097         struct dwc3_trb *trb;
2098 
2099         unsigned int transfer_in_flight;
2100         unsigned int started;
2101 
2102         if (dep->number > 1)
2103             trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
2104         else
2105             trb = &dwc->ep0_trb[dep->trb_enqueue];
2106 
2107         transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
2108         started = !list_empty(&dep->started_list);
2109 
2110         if (!protocol && ((dep->direction && transfer_in_flight) ||
2111                 (!dep->direction && started))) {
2112             return -EAGAIN;
2113         }
2114 
2115         ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
2116                 &params);
2117         if (ret)
2118             dev_err(dwc->dev, "failed to set STALL on %s\n",
2119                     dep->name);
2120         else
2121             dep->flags |= DWC3_EP_STALL;
2122     } else {
2123         /*
2124          * Don't issue CLEAR_STALL command to control endpoints. The
2125          * controller automatically clears the STALL when it receives
2126          * the SETUP token.
2127          */
2128         if (dep->number <= 1) {
2129             dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2130             return 0;
2131         }
2132 
2133         dwc3_stop_active_transfer(dep, true, true);
2134 
2135         list_for_each_entry_safe(req, tmp, &dep->started_list, list)
2136             dwc3_gadget_move_cancelled_request(req, DWC3_REQUEST_STATUS_STALLED);
2137 
2138         if (dep->flags & DWC3_EP_END_TRANSFER_PENDING ||
2139             (dep->flags & DWC3_EP_DELAY_STOP)) {
2140             dep->flags |= DWC3_EP_PENDING_CLEAR_STALL;
2141             if (protocol)
2142                 dwc->clear_stall_protocol = dep->number;
2143 
2144             return 0;
2145         }
2146 
2147         dwc3_gadget_ep_cleanup_cancelled_requests(dep);
2148 
2149         ret = dwc3_send_clear_stall_ep_cmd(dep);
2150         if (ret) {
2151             dev_err(dwc->dev, "failed to clear STALL on %s\n",
2152                     dep->name);
2153             return ret;
2154         }
2155 
2156         dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
2157 
2158         if ((dep->flags & DWC3_EP_DELAY_START) &&
2159             !usb_endpoint_xfer_isoc(dep->endpoint.desc))
2160             __dwc3_gadget_kick_transfer(dep);
2161 
2162         dep->flags &= ~DWC3_EP_DELAY_START;
2163     }
2164 
2165     return ret;
2166 }
2167 
2168 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
2169 {
2170     struct dwc3_ep          *dep = to_dwc3_ep(ep);
2171     struct dwc3         *dwc = dep->dwc;
2172 
2173     unsigned long           flags;
2174 
2175     int             ret;
2176 
2177     spin_lock_irqsave(&dwc->lock, flags);
2178     ret = __dwc3_gadget_ep_set_halt(dep, value, false);
2179     spin_unlock_irqrestore(&dwc->lock, flags);
2180 
2181     return ret;
2182 }
2183 
2184 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
2185 {
2186     struct dwc3_ep          *dep = to_dwc3_ep(ep);
2187     struct dwc3         *dwc = dep->dwc;
2188     unsigned long           flags;
2189     int             ret;
2190 
2191     spin_lock_irqsave(&dwc->lock, flags);
2192     dep->flags |= DWC3_EP_WEDGE;
2193 
2194     if (dep->number == 0 || dep->number == 1)
2195         ret = __dwc3_gadget_ep0_set_halt(ep, 1);
2196     else
2197         ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
2198     spin_unlock_irqrestore(&dwc->lock, flags);
2199 
2200     return ret;
2201 }
2202 
2203 /* -------------------------------------------------------------------------- */
2204 
2205 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
2206     .bLength    = USB_DT_ENDPOINT_SIZE,
2207     .bDescriptorType = USB_DT_ENDPOINT,
2208     .bmAttributes   = USB_ENDPOINT_XFER_CONTROL,
2209 };
2210 
2211 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
2212     .enable     = dwc3_gadget_ep0_enable,
2213     .disable    = dwc3_gadget_ep0_disable,
2214     .alloc_request  = dwc3_gadget_ep_alloc_request,
2215     .free_request   = dwc3_gadget_ep_free_request,
2216     .queue      = dwc3_gadget_ep0_queue,
2217     .dequeue    = dwc3_gadget_ep_dequeue,
2218     .set_halt   = dwc3_gadget_ep0_set_halt,
2219     .set_wedge  = dwc3_gadget_ep_set_wedge,
2220 };
2221 
2222 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
2223     .enable     = dwc3_gadget_ep_enable,
2224     .disable    = dwc3_gadget_ep_disable,
2225     .alloc_request  = dwc3_gadget_ep_alloc_request,
2226     .free_request   = dwc3_gadget_ep_free_request,
2227     .queue      = dwc3_gadget_ep_queue,
2228     .dequeue    = dwc3_gadget_ep_dequeue,
2229     .set_halt   = dwc3_gadget_ep_set_halt,
2230     .set_wedge  = dwc3_gadget_ep_set_wedge,
2231 };
2232 
2233 /* -------------------------------------------------------------------------- */
2234 
2235 static int dwc3_gadget_get_frame(struct usb_gadget *g)
2236 {
2237     struct dwc3     *dwc = gadget_to_dwc(g);
2238 
2239     return __dwc3_gadget_get_frame(dwc);
2240 }
2241 
2242 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
2243 {
2244     int         retries;
2245 
2246     int         ret;
2247     u32         reg;
2248 
2249     u8          link_state;
2250 
2251     /*
2252      * According to the Databook Remote wakeup request should
2253      * be issued only when the device is in early suspend state.
2254      *
2255      * We can check that via USB Link State bits in DSTS register.
2256      */
2257     reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2258 
2259     link_state = DWC3_DSTS_USBLNKST(reg);
2260 
2261     switch (link_state) {
2262     case DWC3_LINK_STATE_RESET:
2263     case DWC3_LINK_STATE_RX_DET:    /* in HS, means Early Suspend */
2264     case DWC3_LINK_STATE_U3:    /* in HS, means SUSPEND */
2265     case DWC3_LINK_STATE_U2:    /* in HS, means Sleep (L1) */
2266     case DWC3_LINK_STATE_U1:
2267     case DWC3_LINK_STATE_RESUME:
2268         break;
2269     default:
2270         return -EINVAL;
2271     }
2272 
2273     ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
2274     if (ret < 0) {
2275         dev_err(dwc->dev, "failed to put link in Recovery\n");
2276         return ret;
2277     }
2278 
2279     /* Recent versions do this automatically */
2280     if (DWC3_VER_IS_PRIOR(DWC3, 194A)) {
2281         /* write zeroes to Link Change Request */
2282         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2283         reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
2284         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2285     }
2286 
2287     /* poll until Link State changes to ON */
2288     retries = 20000;
2289 
2290     while (retries--) {
2291         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2292 
2293         /* in HS, means ON */
2294         if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
2295             break;
2296     }
2297 
2298     if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
2299         dev_err(dwc->dev, "failed to send remote wakeup\n");
2300         return -EINVAL;
2301     }
2302 
2303     return 0;
2304 }
2305 
2306 static int dwc3_gadget_wakeup(struct usb_gadget *g)
2307 {
2308     struct dwc3     *dwc = gadget_to_dwc(g);
2309     unsigned long       flags;
2310     int         ret;
2311 
2312     spin_lock_irqsave(&dwc->lock, flags);
2313     ret = __dwc3_gadget_wakeup(dwc);
2314     spin_unlock_irqrestore(&dwc->lock, flags);
2315 
2316     return ret;
2317 }
2318 
2319 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
2320         int is_selfpowered)
2321 {
2322     struct dwc3     *dwc = gadget_to_dwc(g);
2323     unsigned long       flags;
2324 
2325     spin_lock_irqsave(&dwc->lock, flags);
2326     g->is_selfpowered = !!is_selfpowered;
2327     spin_unlock_irqrestore(&dwc->lock, flags);
2328 
2329     return 0;
2330 }
2331 
2332 static void dwc3_stop_active_transfers(struct dwc3 *dwc)
2333 {
2334     u32 epnum;
2335 
2336     for (epnum = 2; epnum < dwc->num_eps; epnum++) {
2337         struct dwc3_ep *dep;
2338 
2339         dep = dwc->eps[epnum];
2340         if (!dep)
2341             continue;
2342 
2343         dwc3_remove_requests(dwc, dep);
2344     }
2345 }
2346 
2347 static void __dwc3_gadget_set_ssp_rate(struct dwc3 *dwc)
2348 {
2349     enum usb_ssp_rate   ssp_rate = dwc->gadget_ssp_rate;
2350     u32         reg;
2351 
2352     if (ssp_rate == USB_SSP_GEN_UNKNOWN)
2353         ssp_rate = dwc->max_ssp_rate;
2354 
2355     reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2356     reg &= ~DWC3_DCFG_SPEED_MASK;
2357     reg &= ~DWC3_DCFG_NUMLANES(~0);
2358 
2359     if (ssp_rate == USB_SSP_GEN_1x2)
2360         reg |= DWC3_DCFG_SUPERSPEED;
2361     else if (dwc->max_ssp_rate != USB_SSP_GEN_1x2)
2362         reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2363 
2364     if (ssp_rate != USB_SSP_GEN_2x1 &&
2365         dwc->max_ssp_rate != USB_SSP_GEN_2x1)
2366         reg |= DWC3_DCFG_NUMLANES(1);
2367 
2368     dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2369 }
2370 
2371 static void __dwc3_gadget_set_speed(struct dwc3 *dwc)
2372 {
2373     enum usb_device_speed   speed;
2374     u32         reg;
2375 
2376     speed = dwc->gadget_max_speed;
2377     if (speed == USB_SPEED_UNKNOWN || speed > dwc->maximum_speed)
2378         speed = dwc->maximum_speed;
2379 
2380     if (speed == USB_SPEED_SUPER_PLUS &&
2381         DWC3_IP_IS(DWC32)) {
2382         __dwc3_gadget_set_ssp_rate(dwc);
2383         return;
2384     }
2385 
2386     reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2387     reg &= ~(DWC3_DCFG_SPEED_MASK);
2388 
2389     /*
2390      * WORKAROUND: DWC3 revision < 2.20a have an issue
2391      * which would cause metastability state on Run/Stop
2392      * bit if we try to force the IP to USB2-only mode.
2393      *
2394      * Because of that, we cannot configure the IP to any
2395      * speed other than the SuperSpeed
2396      *
2397      * Refers to:
2398      *
2399      * STAR#9000525659: Clock Domain Crossing on DCTL in
2400      * USB 2.0 Mode
2401      */
2402     if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
2403         !dwc->dis_metastability_quirk) {
2404         reg |= DWC3_DCFG_SUPERSPEED;
2405     } else {
2406         switch (speed) {
2407         case USB_SPEED_FULL:
2408             reg |= DWC3_DCFG_FULLSPEED;
2409             break;
2410         case USB_SPEED_HIGH:
2411             reg |= DWC3_DCFG_HIGHSPEED;
2412             break;
2413         case USB_SPEED_SUPER:
2414             reg |= DWC3_DCFG_SUPERSPEED;
2415             break;
2416         case USB_SPEED_SUPER_PLUS:
2417             if (DWC3_IP_IS(DWC3))
2418                 reg |= DWC3_DCFG_SUPERSPEED;
2419             else
2420                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2421             break;
2422         default:
2423             dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2424 
2425             if (DWC3_IP_IS(DWC3))
2426                 reg |= DWC3_DCFG_SUPERSPEED;
2427             else
2428                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2429         }
2430     }
2431 
2432     if (DWC3_IP_IS(DWC32) &&
2433         speed > USB_SPEED_UNKNOWN &&
2434         speed < USB_SPEED_SUPER_PLUS)
2435         reg &= ~DWC3_DCFG_NUMLANES(~0);
2436 
2437     dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2438 }
2439 
2440 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
2441 {
2442     u32         reg;
2443     u32         timeout = 500;
2444 
2445     if (pm_runtime_suspended(dwc->dev))
2446         return 0;
2447 
2448     reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2449     if (is_on) {
2450         if (DWC3_VER_IS_WITHIN(DWC3, ANY, 187A)) {
2451             reg &= ~DWC3_DCTL_TRGTULST_MASK;
2452             reg |= DWC3_DCTL_TRGTULST_RX_DET;
2453         }
2454 
2455         if (!DWC3_VER_IS_PRIOR(DWC3, 194A))
2456             reg &= ~DWC3_DCTL_KEEP_CONNECT;
2457         reg |= DWC3_DCTL_RUN_STOP;
2458 
2459         if (dwc->has_hibernation)
2460             reg |= DWC3_DCTL_KEEP_CONNECT;
2461 
2462         __dwc3_gadget_set_speed(dwc);
2463         dwc->pullups_connected = true;
2464     } else {
2465         reg &= ~DWC3_DCTL_RUN_STOP;
2466 
2467         if (dwc->has_hibernation && !suspend)
2468             reg &= ~DWC3_DCTL_KEEP_CONNECT;
2469 
2470         dwc->pullups_connected = false;
2471     }
2472 
2473     dwc3_gadget_dctl_write_safe(dwc, reg);
2474 
2475     do {
2476         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2477         reg &= DWC3_DSTS_DEVCTRLHLT;
2478     } while (--timeout && !(!is_on ^ !reg));
2479 
2480     if (!timeout)
2481         return -ETIMEDOUT;
2482 
2483     return 0;
2484 }
2485 
2486 static void dwc3_gadget_disable_irq(struct dwc3 *dwc);
2487 static void __dwc3_gadget_stop(struct dwc3 *dwc);
2488 static int __dwc3_gadget_start(struct dwc3 *dwc);
2489 
2490 static int dwc3_gadget_soft_disconnect(struct dwc3 *dwc)
2491 {
2492     unsigned long flags;
2493 
2494     spin_lock_irqsave(&dwc->lock, flags);
2495     dwc->connected = false;
2496 
2497     /*
2498      * Per databook, when we want to stop the gadget, if a control transfer
2499      * is still in process, complete it and get the core into setup phase.
2500      */
2501     if (dwc->ep0state != EP0_SETUP_PHASE) {
2502         int ret;
2503 
2504         reinit_completion(&dwc->ep0_in_setup);
2505 
2506         spin_unlock_irqrestore(&dwc->lock, flags);
2507         ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
2508                 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
2509         spin_lock_irqsave(&dwc->lock, flags);
2510         if (ret == 0)
2511             dev_warn(dwc->dev, "timed out waiting for SETUP phase\n");
2512     }
2513 
2514     /*
2515      * In the Synopsys DesignWare Cores USB3 Databook Rev. 3.30a
2516      * Section 4.1.8 Table 4-7, it states that for a device-initiated
2517      * disconnect, the SW needs to ensure that it sends "a DEPENDXFER
2518      * command for any active transfers" before clearing the RunStop
2519      * bit.
2520      */
2521     dwc3_stop_active_transfers(dwc);
2522     __dwc3_gadget_stop(dwc);
2523     spin_unlock_irqrestore(&dwc->lock, flags);
2524 
2525     /*
2526      * Note: if the GEVNTCOUNT indicates events in the event buffer, the
2527      * driver needs to acknowledge them before the controller can halt.
2528      * Simply let the interrupt handler acknowledges and handle the
2529      * remaining event generated by the controller while polling for
2530      * DSTS.DEVCTLHLT.
2531      */
2532     return dwc3_gadget_run_stop(dwc, false, false);
2533 }
2534 
2535 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
2536 {
2537     struct dwc3     *dwc = gadget_to_dwc(g);
2538     int         ret;
2539 
2540     is_on = !!is_on;
2541 
2542     dwc->softconnect = is_on;
2543 
2544     /*
2545      * Avoid issuing a runtime resume if the device is already in the
2546      * suspended state during gadget disconnect.  DWC3 gadget was already
2547      * halted/stopped during runtime suspend.
2548      */
2549     if (!is_on) {
2550         pm_runtime_barrier(dwc->dev);
2551         if (pm_runtime_suspended(dwc->dev))
2552             return 0;
2553     }
2554 
2555     /*
2556      * Check the return value for successful resume, or error.  For a
2557      * successful resume, the DWC3 runtime PM resume routine will handle
2558      * the run stop sequence, so avoid duplicate operations here.
2559      */
2560     ret = pm_runtime_get_sync(dwc->dev);
2561     if (!ret || ret < 0) {
2562         pm_runtime_put(dwc->dev);
2563         return 0;
2564     }
2565 
2566     if (dwc->pullups_connected == is_on) {
2567         pm_runtime_put(dwc->dev);
2568         return 0;
2569     }
2570 
2571     if (!is_on) {
2572         ret = dwc3_gadget_soft_disconnect(dwc);
2573     } else {
2574         /*
2575          * In the Synopsys DWC_usb31 1.90a programming guide section
2576          * 4.1.9, it specifies that for a reconnect after a
2577          * device-initiated disconnect requires a core soft reset
2578          * (DCTL.CSftRst) before enabling the run/stop bit.
2579          */
2580         dwc3_core_soft_reset(dwc);
2581 
2582         dwc3_event_buffers_setup(dwc);
2583         __dwc3_gadget_start(dwc);
2584         ret = dwc3_gadget_run_stop(dwc, true, false);
2585     }
2586 
2587     pm_runtime_put(dwc->dev);
2588 
2589     return ret;
2590 }
2591 
2592 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
2593 {
2594     u32         reg;
2595 
2596     /* Enable all but Start and End of Frame IRQs */
2597     reg = (DWC3_DEVTEN_EVNTOVERFLOWEN |
2598             DWC3_DEVTEN_CMDCMPLTEN |
2599             DWC3_DEVTEN_ERRTICERREN |
2600             DWC3_DEVTEN_WKUPEVTEN |
2601             DWC3_DEVTEN_CONNECTDONEEN |
2602             DWC3_DEVTEN_USBRSTEN |
2603             DWC3_DEVTEN_DISCONNEVTEN);
2604 
2605     if (DWC3_VER_IS_PRIOR(DWC3, 250A))
2606         reg |= DWC3_DEVTEN_ULSTCNGEN;
2607 
2608     /* On 2.30a and above this bit enables U3/L2-L1 Suspend Events */
2609     if (!DWC3_VER_IS_PRIOR(DWC3, 230A))
2610         reg |= DWC3_DEVTEN_U3L2L1SUSPEN;
2611 
2612     dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
2613 }
2614 
2615 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
2616 {
2617     /* mask all interrupts */
2618     dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
2619 }
2620 
2621 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
2622 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
2623 
2624 /**
2625  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
2626  * @dwc: pointer to our context structure
2627  *
2628  * The following looks like complex but it's actually very simple. In order to
2629  * calculate the number of packets we can burst at once on OUT transfers, we're
2630  * gonna use RxFIFO size.
2631  *
2632  * To calculate RxFIFO size we need two numbers:
2633  * MDWIDTH = size, in bits, of the internal memory bus
2634  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
2635  *
2636  * Given these two numbers, the formula is simple:
2637  *
2638  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
2639  *
2640  * 24 bytes is for 3x SETUP packets
2641  * 16 bytes is a clock domain crossing tolerance
2642  *
2643  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
2644  */
2645 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
2646 {
2647     u32 ram2_depth;
2648     u32 mdwidth;
2649     u32 nump;
2650     u32 reg;
2651 
2652     ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
2653     mdwidth = dwc3_mdwidth(dwc);
2654 
2655     nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
2656     nump = min_t(u32, nump, 16);
2657 
2658     /* update NumP */
2659     reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2660     reg &= ~DWC3_DCFG_NUMP_MASK;
2661     reg |= nump << DWC3_DCFG_NUMP_SHIFT;
2662     dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2663 }
2664 
2665 static int __dwc3_gadget_start(struct dwc3 *dwc)
2666 {
2667     struct dwc3_ep      *dep;
2668     int         ret = 0;
2669     u32         reg;
2670 
2671     /*
2672      * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
2673      * the core supports IMOD, disable it.
2674      */
2675     if (dwc->imod_interval) {
2676         dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
2677         dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
2678     } else if (dwc3_has_imod(dwc)) {
2679         dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
2680     }
2681 
2682     /*
2683      * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
2684      * field instead of letting dwc3 itself calculate that automatically.
2685      *
2686      * This way, we maximize the chances that we'll be able to get several
2687      * bursts of data without going through any sort of endpoint throttling.
2688      */
2689     reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
2690     if (DWC3_IP_IS(DWC3))
2691         reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
2692     else
2693         reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
2694 
2695     dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
2696 
2697     dwc3_gadget_setup_nump(dwc);
2698 
2699     /*
2700      * Currently the controller handles single stream only. So, Ignore
2701      * Packet Pending bit for stream selection and don't search for another
2702      * stream if the host sends Data Packet with PP=0 (for OUT direction) or
2703      * ACK with NumP=0 and PP=0 (for IN direction). This slightly improves
2704      * the stream performance.
2705      */
2706     reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2707     reg |= DWC3_DCFG_IGNSTRMPP;
2708     dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2709 
2710     /* Enable MST by default if the device is capable of MST */
2711     if (DWC3_MST_CAPABLE(&dwc->hwparams)) {
2712         reg = dwc3_readl(dwc->regs, DWC3_DCFG1);
2713         reg &= ~DWC3_DCFG1_DIS_MST_ENH;
2714         dwc3_writel(dwc->regs, DWC3_DCFG1, reg);
2715     }
2716 
2717     /* Start with SuperSpeed Default */
2718     dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2719 
2720     dep = dwc->eps[0];
2721     ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2722     if (ret) {
2723         dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2724         goto err0;
2725     }
2726 
2727     dep = dwc->eps[1];
2728     ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
2729     if (ret) {
2730         dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2731         goto err1;
2732     }
2733 
2734     /* begin to receive SETUP packets */
2735     dwc->ep0state = EP0_SETUP_PHASE;
2736     dwc->ep0_bounced = false;
2737     dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2738     dwc->delayed_status = false;
2739     dwc3_ep0_out_start(dwc);
2740 
2741     dwc3_gadget_enable_irq(dwc);
2742 
2743     return 0;
2744 
2745 err1:
2746     __dwc3_gadget_ep_disable(dwc->eps[0]);
2747 
2748 err0:
2749     return ret;
2750 }
2751 
2752 static int dwc3_gadget_start(struct usb_gadget *g,
2753         struct usb_gadget_driver *driver)
2754 {
2755     struct dwc3     *dwc = gadget_to_dwc(g);
2756     unsigned long       flags;
2757     int         ret;
2758     int         irq;
2759 
2760     irq = dwc->irq_gadget;
2761     ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2762             IRQF_SHARED, "dwc3", dwc->ev_buf);
2763     if (ret) {
2764         dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2765                 irq, ret);
2766         return ret;
2767     }
2768 
2769     spin_lock_irqsave(&dwc->lock, flags);
2770     dwc->gadget_driver  = driver;
2771     spin_unlock_irqrestore(&dwc->lock, flags);
2772 
2773     return 0;
2774 }
2775 
2776 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2777 {
2778     dwc3_gadget_disable_irq(dwc);
2779     __dwc3_gadget_ep_disable(dwc->eps[0]);
2780     __dwc3_gadget_ep_disable(dwc->eps[1]);
2781 }
2782 
2783 static int dwc3_gadget_stop(struct usb_gadget *g)
2784 {
2785     struct dwc3     *dwc = gadget_to_dwc(g);
2786     unsigned long       flags;
2787 
2788     spin_lock_irqsave(&dwc->lock, flags);
2789     dwc->gadget_driver  = NULL;
2790     dwc->max_cfg_eps = 0;
2791     spin_unlock_irqrestore(&dwc->lock, flags);
2792 
2793     free_irq(dwc->irq_gadget, dwc->ev_buf);
2794 
2795     return 0;
2796 }
2797 
2798 static void dwc3_gadget_config_params(struct usb_gadget *g,
2799                       struct usb_dcd_config_params *params)
2800 {
2801     struct dwc3     *dwc = gadget_to_dwc(g);
2802 
2803     params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2804     params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2805 
2806     /* Recommended BESL */
2807     if (!dwc->dis_enblslpm_quirk) {
2808         /*
2809          * If the recommended BESL baseline is 0 or if the BESL deep is
2810          * less than 2, Microsoft's Windows 10 host usb stack will issue
2811          * a usb reset immediately after it receives the extended BOS
2812          * descriptor and the enumeration will fail. To maintain
2813          * compatibility with the Windows' usb stack, let's set the
2814          * recommended BESL baseline to 1 and clamp the BESL deep to be
2815          * within 2 to 15.
2816          */
2817         params->besl_baseline = 1;
2818         if (dwc->is_utmi_l1_suspend)
2819             params->besl_deep =
2820                 clamp_t(u8, dwc->hird_threshold, 2, 15);
2821     }
2822 
2823     /* U1 Device exit Latency */
2824     if (dwc->dis_u1_entry_quirk)
2825         params->bU1devExitLat = 0;
2826     else
2827         params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
2828 
2829     /* U2 Device exit Latency */
2830     if (dwc->dis_u2_entry_quirk)
2831         params->bU2DevExitLat = 0;
2832     else
2833         params->bU2DevExitLat =
2834                 cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
2835 }
2836 
2837 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2838                   enum usb_device_speed speed)
2839 {
2840     struct dwc3     *dwc = gadget_to_dwc(g);
2841     unsigned long       flags;
2842 
2843     spin_lock_irqsave(&dwc->lock, flags);
2844     dwc->gadget_max_speed = speed;
2845     spin_unlock_irqrestore(&dwc->lock, flags);
2846 }
2847 
2848 static void dwc3_gadget_set_ssp_rate(struct usb_gadget *g,
2849                      enum usb_ssp_rate rate)
2850 {
2851     struct dwc3     *dwc = gadget_to_dwc(g);
2852     unsigned long       flags;
2853 
2854     spin_lock_irqsave(&dwc->lock, flags);
2855     dwc->gadget_max_speed = USB_SPEED_SUPER_PLUS;
2856     dwc->gadget_ssp_rate = rate;
2857     spin_unlock_irqrestore(&dwc->lock, flags);
2858 }
2859 
2860 static int dwc3_gadget_vbus_draw(struct usb_gadget *g, unsigned int mA)
2861 {
2862     struct dwc3     *dwc = gadget_to_dwc(g);
2863     union power_supply_propval  val = {0};
2864     int             ret;
2865 
2866     if (dwc->usb2_phy)
2867         return usb_phy_set_power(dwc->usb2_phy, mA);
2868 
2869     if (!dwc->usb_psy)
2870         return -EOPNOTSUPP;
2871 
2872     val.intval = 1000 * mA;
2873     ret = power_supply_set_property(dwc->usb_psy, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT, &val);
2874 
2875     return ret;
2876 }
2877 
2878 /**
2879  * dwc3_gadget_check_config - ensure dwc3 can support the USB configuration
2880  * @g: pointer to the USB gadget
2881  *
2882  * Used to record the maximum number of endpoints being used in a USB composite
2883  * device. (across all configurations)  This is to be used in the calculation
2884  * of the TXFIFO sizes when resizing internal memory for individual endpoints.
2885  * It will help ensured that the resizing logic reserves enough space for at
2886  * least one max packet.
2887  */
2888 static int dwc3_gadget_check_config(struct usb_gadget *g)
2889 {
2890     struct dwc3 *dwc = gadget_to_dwc(g);
2891     struct usb_ep *ep;
2892     int fifo_size = 0;
2893     int ram1_depth;
2894     int ep_num = 0;
2895 
2896     if (!dwc->do_fifo_resize)
2897         return 0;
2898 
2899     list_for_each_entry(ep, &g->ep_list, ep_list) {
2900         /* Only interested in the IN endpoints */
2901         if (ep->claimed && (ep->address & USB_DIR_IN))
2902             ep_num++;
2903     }
2904 
2905     if (ep_num <= dwc->max_cfg_eps)
2906         return 0;
2907 
2908     /* Update the max number of eps in the composition */
2909     dwc->max_cfg_eps = ep_num;
2910 
2911     fifo_size = dwc3_gadget_calc_tx_fifo_size(dwc, dwc->max_cfg_eps);
2912     /* Based on the equation, increment by one for every ep */
2913     fifo_size += dwc->max_cfg_eps;
2914 
2915     /* Check if we can fit a single fifo per endpoint */
2916     ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
2917     if (fifo_size > ram1_depth)
2918         return -ENOMEM;
2919 
2920     return 0;
2921 }
2922 
2923 static void dwc3_gadget_async_callbacks(struct usb_gadget *g, bool enable)
2924 {
2925     struct dwc3     *dwc = gadget_to_dwc(g);
2926     unsigned long       flags;
2927 
2928     spin_lock_irqsave(&dwc->lock, flags);
2929     dwc->async_callbacks = enable;
2930     spin_unlock_irqrestore(&dwc->lock, flags);
2931 }
2932 
2933 static const struct usb_gadget_ops dwc3_gadget_ops = {
2934     .get_frame      = dwc3_gadget_get_frame,
2935     .wakeup         = dwc3_gadget_wakeup,
2936     .set_selfpowered    = dwc3_gadget_set_selfpowered,
2937     .pullup         = dwc3_gadget_pullup,
2938     .udc_start      = dwc3_gadget_start,
2939     .udc_stop       = dwc3_gadget_stop,
2940     .udc_set_speed      = dwc3_gadget_set_speed,
2941     .udc_set_ssp_rate   = dwc3_gadget_set_ssp_rate,
2942     .get_config_params  = dwc3_gadget_config_params,
2943     .vbus_draw      = dwc3_gadget_vbus_draw,
2944     .check_config       = dwc3_gadget_check_config,
2945     .udc_async_callbacks    = dwc3_gadget_async_callbacks,
2946 };
2947 
2948 /* -------------------------------------------------------------------------- */
2949 
2950 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2951 {
2952     struct dwc3 *dwc = dep->dwc;
2953 
2954     usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2955     dep->endpoint.maxburst = 1;
2956     dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2957     if (!dep->direction)
2958         dwc->gadget->ep0 = &dep->endpoint;
2959 
2960     dep->endpoint.caps.type_control = true;
2961 
2962     return 0;
2963 }
2964 
2965 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2966 {
2967     struct dwc3 *dwc = dep->dwc;
2968     u32 mdwidth;
2969     int size;
2970     int maxpacket;
2971 
2972     mdwidth = dwc3_mdwidth(dwc);
2973 
2974     /* MDWIDTH is represented in bits, we need it in bytes */
2975     mdwidth /= 8;
2976 
2977     size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2978     if (DWC3_IP_IS(DWC3))
2979         size = DWC3_GTXFIFOSIZ_TXFDEP(size);
2980     else
2981         size = DWC31_GTXFIFOSIZ_TXFDEP(size);
2982 
2983     /*
2984      * maxpacket size is determined as part of the following, after assuming
2985      * a mult value of one maxpacket:
2986      * DWC3 revision 280A and prior:
2987      * fifo_size = mult * (max_packet / mdwidth) + 1;
2988      * maxpacket = mdwidth * (fifo_size - 1);
2989      *
2990      * DWC3 revision 290A and onwards:
2991      * fifo_size = mult * ((max_packet + mdwidth)/mdwidth + 1) + 1
2992      * maxpacket = mdwidth * ((fifo_size - 1) - 1) - mdwidth;
2993      */
2994     if (DWC3_VER_IS_PRIOR(DWC3, 290A))
2995         maxpacket = mdwidth * (size - 1);
2996     else
2997         maxpacket = mdwidth * ((size - 1) - 1) - mdwidth;
2998 
2999     /* Functionally, space for one max packet is sufficient */
3000     size = min_t(int, maxpacket, 1024);
3001     usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3002 
3003     dep->endpoint.max_streams = 16;
3004     dep->endpoint.ops = &dwc3_gadget_ep_ops;
3005     list_add_tail(&dep->endpoint.ep_list,
3006             &dwc->gadget->ep_list);
3007     dep->endpoint.caps.type_iso = true;
3008     dep->endpoint.caps.type_bulk = true;
3009     dep->endpoint.caps.type_int = true;
3010 
3011     return dwc3_alloc_trb_pool(dep);
3012 }
3013 
3014 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
3015 {
3016     struct dwc3 *dwc = dep->dwc;
3017     u32 mdwidth;
3018     int size;
3019 
3020     mdwidth = dwc3_mdwidth(dwc);
3021 
3022     /* MDWIDTH is represented in bits, convert to bytes */
3023     mdwidth /= 8;
3024 
3025     /* All OUT endpoints share a single RxFIFO space */
3026     size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
3027     if (DWC3_IP_IS(DWC3))
3028         size = DWC3_GRXFIFOSIZ_RXFDEP(size);
3029     else
3030         size = DWC31_GRXFIFOSIZ_RXFDEP(size);
3031 
3032     /* FIFO depth is in MDWDITH bytes */
3033     size *= mdwidth;
3034 
3035     /*
3036      * To meet performance requirement, a minimum recommended RxFIFO size
3037      * is defined as follow:
3038      * RxFIFO size >= (3 x MaxPacketSize) +
3039      * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
3040      *
3041      * Then calculate the max packet limit as below.
3042      */
3043     size -= (3 * 8) + 16;
3044     if (size < 0)
3045         size = 0;
3046     else
3047         size /= 3;
3048 
3049     usb_ep_set_maxpacket_limit(&dep->endpoint, size);
3050     dep->endpoint.max_streams = 16;
3051     dep->endpoint.ops = &dwc3_gadget_ep_ops;
3052     list_add_tail(&dep->endpoint.ep_list,
3053             &dwc->gadget->ep_list);
3054     dep->endpoint.caps.type_iso = true;
3055     dep->endpoint.caps.type_bulk = true;
3056     dep->endpoint.caps.type_int = true;
3057 
3058     return dwc3_alloc_trb_pool(dep);
3059 }
3060 
3061 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
3062 {
3063     struct dwc3_ep          *dep;
3064     bool                direction = epnum & 1;
3065     int             ret;
3066     u8              num = epnum >> 1;
3067 
3068     dep = kzalloc(sizeof(*dep), GFP_KERNEL);
3069     if (!dep)
3070         return -ENOMEM;
3071 
3072     dep->dwc = dwc;
3073     dep->number = epnum;
3074     dep->direction = direction;
3075     dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
3076     dwc->eps[epnum] = dep;
3077     dep->combo_num = 0;
3078     dep->start_cmd_status = 0;
3079 
3080     snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
3081             direction ? "in" : "out");
3082 
3083     dep->endpoint.name = dep->name;
3084 
3085     if (!(dep->number > 1)) {
3086         dep->endpoint.desc = &dwc3_gadget_ep0_desc;
3087         dep->endpoint.comp_desc = NULL;
3088     }
3089 
3090     if (num == 0)
3091         ret = dwc3_gadget_init_control_endpoint(dep);
3092     else if (direction)
3093         ret = dwc3_gadget_init_in_endpoint(dep);
3094     else
3095         ret = dwc3_gadget_init_out_endpoint(dep);
3096 
3097     if (ret)
3098         return ret;
3099 
3100     dep->endpoint.caps.dir_in = direction;
3101     dep->endpoint.caps.dir_out = !direction;
3102 
3103     INIT_LIST_HEAD(&dep->pending_list);
3104     INIT_LIST_HEAD(&dep->started_list);
3105     INIT_LIST_HEAD(&dep->cancelled_list);
3106 
3107     dwc3_debugfs_create_endpoint_dir(dep);
3108 
3109     return 0;
3110 }
3111 
3112 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
3113 {
3114     u8              epnum;
3115 
3116     INIT_LIST_HEAD(&dwc->gadget->ep_list);
3117 
3118     for (epnum = 0; epnum < total; epnum++) {
3119         int         ret;
3120 
3121         ret = dwc3_gadget_init_endpoint(dwc, epnum);
3122         if (ret)
3123             return ret;
3124     }
3125 
3126     return 0;
3127 }
3128 
3129 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
3130 {
3131     struct dwc3_ep          *dep;
3132     u8              epnum;
3133 
3134     for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3135         dep = dwc->eps[epnum];
3136         if (!dep)
3137             continue;
3138         /*
3139          * Physical endpoints 0 and 1 are special; they form the
3140          * bi-directional USB endpoint 0.
3141          *
3142          * For those two physical endpoints, we don't allocate a TRB
3143          * pool nor do we add them the endpoints list. Due to that, we
3144          * shouldn't do these two operations otherwise we would end up
3145          * with all sorts of bugs when removing dwc3.ko.
3146          */
3147         if (epnum != 0 && epnum != 1) {
3148             dwc3_free_trb_pool(dep);
3149             list_del(&dep->endpoint.ep_list);
3150         }
3151 
3152         debugfs_remove_recursive(debugfs_lookup(dep->name,
3153                 debugfs_lookup(dev_name(dep->dwc->dev),
3154                            usb_debug_root)));
3155         kfree(dep);
3156     }
3157 }
3158 
3159 /* -------------------------------------------------------------------------- */
3160 
3161 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
3162         struct dwc3_request *req, struct dwc3_trb *trb,
3163         const struct dwc3_event_depevt *event, int status, int chain)
3164 {
3165     unsigned int        count;
3166 
3167     dwc3_ep_inc_deq(dep);
3168 
3169     trace_dwc3_complete_trb(dep, trb);
3170     req->num_trbs--;
3171 
3172     /*
3173      * If we're in the middle of series of chained TRBs and we
3174      * receive a short transfer along the way, DWC3 will skip
3175      * through all TRBs including the last TRB in the chain (the
3176      * where CHN bit is zero. DWC3 will also avoid clearing HWO
3177      * bit and SW has to do it manually.
3178      *
3179      * We're going to do that here to avoid problems of HW trying
3180      * to use bogus TRBs for transfers.
3181      */
3182     if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
3183         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3184 
3185     /*
3186      * For isochronous transfers, the first TRB in a service interval must
3187      * have the Isoc-First type. Track and report its interval frame number.
3188      */
3189     if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3190         (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
3191         unsigned int frame_number;
3192 
3193         frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
3194         frame_number &= ~(dep->interval - 1);
3195         req->request.frame_number = frame_number;
3196     }
3197 
3198     /*
3199      * We use bounce buffer for requests that needs extra TRB or OUT ZLP. If
3200      * this TRB points to the bounce buffer address, it's a MPS alignment
3201      * TRB. Don't add it to req->remaining calculation.
3202      */
3203     if (trb->bpl == lower_32_bits(dep->dwc->bounce_addr) &&
3204         trb->bph == upper_32_bits(dep->dwc->bounce_addr)) {
3205         trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
3206         return 1;
3207     }
3208 
3209     count = trb->size & DWC3_TRB_SIZE_MASK;
3210     req->remaining += count;
3211 
3212     if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
3213         return 1;
3214 
3215     if (event->status & DEPEVT_STATUS_SHORT && !chain)
3216         return 1;
3217 
3218     if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
3219         (trb->ctrl & DWC3_TRB_CTRL_LST))
3220         return 1;
3221 
3222     return 0;
3223 }
3224 
3225 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
3226         struct dwc3_request *req, const struct dwc3_event_depevt *event,
3227         int status)
3228 {
3229     struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3230     struct scatterlist *sg = req->sg;
3231     struct scatterlist *s;
3232     unsigned int num_queued = req->num_queued_sgs;
3233     unsigned int i;
3234     int ret = 0;
3235 
3236     for_each_sg(sg, s, num_queued, i) {
3237         trb = &dep->trb_pool[dep->trb_dequeue];
3238 
3239         req->sg = sg_next(s);
3240         req->num_queued_sgs--;
3241 
3242         ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
3243                 trb, event, status, true);
3244         if (ret)
3245             break;
3246     }
3247 
3248     return ret;
3249 }
3250 
3251 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
3252         struct dwc3_request *req, const struct dwc3_event_depevt *event,
3253         int status)
3254 {
3255     struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
3256 
3257     return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
3258             event, status, false);
3259 }
3260 
3261 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
3262 {
3263     return req->num_pending_sgs == 0 && req->num_queued_sgs == 0;
3264 }
3265 
3266 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
3267         const struct dwc3_event_depevt *event,
3268         struct dwc3_request *req, int status)
3269 {
3270     int request_status;
3271     int ret;
3272 
3273     if (req->request.num_mapped_sgs)
3274         ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
3275                 status);
3276     else
3277         ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3278                 status);
3279 
3280     req->request.actual = req->request.length - req->remaining;
3281 
3282     if (!dwc3_gadget_ep_request_completed(req))
3283         goto out;
3284 
3285     if (req->needs_extra_trb) {
3286         ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
3287                 status);
3288         req->needs_extra_trb = false;
3289     }
3290 
3291     /*
3292      * The event status only reflects the status of the TRB with IOC set.
3293      * For the requests that don't set interrupt on completion, the driver
3294      * needs to check and return the status of the completed TRBs associated
3295      * with the request. Use the status of the last TRB of the request.
3296      */
3297     if (req->request.no_interrupt) {
3298         struct dwc3_trb *trb;
3299 
3300         trb = dwc3_ep_prev_trb(dep, dep->trb_dequeue);
3301         switch (DWC3_TRB_SIZE_TRBSTS(trb->size)) {
3302         case DWC3_TRBSTS_MISSED_ISOC:
3303             /* Isoc endpoint only */
3304             request_status = -EXDEV;
3305             break;
3306         case DWC3_TRB_STS_XFER_IN_PROG:
3307             /* Applicable when End Transfer with ForceRM=0 */
3308         case DWC3_TRBSTS_SETUP_PENDING:
3309             /* Control endpoint only */
3310         case DWC3_TRBSTS_OK:
3311         default:
3312             request_status = 0;
3313             break;
3314         }
3315     } else {
3316         request_status = status;
3317     }
3318 
3319     dwc3_gadget_giveback(dep, req, request_status);
3320 
3321 out:
3322     return ret;
3323 }
3324 
3325 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
3326         const struct dwc3_event_depevt *event, int status)
3327 {
3328     struct dwc3_request *req;
3329 
3330     while (!list_empty(&dep->started_list)) {
3331         int ret;
3332 
3333         req = next_request(&dep->started_list);
3334         ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
3335                 req, status);
3336         if (ret)
3337             break;
3338         /*
3339          * The endpoint is disabled, let the dwc3_remove_requests()
3340          * handle the cleanup.
3341          */
3342         if (!dep->endpoint.desc)
3343             break;
3344     }
3345 }
3346 
3347 static bool dwc3_gadget_ep_should_continue(struct dwc3_ep *dep)
3348 {
3349     struct dwc3_request *req;
3350     struct dwc3     *dwc = dep->dwc;
3351 
3352     if (!dep->endpoint.desc || !dwc->pullups_connected ||
3353         !dwc->connected)
3354         return false;
3355 
3356     if (!list_empty(&dep->pending_list))
3357         return true;
3358 
3359     /*
3360      * We only need to check the first entry of the started list. We can
3361      * assume the completed requests are removed from the started list.
3362      */
3363     req = next_request(&dep->started_list);
3364     if (!req)
3365         return false;
3366 
3367     return !dwc3_gadget_ep_request_completed(req);
3368 }
3369 
3370 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
3371         const struct dwc3_event_depevt *event)
3372 {
3373     dep->frame_number = event->parameters;
3374 }
3375 
3376 static bool dwc3_gadget_endpoint_trbs_complete(struct dwc3_ep *dep,
3377         const struct dwc3_event_depevt *event, int status)
3378 {
3379     struct dwc3     *dwc = dep->dwc;
3380     bool            no_started_trb = true;
3381 
3382     dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
3383 
3384     if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3385         goto out;
3386 
3387     if (!dep->endpoint.desc)
3388         return no_started_trb;
3389 
3390     if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
3391         list_empty(&dep->started_list) &&
3392         (list_empty(&dep->pending_list) || status == -EXDEV))
3393         dwc3_stop_active_transfer(dep, true, true);
3394     else if (dwc3_gadget_ep_should_continue(dep))
3395         if (__dwc3_gadget_kick_transfer(dep) == 0)
3396             no_started_trb = false;
3397 
3398 out:
3399     /*
3400      * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
3401      * See dwc3_gadget_linksts_change_interrupt() for 1st half.
3402      */
3403     if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
3404         u32     reg;
3405         int     i;
3406 
3407         for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
3408             dep = dwc->eps[i];
3409 
3410             if (!(dep->flags & DWC3_EP_ENABLED))
3411                 continue;
3412 
3413             if (!list_empty(&dep->started_list))
3414                 return no_started_trb;
3415         }
3416 
3417         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3418         reg |= dwc->u1u2;
3419         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
3420 
3421         dwc->u1u2 = 0;
3422     }
3423 
3424     return no_started_trb;
3425 }
3426 
3427 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
3428         const struct dwc3_event_depevt *event)
3429 {
3430     int status = 0;
3431 
3432     if (!dep->endpoint.desc)
3433         return;
3434 
3435     if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
3436         dwc3_gadget_endpoint_frame_from_event(dep, event);
3437 
3438     if (event->status & DEPEVT_STATUS_BUSERR)
3439         status = -ECONNRESET;
3440 
3441     if (event->status & DEPEVT_STATUS_MISSED_ISOC)
3442         status = -EXDEV;
3443 
3444     dwc3_gadget_endpoint_trbs_complete(dep, event, status);
3445 }
3446 
3447 static void dwc3_gadget_endpoint_transfer_complete(struct dwc3_ep *dep,
3448         const struct dwc3_event_depevt *event)
3449 {
3450     int status = 0;
3451 
3452     dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3453 
3454     if (event->status & DEPEVT_STATUS_BUSERR)
3455         status = -ECONNRESET;
3456 
3457     if (dwc3_gadget_endpoint_trbs_complete(dep, event, status))
3458         dep->flags &= ~DWC3_EP_WAIT_TRANSFER_COMPLETE;
3459 }
3460 
3461 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
3462         const struct dwc3_event_depevt *event)
3463 {
3464     dwc3_gadget_endpoint_frame_from_event(dep, event);
3465 
3466     /*
3467      * The XferNotReady event is generated only once before the endpoint
3468      * starts. It will be generated again when END_TRANSFER command is
3469      * issued. For some controller versions, the XferNotReady event may be
3470      * generated while the END_TRANSFER command is still in process. Ignore
3471      * it and wait for the next XferNotReady event after the command is
3472      * completed.
3473      */
3474     if (dep->flags & DWC3_EP_END_TRANSFER_PENDING)
3475         return;
3476 
3477     (void) __dwc3_gadget_start_isoc(dep);
3478 }
3479 
3480 static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep,
3481         const struct dwc3_event_depevt *event)
3482 {
3483     u8 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
3484 
3485     if (cmd != DWC3_DEPCMD_ENDTRANSFER)
3486         return;
3487 
3488     /*
3489      * The END_TRANSFER command will cause the controller to generate a
3490      * NoStream Event, and it's not due to the host DP NoStream rejection.
3491      * Ignore the next NoStream event.
3492      */
3493     if (dep->stream_capable)
3494         dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
3495 
3496     dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
3497     dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
3498     dwc3_gadget_ep_cleanup_cancelled_requests(dep);
3499 
3500     if (dep->flags & DWC3_EP_PENDING_CLEAR_STALL) {
3501         struct dwc3 *dwc = dep->dwc;
3502 
3503         dep->flags &= ~DWC3_EP_PENDING_CLEAR_STALL;
3504         if (dwc3_send_clear_stall_ep_cmd(dep)) {
3505             struct usb_ep *ep0 = &dwc->eps[0]->endpoint;
3506 
3507             dev_err(dwc->dev, "failed to clear STALL on %s\n", dep->name);
3508             if (dwc->delayed_status)
3509                 __dwc3_gadget_ep0_set_halt(ep0, 1);
3510             return;
3511         }
3512 
3513         dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
3514         if (dwc->clear_stall_protocol == dep->number)
3515             dwc3_ep0_send_delayed_status(dwc);
3516     }
3517 
3518     if ((dep->flags & DWC3_EP_DELAY_START) &&
3519         !usb_endpoint_xfer_isoc(dep->endpoint.desc))
3520         __dwc3_gadget_kick_transfer(dep);
3521 
3522     dep->flags &= ~DWC3_EP_DELAY_START;
3523 }
3524 
3525 static void dwc3_gadget_endpoint_stream_event(struct dwc3_ep *dep,
3526         const struct dwc3_event_depevt *event)
3527 {
3528     struct dwc3 *dwc = dep->dwc;
3529 
3530     if (event->status == DEPEVT_STREAMEVT_FOUND) {
3531         dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3532         goto out;
3533     }
3534 
3535     /* Note: NoStream rejection event param value is 0 and not 0xFFFF */
3536     switch (event->parameters) {
3537     case DEPEVT_STREAM_PRIME:
3538         /*
3539          * If the host can properly transition the endpoint state from
3540          * idle to prime after a NoStream rejection, there's no need to
3541          * force restarting the endpoint to reinitiate the stream. To
3542          * simplify the check, assume the host follows the USB spec if
3543          * it primed the endpoint more than once.
3544          */
3545         if (dep->flags & DWC3_EP_FORCE_RESTART_STREAM) {
3546             if (dep->flags & DWC3_EP_FIRST_STREAM_PRIMED)
3547                 dep->flags &= ~DWC3_EP_FORCE_RESTART_STREAM;
3548             else
3549                 dep->flags |= DWC3_EP_FIRST_STREAM_PRIMED;
3550         }
3551 
3552         break;
3553     case DEPEVT_STREAM_NOSTREAM:
3554         if ((dep->flags & DWC3_EP_IGNORE_NEXT_NOSTREAM) ||
3555             !(dep->flags & DWC3_EP_FORCE_RESTART_STREAM) ||
3556             (!DWC3_MST_CAPABLE(&dwc->hwparams) &&
3557              !(dep->flags & DWC3_EP_WAIT_TRANSFER_COMPLETE)))
3558             break;
3559 
3560         /*
3561          * If the host rejects a stream due to no active stream, by the
3562          * USB and xHCI spec, the endpoint will be put back to idle
3563          * state. When the host is ready (buffer added/updated), it will
3564          * prime the endpoint to inform the usb device controller. This
3565          * triggers the device controller to issue ERDY to restart the
3566          * stream. However, some hosts don't follow this and keep the
3567          * endpoint in the idle state. No prime will come despite host
3568          * streams are updated, and the device controller will not be
3569          * triggered to generate ERDY to move the next stream data. To
3570          * workaround this and maintain compatibility with various
3571          * hosts, force to reinitate the stream until the host is ready
3572          * instead of waiting for the host to prime the endpoint.
3573          */
3574         if (DWC3_VER_IS_WITHIN(DWC32, 100A, ANY)) {
3575             unsigned int cmd = DWC3_DGCMD_SET_ENDPOINT_PRIME;
3576 
3577             dwc3_send_gadget_generic_command(dwc, cmd, dep->number);
3578         } else {
3579             dep->flags |= DWC3_EP_DELAY_START;
3580             dwc3_stop_active_transfer(dep, true, true);
3581             return;
3582         }
3583         break;
3584     }
3585 
3586 out:
3587     dep->flags &= ~DWC3_EP_IGNORE_NEXT_NOSTREAM;
3588 }
3589 
3590 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
3591         const struct dwc3_event_depevt *event)
3592 {
3593     struct dwc3_ep      *dep;
3594     u8          epnum = event->endpoint_number;
3595 
3596     dep = dwc->eps[epnum];
3597 
3598     if (!(dep->flags & DWC3_EP_ENABLED)) {
3599         if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
3600             return;
3601 
3602         /* Handle only EPCMDCMPLT when EP disabled */
3603         if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
3604             return;
3605     }
3606 
3607     if (epnum == 0 || epnum == 1) {
3608         dwc3_ep0_interrupt(dwc, event);
3609         return;
3610     }
3611 
3612     switch (event->endpoint_event) {
3613     case DWC3_DEPEVT_XFERINPROGRESS:
3614         dwc3_gadget_endpoint_transfer_in_progress(dep, event);
3615         break;
3616     case DWC3_DEPEVT_XFERNOTREADY:
3617         dwc3_gadget_endpoint_transfer_not_ready(dep, event);
3618         break;
3619     case DWC3_DEPEVT_EPCMDCMPLT:
3620         dwc3_gadget_endpoint_command_complete(dep, event);
3621         break;
3622     case DWC3_DEPEVT_XFERCOMPLETE:
3623         dwc3_gadget_endpoint_transfer_complete(dep, event);
3624         break;
3625     case DWC3_DEPEVT_STREAMEVT:
3626         dwc3_gadget_endpoint_stream_event(dep, event);
3627         break;
3628     case DWC3_DEPEVT_RXTXFIFOEVT:
3629         break;
3630     }
3631 }
3632 
3633 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
3634 {
3635     if (dwc->async_callbacks && dwc->gadget_driver->disconnect) {
3636         spin_unlock(&dwc->lock);
3637         dwc->gadget_driver->disconnect(dwc->gadget);
3638         spin_lock(&dwc->lock);
3639     }
3640 }
3641 
3642 static void dwc3_suspend_gadget(struct dwc3 *dwc)
3643 {
3644     if (dwc->async_callbacks && dwc->gadget_driver->suspend) {
3645         spin_unlock(&dwc->lock);
3646         dwc->gadget_driver->suspend(dwc->gadget);
3647         spin_lock(&dwc->lock);
3648     }
3649 }
3650 
3651 static void dwc3_resume_gadget(struct dwc3 *dwc)
3652 {
3653     if (dwc->async_callbacks && dwc->gadget_driver->resume) {
3654         spin_unlock(&dwc->lock);
3655         dwc->gadget_driver->resume(dwc->gadget);
3656         spin_lock(&dwc->lock);
3657     }
3658 }
3659 
3660 static void dwc3_reset_gadget(struct dwc3 *dwc)
3661 {
3662     if (!dwc->gadget_driver)
3663         return;
3664 
3665     if (dwc->async_callbacks && dwc->gadget->speed != USB_SPEED_UNKNOWN) {
3666         spin_unlock(&dwc->lock);
3667         usb_gadget_udc_reset(dwc->gadget, dwc->gadget_driver);
3668         spin_lock(&dwc->lock);
3669     }
3670 }
3671 
3672 void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
3673     bool interrupt)
3674 {
3675     struct dwc3 *dwc = dep->dwc;
3676 
3677     /*
3678      * Only issue End Transfer command to the control endpoint of a started
3679      * Data Phase. Typically we should only do so in error cases such as
3680      * invalid/unexpected direction as described in the control transfer
3681      * flow of the programming guide.
3682      */
3683     if (dep->number <= 1 && dwc->ep0state != EP0_DATA_PHASE)
3684         return;
3685 
3686     if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
3687         (dep->flags & DWC3_EP_DELAY_STOP) ||
3688         (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
3689         return;
3690 
3691     /*
3692      * If a Setup packet is received but yet to DMA out, the controller will
3693      * not process the End Transfer command of any endpoint. Polling of its
3694      * DEPCMD.CmdAct may block setting up TRB for Setup packet, causing a
3695      * timeout. Delay issuing the End Transfer command until the Setup TRB is
3696      * prepared.
3697      */
3698     if (dwc->ep0state != EP0_SETUP_PHASE && !dwc->delayed_status) {
3699         dep->flags |= DWC3_EP_DELAY_STOP;
3700         return;
3701     }
3702 
3703     /*
3704      * NOTICE: We are violating what the Databook says about the
3705      * EndTransfer command. Ideally we would _always_ wait for the
3706      * EndTransfer Command Completion IRQ, but that's causing too
3707      * much trouble synchronizing between us and gadget driver.
3708      *
3709      * We have discussed this with the IP Provider and it was
3710      * suggested to giveback all requests here.
3711      *
3712      * Note also that a similar handling was tested by Synopsys
3713      * (thanks a lot Paul) and nothing bad has come out of it.
3714      * In short, what we're doing is issuing EndTransfer with
3715      * CMDIOC bit set and delay kicking transfer until the
3716      * EndTransfer command had completed.
3717      *
3718      * As of IP version 3.10a of the DWC_usb3 IP, the controller
3719      * supports a mode to work around the above limitation. The
3720      * software can poll the CMDACT bit in the DEPCMD register
3721      * after issuing a EndTransfer command. This mode is enabled
3722      * by writing GUCTL2[14]. This polling is already done in the
3723      * dwc3_send_gadget_ep_cmd() function so if the mode is
3724      * enabled, the EndTransfer command will have completed upon
3725      * returning from this function.
3726      *
3727      * This mode is NOT available on the DWC_usb31 IP.
3728      */
3729 
3730     __dwc3_stop_active_transfer(dep, force, interrupt);
3731 }
3732 
3733 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
3734 {
3735     u32 epnum;
3736 
3737     for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
3738         struct dwc3_ep *dep;
3739         int ret;
3740 
3741         dep = dwc->eps[epnum];
3742         if (!dep)
3743             continue;
3744 
3745         if (!(dep->flags & DWC3_EP_STALL))
3746             continue;
3747 
3748         dep->flags &= ~DWC3_EP_STALL;
3749 
3750         ret = dwc3_send_clear_stall_ep_cmd(dep);
3751         WARN_ON_ONCE(ret);
3752     }
3753 }
3754 
3755 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
3756 {
3757     int         reg;
3758 
3759     dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RX_DET);
3760 
3761     reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3762     reg &= ~DWC3_DCTL_INITU1ENA;
3763     reg &= ~DWC3_DCTL_INITU2ENA;
3764     dwc3_gadget_dctl_write_safe(dwc, reg);
3765 
3766     dwc3_disconnect_gadget(dwc);
3767 
3768     dwc->gadget->speed = USB_SPEED_UNKNOWN;
3769     dwc->setup_packet_pending = false;
3770     usb_gadget_set_state(dwc->gadget, USB_STATE_NOTATTACHED);
3771 
3772     dwc->connected = false;
3773 }
3774 
3775 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
3776 {
3777     u32         reg;
3778 
3779     /*
3780      * Ideally, dwc3_reset_gadget() would trigger the function
3781      * drivers to stop any active transfers through ep disable.
3782      * However, for functions which defer ep disable, such as mass
3783      * storage, we will need to rely on the call to stop active
3784      * transfers here, and avoid allowing of request queuing.
3785      */
3786     dwc->connected = false;
3787 
3788     /*
3789      * WORKAROUND: DWC3 revisions <1.88a have an issue which
3790      * would cause a missing Disconnect Event if there's a
3791      * pending Setup Packet in the FIFO.
3792      *
3793      * There's no suggested workaround on the official Bug
3794      * report, which states that "unless the driver/application
3795      * is doing any special handling of a disconnect event,
3796      * there is no functional issue".
3797      *
3798      * Unfortunately, it turns out that we _do_ some special
3799      * handling of a disconnect event, namely complete all
3800      * pending transfers, notify gadget driver of the
3801      * disconnection, and so on.
3802      *
3803      * Our suggested workaround is to follow the Disconnect
3804      * Event steps here, instead, based on a setup_packet_pending
3805      * flag. Such flag gets set whenever we have a SETUP_PENDING
3806      * status for EP0 TRBs and gets cleared on XferComplete for the
3807      * same endpoint.
3808      *
3809      * Refers to:
3810      *
3811      * STAR#9000466709: RTL: Device : Disconnect event not
3812      * generated if setup packet pending in FIFO
3813      */
3814     if (DWC3_VER_IS_PRIOR(DWC3, 188A)) {
3815         if (dwc->setup_packet_pending)
3816             dwc3_gadget_disconnect_interrupt(dwc);
3817     }
3818 
3819     dwc3_reset_gadget(dwc);
3820 
3821     /*
3822      * From SNPS databook section 8.1.2, the EP0 should be in setup
3823      * phase. So ensure that EP0 is in setup phase by issuing a stall
3824      * and restart if EP0 is not in setup phase.
3825      */
3826     if (dwc->ep0state != EP0_SETUP_PHASE) {
3827         unsigned int    dir;
3828 
3829         dir = !!dwc->ep0_expect_in;
3830         if (dwc->ep0state == EP0_DATA_PHASE)
3831             dwc3_ep0_end_control_data(dwc, dwc->eps[dir]);
3832         else
3833             dwc3_ep0_end_control_data(dwc, dwc->eps[!dir]);
3834 
3835         dwc->eps[0]->trb_enqueue = 0;
3836         dwc->eps[1]->trb_enqueue = 0;
3837 
3838         dwc3_ep0_stall_and_restart(dwc);
3839     }
3840 
3841     /*
3842      * In the Synopsis DesignWare Cores USB3 Databook Rev. 3.30a
3843      * Section 4.1.2 Table 4-2, it states that during a USB reset, the SW
3844      * needs to ensure that it sends "a DEPENDXFER command for any active
3845      * transfers."
3846      */
3847     dwc3_stop_active_transfers(dwc);
3848     dwc->connected = true;
3849 
3850     reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3851     reg &= ~DWC3_DCTL_TSTCTRL_MASK;
3852     dwc3_gadget_dctl_write_safe(dwc, reg);
3853     dwc->test_mode = false;
3854     dwc3_clear_stall_all_ep(dwc);
3855 
3856     /* Reset device address to zero */
3857     reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3858     reg &= ~(DWC3_DCFG_DEVADDR_MASK);
3859     dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3860 }
3861 
3862 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
3863 {
3864     struct dwc3_ep      *dep;
3865     int         ret;
3866     u32         reg;
3867     u8          lanes = 1;
3868     u8          speed;
3869 
3870     reg = dwc3_readl(dwc->regs, DWC3_DSTS);
3871     speed = reg & DWC3_DSTS_CONNECTSPD;
3872     dwc->speed = speed;
3873 
3874     if (DWC3_IP_IS(DWC32))
3875         lanes = DWC3_DSTS_CONNLANES(reg) + 1;
3876 
3877     dwc->gadget->ssp_rate = USB_SSP_GEN_UNKNOWN;
3878 
3879     /*
3880      * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
3881      * each time on Connect Done.
3882      *
3883      * Currently we always use the reset value. If any platform
3884      * wants to set this to a different value, we need to add a
3885      * setting and update GCTL.RAMCLKSEL here.
3886      */
3887 
3888     switch (speed) {
3889     case DWC3_DSTS_SUPERSPEED_PLUS:
3890         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3891         dwc->gadget->ep0->maxpacket = 512;
3892         dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3893 
3894         if (lanes > 1)
3895             dwc->gadget->ssp_rate = USB_SSP_GEN_2x2;
3896         else
3897             dwc->gadget->ssp_rate = USB_SSP_GEN_2x1;
3898         break;
3899     case DWC3_DSTS_SUPERSPEED:
3900         /*
3901          * WORKAROUND: DWC3 revisions <1.90a have an issue which
3902          * would cause a missing USB3 Reset event.
3903          *
3904          * In such situations, we should force a USB3 Reset
3905          * event by calling our dwc3_gadget_reset_interrupt()
3906          * routine.
3907          *
3908          * Refers to:
3909          *
3910          * STAR#9000483510: RTL: SS : USB3 reset event may
3911          * not be generated always when the link enters poll
3912          */
3913         if (DWC3_VER_IS_PRIOR(DWC3, 190A))
3914             dwc3_gadget_reset_interrupt(dwc);
3915 
3916         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
3917         dwc->gadget->ep0->maxpacket = 512;
3918         dwc->gadget->speed = USB_SPEED_SUPER;
3919 
3920         if (lanes > 1) {
3921             dwc->gadget->speed = USB_SPEED_SUPER_PLUS;
3922             dwc->gadget->ssp_rate = USB_SSP_GEN_1x2;
3923         }
3924         break;
3925     case DWC3_DSTS_HIGHSPEED:
3926         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3927         dwc->gadget->ep0->maxpacket = 64;
3928         dwc->gadget->speed = USB_SPEED_HIGH;
3929         break;
3930     case DWC3_DSTS_FULLSPEED:
3931         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
3932         dwc->gadget->ep0->maxpacket = 64;
3933         dwc->gadget->speed = USB_SPEED_FULL;
3934         break;
3935     }
3936 
3937     dwc->eps[1]->endpoint.maxpacket = dwc->gadget->ep0->maxpacket;
3938 
3939     /* Enable USB2 LPM Capability */
3940 
3941     if (!DWC3_VER_IS_WITHIN(DWC3, ANY, 194A) &&
3942         !dwc->usb2_gadget_lpm_disable &&
3943         (speed != DWC3_DSTS_SUPERSPEED) &&
3944         (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
3945         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3946         reg |= DWC3_DCFG_LPM_CAP;
3947         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3948 
3949         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3950         reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
3951 
3952         reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
3953                         (dwc->is_utmi_l1_suspend << 4));
3954 
3955         /*
3956          * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
3957          * DCFG.LPMCap is set, core responses with an ACK and the
3958          * BESL value in the LPM token is less than or equal to LPM
3959          * NYET threshold.
3960          */
3961         WARN_ONCE(DWC3_VER_IS_PRIOR(DWC3, 240A) && dwc->has_lpm_erratum,
3962                 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
3963 
3964         if (dwc->has_lpm_erratum && !DWC3_VER_IS_PRIOR(DWC3, 240A))
3965             reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
3966 
3967         dwc3_gadget_dctl_write_safe(dwc, reg);
3968     } else {
3969         if (dwc->usb2_gadget_lpm_disable) {
3970             reg = dwc3_readl(dwc->regs, DWC3_DCFG);
3971             reg &= ~DWC3_DCFG_LPM_CAP;
3972             dwc3_writel(dwc->regs, DWC3_DCFG, reg);
3973         }
3974 
3975         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3976         reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
3977         dwc3_gadget_dctl_write_safe(dwc, reg);
3978     }
3979 
3980     dep = dwc->eps[0];
3981     ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3982     if (ret) {
3983         dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3984         return;
3985     }
3986 
3987     dep = dwc->eps[1];
3988     ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
3989     if (ret) {
3990         dev_err(dwc->dev, "failed to enable %s\n", dep->name);
3991         return;
3992     }
3993 
3994     /*
3995      * Configure PHY via GUSB3PIPECTLn if required.
3996      *
3997      * Update GTXFIFOSIZn
3998      *
3999      * In both cases reset values should be sufficient.
4000      */
4001 }
4002 
4003 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
4004 {
4005     /*
4006      * TODO take core out of low power mode when that's
4007      * implemented.
4008      */
4009 
4010     if (dwc->async_callbacks && dwc->gadget_driver->resume) {
4011         spin_unlock(&dwc->lock);
4012         dwc->gadget_driver->resume(dwc->gadget);
4013         spin_lock(&dwc->lock);
4014     }
4015 }
4016 
4017 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
4018         unsigned int evtinfo)
4019 {
4020     enum dwc3_link_state    next = evtinfo & DWC3_LINK_STATE_MASK;
4021     unsigned int        pwropt;
4022 
4023     /*
4024      * WORKAROUND: DWC3 < 2.50a have an issue when configured without
4025      * Hibernation mode enabled which would show up when device detects
4026      * host-initiated U3 exit.
4027      *
4028      * In that case, device will generate a Link State Change Interrupt
4029      * from U3 to RESUME which is only necessary if Hibernation is
4030      * configured in.
4031      *
4032      * There are no functional changes due to such spurious event and we
4033      * just need to ignore it.
4034      *
4035      * Refers to:
4036      *
4037      * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
4038      * operational mode
4039      */
4040     pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
4041     if (DWC3_VER_IS_PRIOR(DWC3, 250A) &&
4042             (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
4043         if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
4044                 (next == DWC3_LINK_STATE_RESUME)) {
4045             return;
4046         }
4047     }
4048 
4049     /*
4050      * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
4051      * on the link partner, the USB session might do multiple entry/exit
4052      * of low power states before a transfer takes place.
4053      *
4054      * Due to this problem, we might experience lower throughput. The
4055      * suggested workaround is to disable DCTL[12:9] bits if we're
4056      * transitioning from U1/U2 to U0 and enable those bits again
4057      * after a transfer completes and there are no pending transfers
4058      * on any of the enabled endpoints.
4059      *
4060      * This is the first half of that workaround.
4061      *
4062      * Refers to:
4063      *
4064      * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
4065      * core send LGO_Ux entering U0
4066      */
4067     if (DWC3_VER_IS_PRIOR(DWC3, 183A)) {
4068         if (next == DWC3_LINK_STATE_U0) {
4069             u32 u1u2;
4070             u32 reg;
4071 
4072             switch (dwc->link_state) {
4073             case DWC3_LINK_STATE_U1:
4074             case DWC3_LINK_STATE_U2:
4075                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
4076                 u1u2 = reg & (DWC3_DCTL_INITU2ENA
4077                         | DWC3_DCTL_ACCEPTU2ENA
4078                         | DWC3_DCTL_INITU1ENA
4079                         | DWC3_DCTL_ACCEPTU1ENA);
4080 
4081                 if (!dwc->u1u2)
4082                     dwc->u1u2 = reg & u1u2;
4083 
4084                 reg &= ~u1u2;
4085 
4086                 dwc3_gadget_dctl_write_safe(dwc, reg);
4087                 break;
4088             default:
4089                 /* do nothing */
4090                 break;
4091             }
4092         }
4093     }
4094 
4095     switch (next) {
4096     case DWC3_LINK_STATE_U1:
4097         if (dwc->speed == USB_SPEED_SUPER)
4098             dwc3_suspend_gadget(dwc);
4099         break;
4100     case DWC3_LINK_STATE_U2:
4101     case DWC3_LINK_STATE_U3:
4102         dwc3_suspend_gadget(dwc);
4103         break;
4104     case DWC3_LINK_STATE_RESUME:
4105         dwc3_resume_gadget(dwc);
4106         break;
4107     default:
4108         /* do nothing */
4109         break;
4110     }
4111 
4112     dwc->link_state = next;
4113 }
4114 
4115 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
4116                       unsigned int evtinfo)
4117 {
4118     enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
4119 
4120     if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
4121         dwc3_suspend_gadget(dwc);
4122 
4123     dwc->link_state = next;
4124 }
4125 
4126 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
4127         unsigned int evtinfo)
4128 {
4129     unsigned int is_ss = evtinfo & BIT(4);
4130 
4131     /*
4132      * WORKAROUND: DWC3 revison 2.20a with hibernation support
4133      * have a known issue which can cause USB CV TD.9.23 to fail
4134      * randomly.
4135      *
4136      * Because of this issue, core could generate bogus hibernation
4137      * events which SW needs to ignore.
4138      *
4139      * Refers to:
4140      *
4141      * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
4142      * Device Fallback from SuperSpeed
4143      */
4144     if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
4145         return;
4146 
4147     /* enter hibernation here */
4148 }
4149 
4150 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
4151         const struct dwc3_event_devt *event)
4152 {
4153     switch (event->type) {
4154     case DWC3_DEVICE_EVENT_DISCONNECT:
4155         dwc3_gadget_disconnect_interrupt(dwc);
4156         break;
4157     case DWC3_DEVICE_EVENT_RESET:
4158         dwc3_gadget_reset_interrupt(dwc);
4159         break;
4160     case DWC3_DEVICE_EVENT_CONNECT_DONE:
4161         dwc3_gadget_conndone_interrupt(dwc);
4162         break;
4163     case DWC3_DEVICE_EVENT_WAKEUP:
4164         dwc3_gadget_wakeup_interrupt(dwc);
4165         break;
4166     case DWC3_DEVICE_EVENT_HIBER_REQ:
4167         if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
4168                     "unexpected hibernation event\n"))
4169             break;
4170 
4171         dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
4172         break;
4173     case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
4174         dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
4175         break;
4176     case DWC3_DEVICE_EVENT_SUSPEND:
4177         /* It changed to be suspend event for version 2.30a and above */
4178         if (!DWC3_VER_IS_PRIOR(DWC3, 230A)) {
4179             /*
4180              * Ignore suspend event until the gadget enters into
4181              * USB_STATE_CONFIGURED state.
4182              */
4183             if (dwc->gadget->state >= USB_STATE_CONFIGURED)
4184                 dwc3_gadget_suspend_interrupt(dwc,
4185                         event->event_info);
4186         }
4187         break;
4188     case DWC3_DEVICE_EVENT_SOF:
4189     case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
4190     case DWC3_DEVICE_EVENT_CMD_CMPL:
4191     case DWC3_DEVICE_EVENT_OVERFLOW:
4192         break;
4193     default:
4194         dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
4195     }
4196 }
4197 
4198 static void dwc3_process_event_entry(struct dwc3 *dwc,
4199         const union dwc3_event *event)
4200 {
4201     trace_dwc3_event(event->raw, dwc);
4202 
4203     if (!event->type.is_devspec)
4204         dwc3_endpoint_interrupt(dwc, &event->depevt);
4205     else if (event->type.type == DWC3_EVENT_TYPE_DEV)
4206         dwc3_gadget_interrupt(dwc, &event->devt);
4207     else
4208         dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
4209 }
4210 
4211 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
4212 {
4213     struct dwc3 *dwc = evt->dwc;
4214     irqreturn_t ret = IRQ_NONE;
4215     int left;
4216 
4217     left = evt->count;
4218 
4219     if (!(evt->flags & DWC3_EVENT_PENDING))
4220         return IRQ_NONE;
4221 
4222     while (left > 0) {
4223         union dwc3_event event;
4224 
4225         event.raw = *(u32 *) (evt->cache + evt->lpos);
4226 
4227         dwc3_process_event_entry(dwc, &event);
4228 
4229         /*
4230          * FIXME we wrap around correctly to the next entry as
4231          * almost all entries are 4 bytes in size. There is one
4232          * entry which has 12 bytes which is a regular entry
4233          * followed by 8 bytes data. ATM I don't know how
4234          * things are organized if we get next to the a
4235          * boundary so I worry about that once we try to handle
4236          * that.
4237          */
4238         evt->lpos = (evt->lpos + 4) % evt->length;
4239         left -= 4;
4240     }
4241 
4242     evt->count = 0;
4243     ret = IRQ_HANDLED;
4244 
4245     /* Unmask interrupt */
4246     dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4247             DWC3_GEVNTSIZ_SIZE(evt->length));
4248 
4249     if (dwc->imod_interval) {
4250         dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
4251         dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
4252     }
4253 
4254     /* Keep the clearing of DWC3_EVENT_PENDING at the end */
4255     evt->flags &= ~DWC3_EVENT_PENDING;
4256 
4257     return ret;
4258 }
4259 
4260 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
4261 {
4262     struct dwc3_event_buffer *evt = _evt;
4263     struct dwc3 *dwc = evt->dwc;
4264     unsigned long flags;
4265     irqreturn_t ret = IRQ_NONE;
4266 
4267     local_bh_disable();
4268     spin_lock_irqsave(&dwc->lock, flags);
4269     ret = dwc3_process_event_buf(evt);
4270     spin_unlock_irqrestore(&dwc->lock, flags);
4271     local_bh_enable();
4272 
4273     return ret;
4274 }
4275 
4276 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
4277 {
4278     struct dwc3 *dwc = evt->dwc;
4279     u32 amount;
4280     u32 count;
4281 
4282     if (pm_runtime_suspended(dwc->dev)) {
4283         pm_runtime_get(dwc->dev);
4284         disable_irq_nosync(dwc->irq_gadget);
4285         dwc->pending_events = true;
4286         return IRQ_HANDLED;
4287     }
4288 
4289     /*
4290      * With PCIe legacy interrupt, test shows that top-half irq handler can
4291      * be called again after HW interrupt deassertion. Check if bottom-half
4292      * irq event handler completes before caching new event to prevent
4293      * losing events.
4294      */
4295     if (evt->flags & DWC3_EVENT_PENDING)
4296         return IRQ_HANDLED;
4297 
4298     count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
4299     count &= DWC3_GEVNTCOUNT_MASK;
4300     if (!count)
4301         return IRQ_NONE;
4302 
4303     evt->count = count;
4304     evt->flags |= DWC3_EVENT_PENDING;
4305 
4306     /* Mask interrupt */
4307     dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0),
4308             DWC3_GEVNTSIZ_INTMASK | DWC3_GEVNTSIZ_SIZE(evt->length));
4309 
4310     amount = min(count, evt->length - evt->lpos);
4311     memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
4312 
4313     if (amount < count)
4314         memcpy(evt->cache, evt->buf, count - amount);
4315 
4316     dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
4317 
4318     return IRQ_WAKE_THREAD;
4319 }
4320 
4321 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
4322 {
4323     struct dwc3_event_buffer    *evt = _evt;
4324 
4325     return dwc3_check_event_buf(evt);
4326 }
4327 
4328 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
4329 {
4330     struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
4331     int irq;
4332 
4333     irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
4334     if (irq > 0)
4335         goto out;
4336 
4337     if (irq == -EPROBE_DEFER)
4338         goto out;
4339 
4340     irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
4341     if (irq > 0)
4342         goto out;
4343 
4344     if (irq == -EPROBE_DEFER)
4345         goto out;
4346 
4347     irq = platform_get_irq(dwc3_pdev, 0);
4348     if (irq > 0)
4349         goto out;
4350 
4351     if (!irq)
4352         irq = -EINVAL;
4353 
4354 out:
4355     return irq;
4356 }
4357 
4358 static void dwc_gadget_release(struct device *dev)
4359 {
4360     struct usb_gadget *gadget = container_of(dev, struct usb_gadget, dev);
4361 
4362     kfree(gadget);
4363 }
4364 
4365 /**
4366  * dwc3_gadget_init - initializes gadget related registers
4367  * @dwc: pointer to our controller context structure
4368  *
4369  * Returns 0 on success otherwise negative errno.
4370  */
4371 int dwc3_gadget_init(struct dwc3 *dwc)
4372 {
4373     int ret;
4374     int irq;
4375     struct device *dev;
4376 
4377     irq = dwc3_gadget_get_irq(dwc);
4378     if (irq < 0) {
4379         ret = irq;
4380         goto err0;
4381     }
4382 
4383     dwc->irq_gadget = irq;
4384 
4385     dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
4386                       sizeof(*dwc->ep0_trb) * 2,
4387                       &dwc->ep0_trb_addr, GFP_KERNEL);
4388     if (!dwc->ep0_trb) {
4389         dev_err(dwc->dev, "failed to allocate ep0 trb\n");
4390         ret = -ENOMEM;
4391         goto err0;
4392     }
4393 
4394     dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
4395     if (!dwc->setup_buf) {
4396         ret = -ENOMEM;
4397         goto err1;
4398     }
4399 
4400     dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
4401             &dwc->bounce_addr, GFP_KERNEL);
4402     if (!dwc->bounce) {
4403         ret = -ENOMEM;
4404         goto err2;
4405     }
4406 
4407     init_completion(&dwc->ep0_in_setup);
4408     dwc->gadget = kzalloc(sizeof(struct usb_gadget), GFP_KERNEL);
4409     if (!dwc->gadget) {
4410         ret = -ENOMEM;
4411         goto err3;
4412     }
4413 
4414 
4415     usb_initialize_gadget(dwc->dev, dwc->gadget, dwc_gadget_release);
4416     dev             = &dwc->gadget->dev;
4417     dev->platform_data      = dwc;
4418     dwc->gadget->ops        = &dwc3_gadget_ops;
4419     dwc->gadget->speed      = USB_SPEED_UNKNOWN;
4420     dwc->gadget->ssp_rate       = USB_SSP_GEN_UNKNOWN;
4421     dwc->gadget->sg_supported   = true;
4422     dwc->gadget->name       = "dwc3-gadget";
4423     dwc->gadget->lpm_capable    = !dwc->usb2_gadget_lpm_disable;
4424 
4425     /*
4426      * FIXME We might be setting max_speed to <SUPER, however versions
4427      * <2.20a of dwc3 have an issue with metastability (documented
4428      * elsewhere in this driver) which tells us we can't set max speed to
4429      * anything lower than SUPER.
4430      *
4431      * Because gadget.max_speed is only used by composite.c and function
4432      * drivers (i.e. it won't go into dwc3's registers) we are allowing this
4433      * to happen so we avoid sending SuperSpeed Capability descriptor
4434      * together with our BOS descriptor as that could confuse host into
4435      * thinking we can handle super speed.
4436      *
4437      * Note that, in fact, we won't even support GetBOS requests when speed
4438      * is less than super speed because we don't have means, yet, to tell
4439      * composite.c that we are USB 2.0 + LPM ECN.
4440      */
4441     if (DWC3_VER_IS_PRIOR(DWC3, 220A) &&
4442         !dwc->dis_metastability_quirk)
4443         dev_info(dwc->dev, "changing max_speed on rev %08x\n",
4444                 dwc->revision);
4445 
4446     dwc->gadget->max_speed      = dwc->maximum_speed;
4447     dwc->gadget->max_ssp_rate   = dwc->max_ssp_rate;
4448 
4449     /*
4450      * REVISIT: Here we should clear all pending IRQs to be
4451      * sure we're starting from a well known location.
4452      */
4453 
4454     ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
4455     if (ret)
4456         goto err4;
4457 
4458     ret = usb_add_gadget(dwc->gadget);
4459     if (ret) {
4460         dev_err(dwc->dev, "failed to add gadget\n");
4461         goto err5;
4462     }
4463 
4464     if (DWC3_IP_IS(DWC32) && dwc->maximum_speed == USB_SPEED_SUPER_PLUS)
4465         dwc3_gadget_set_ssp_rate(dwc->gadget, dwc->max_ssp_rate);
4466     else
4467         dwc3_gadget_set_speed(dwc->gadget, dwc->maximum_speed);
4468 
4469     return 0;
4470 
4471 err5:
4472     dwc3_gadget_free_endpoints(dwc);
4473 err4:
4474     usb_put_gadget(dwc->gadget);
4475     dwc->gadget = NULL;
4476 err3:
4477     dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4478             dwc->bounce_addr);
4479 
4480 err2:
4481     kfree(dwc->setup_buf);
4482 
4483 err1:
4484     dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4485             dwc->ep0_trb, dwc->ep0_trb_addr);
4486 
4487 err0:
4488     return ret;
4489 }
4490 
4491 /* -------------------------------------------------------------------------- */
4492 
4493 void dwc3_gadget_exit(struct dwc3 *dwc)
4494 {
4495     if (!dwc->gadget)
4496         return;
4497 
4498     usb_del_gadget(dwc->gadget);
4499     dwc3_gadget_free_endpoints(dwc);
4500     usb_put_gadget(dwc->gadget);
4501     dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
4502               dwc->bounce_addr);
4503     kfree(dwc->setup_buf);
4504     dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
4505               dwc->ep0_trb, dwc->ep0_trb_addr);
4506 }
4507 
4508 int dwc3_gadget_suspend(struct dwc3 *dwc)
4509 {
4510     if (!dwc->gadget_driver)
4511         return 0;
4512 
4513     dwc3_gadget_run_stop(dwc, false, false);
4514     dwc3_disconnect_gadget(dwc);
4515     __dwc3_gadget_stop(dwc);
4516 
4517     return 0;
4518 }
4519 
4520 int dwc3_gadget_resume(struct dwc3 *dwc)
4521 {
4522     int         ret;
4523 
4524     if (!dwc->gadget_driver || !dwc->softconnect)
4525         return 0;
4526 
4527     ret = __dwc3_gadget_start(dwc);
4528     if (ret < 0)
4529         goto err0;
4530 
4531     ret = dwc3_gadget_run_stop(dwc, true, false);
4532     if (ret < 0)
4533         goto err1;
4534 
4535     return 0;
4536 
4537 err1:
4538     __dwc3_gadget_stop(dwc);
4539 
4540 err0:
4541     return ret;
4542 }
4543 
4544 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
4545 {
4546     if (dwc->pending_events) {
4547         dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
4548         dwc->pending_events = false;
4549         enable_irq(dwc->irq_gadget);
4550     }
4551 }