root/drivers/usb/dwc3/gadget.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. dwc3_gadget_set_test_mode
  2. dwc3_gadget_get_link_state
  3. dwc3_gadget_set_link_state
  4. dwc3_ep_inc_trb
  5. dwc3_ep_inc_enq
  6. dwc3_ep_inc_deq
  7. dwc3_gadget_del_and_unmap_request
  8. dwc3_gadget_giveback
  9. dwc3_send_gadget_generic_command
  10. dwc3_send_gadget_ep_cmd
  11. dwc3_send_clear_stall_ep_cmd
  12. dwc3_trb_dma_offset
  13. dwc3_alloc_trb_pool
  14. dwc3_free_trb_pool
  15. dwc3_gadget_set_xfer_resource
  16. dwc3_gadget_start_config
  17. dwc3_gadget_set_ep_config
  18. __dwc3_gadget_ep_enable
  19. dwc3_remove_requests
  20. __dwc3_gadget_ep_disable
  21. dwc3_gadget_ep0_enable
  22. dwc3_gadget_ep0_disable
  23. dwc3_gadget_ep_enable
  24. dwc3_gadget_ep_disable
  25. dwc3_gadget_ep_alloc_request
  26. dwc3_gadget_ep_free_request
  27. dwc3_ep_prev_trb
  28. dwc3_calc_trbs_left
  29. __dwc3_prepare_one_trb
  30. dwc3_prepare_one_trb
  31. dwc3_prepare_one_trb_sg
  32. dwc3_prepare_one_trb_linear
  33. dwc3_prepare_trbs
  34. __dwc3_gadget_kick_transfer
  35. __dwc3_gadget_get_frame
  36. dwc3_gadget_start_isoc_quirk
  37. __dwc3_gadget_start_isoc
  38. __dwc3_gadget_ep_queue
  39. dwc3_gadget_ep_queue
  40. dwc3_gadget_ep_skip_trbs
  41. dwc3_gadget_ep_cleanup_cancelled_requests
  42. dwc3_gadget_ep_dequeue
  43. __dwc3_gadget_ep_set_halt
  44. dwc3_gadget_ep_set_halt
  45. dwc3_gadget_ep_set_wedge
  46. dwc3_gadget_get_frame
  47. __dwc3_gadget_wakeup
  48. dwc3_gadget_wakeup
  49. dwc3_gadget_set_selfpowered
  50. dwc3_gadget_run_stop
  51. dwc3_gadget_pullup
  52. dwc3_gadget_enable_irq
  53. dwc3_gadget_disable_irq
  54. dwc3_gadget_setup_nump
  55. __dwc3_gadget_start
  56. dwc3_gadget_start
  57. __dwc3_gadget_stop
  58. dwc3_gadget_stop
  59. dwc3_gadget_config_params
  60. dwc3_gadget_set_speed
  61. dwc3_gadget_init_control_endpoint
  62. dwc3_gadget_init_in_endpoint
  63. dwc3_gadget_init_out_endpoint
  64. dwc3_gadget_init_endpoint
  65. dwc3_gadget_init_endpoints
  66. dwc3_gadget_free_endpoints
  67. dwc3_gadget_ep_reclaim_completed_trb
  68. dwc3_gadget_ep_reclaim_trb_sg
  69. dwc3_gadget_ep_reclaim_trb_linear
  70. dwc3_gadget_ep_request_completed
  71. dwc3_gadget_ep_cleanup_completed_request
  72. dwc3_gadget_ep_cleanup_completed_requests
  73. dwc3_gadget_endpoint_frame_from_event
  74. dwc3_gadget_endpoint_transfer_in_progress
  75. dwc3_gadget_endpoint_transfer_not_ready
  76. dwc3_endpoint_interrupt
  77. dwc3_disconnect_gadget
  78. dwc3_suspend_gadget
  79. dwc3_resume_gadget
  80. dwc3_reset_gadget
  81. dwc3_stop_active_transfer
  82. dwc3_clear_stall_all_ep
  83. dwc3_gadget_disconnect_interrupt
  84. dwc3_gadget_reset_interrupt
  85. dwc3_gadget_conndone_interrupt
  86. dwc3_gadget_wakeup_interrupt
  87. dwc3_gadget_linksts_change_interrupt
  88. dwc3_gadget_suspend_interrupt
  89. dwc3_gadget_hibernation_interrupt
  90. dwc3_gadget_interrupt
  91. dwc3_process_event_entry
  92. dwc3_process_event_buf
  93. dwc3_thread_interrupt
  94. dwc3_check_event_buf
  95. dwc3_interrupt
  96. dwc3_gadget_get_irq
  97. dwc3_gadget_init
  98. dwc3_gadget_exit
  99. dwc3_gadget_suspend
  100. dwc3_gadget_resume
  101. dwc3_gadget_process_pending_events

   1 // SPDX-License-Identifier: GPL-2.0
   2 /*
   3  * gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
   4  *
   5  * Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
   6  *
   7  * Authors: Felipe Balbi <balbi@ti.com>,
   8  *          Sebastian Andrzej Siewior <bigeasy@linutronix.de>
   9  */
  10 
  11 #include <linux/kernel.h>
  12 #include <linux/delay.h>
  13 #include <linux/slab.h>
  14 #include <linux/spinlock.h>
  15 #include <linux/platform_device.h>
  16 #include <linux/pm_runtime.h>
  17 #include <linux/interrupt.h>
  18 #include <linux/io.h>
  19 #include <linux/list.h>
  20 #include <linux/dma-mapping.h>
  21 
  22 #include <linux/usb/ch9.h>
  23 #include <linux/usb/gadget.h>
  24 
  25 #include "debug.h"
  26 #include "core.h"
  27 #include "gadget.h"
  28 #include "io.h"
  29 
  30 #define DWC3_ALIGN_FRAME(d, n)  (((d)->frame_number + ((d)->interval * (n))) \
  31                                         & ~((d)->interval - 1))
  32 
  33 /**
  34  * dwc3_gadget_set_test_mode - enables usb2 test modes
  35  * @dwc: pointer to our context structure
  36  * @mode: the mode to set (J, K SE0 NAK, Force Enable)
  37  *
  38  * Caller should take care of locking. This function will return 0 on
  39  * success or -EINVAL if wrong Test Selector is passed.
  40  */
  41 int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
  42 {
  43         u32             reg;
  44 
  45         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
  46         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
  47 
  48         switch (mode) {
  49         case TEST_J:
  50         case TEST_K:
  51         case TEST_SE0_NAK:
  52         case TEST_PACKET:
  53         case TEST_FORCE_EN:
  54                 reg |= mode << 1;
  55                 break;
  56         default:
  57                 return -EINVAL;
  58         }
  59 
  60         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
  61 
  62         return 0;
  63 }
  64 
  65 /**
  66  * dwc3_gadget_get_link_state - gets current state of usb link
  67  * @dwc: pointer to our context structure
  68  *
  69  * Caller should take care of locking. This function will
  70  * return the link state on success (>= 0) or -ETIMEDOUT.
  71  */
  72 int dwc3_gadget_get_link_state(struct dwc3 *dwc)
  73 {
  74         u32             reg;
  75 
  76         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
  77 
  78         return DWC3_DSTS_USBLNKST(reg);
  79 }
  80 
  81 /**
  82  * dwc3_gadget_set_link_state - sets usb link to a particular state
  83  * @dwc: pointer to our context structure
  84  * @state: the state to put link into
  85  *
  86  * Caller should take care of locking. This function will
  87  * return 0 on success or -ETIMEDOUT.
  88  */
  89 int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
  90 {
  91         int             retries = 10000;
  92         u32             reg;
  93 
  94         /*
  95          * Wait until device controller is ready. Only applies to 1.94a and
  96          * later RTL.
  97          */
  98         if (dwc->revision >= DWC3_REVISION_194A) {
  99                 while (--retries) {
 100                         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
 101                         if (reg & DWC3_DSTS_DCNRD)
 102                                 udelay(5);
 103                         else
 104                                 break;
 105                 }
 106 
 107                 if (retries <= 0)
 108                         return -ETIMEDOUT;
 109         }
 110 
 111         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
 112         reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
 113 
 114         /* set requested state */
 115         reg |= DWC3_DCTL_ULSTCHNGREQ(state);
 116         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
 117 
 118         /*
 119          * The following code is racy when called from dwc3_gadget_wakeup,
 120          * and is not needed, at least on newer versions
 121          */
 122         if (dwc->revision >= DWC3_REVISION_194A)
 123                 return 0;
 124 
 125         /* wait for a change in DSTS */
 126         retries = 10000;
 127         while (--retries) {
 128                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
 129 
 130                 if (DWC3_DSTS_USBLNKST(reg) == state)
 131                         return 0;
 132 
 133                 udelay(5);
 134         }
 135 
 136         return -ETIMEDOUT;
 137 }
 138 
 139 /**
 140  * dwc3_ep_inc_trb - increment a trb index.
 141  * @index: Pointer to the TRB index to increment.
 142  *
 143  * The index should never point to the link TRB. After incrementing,
 144  * if it is point to the link TRB, wrap around to the beginning. The
 145  * link TRB is always at the last TRB entry.
 146  */
 147 static void dwc3_ep_inc_trb(u8 *index)
 148 {
 149         (*index)++;
 150         if (*index == (DWC3_TRB_NUM - 1))
 151                 *index = 0;
 152 }
 153 
 154 /**
 155  * dwc3_ep_inc_enq - increment endpoint's enqueue pointer
 156  * @dep: The endpoint whose enqueue pointer we're incrementing
 157  */
 158 static void dwc3_ep_inc_enq(struct dwc3_ep *dep)
 159 {
 160         dwc3_ep_inc_trb(&dep->trb_enqueue);
 161 }
 162 
 163 /**
 164  * dwc3_ep_inc_deq - increment endpoint's dequeue pointer
 165  * @dep: The endpoint whose enqueue pointer we're incrementing
 166  */
 167 static void dwc3_ep_inc_deq(struct dwc3_ep *dep)
 168 {
 169         dwc3_ep_inc_trb(&dep->trb_dequeue);
 170 }
 171 
 172 static void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
 173                 struct dwc3_request *req, int status)
 174 {
 175         struct dwc3                     *dwc = dep->dwc;
 176 
 177         list_del(&req->list);
 178         req->remaining = 0;
 179         req->needs_extra_trb = false;
 180 
 181         if (req->request.status == -EINPROGRESS)
 182                 req->request.status = status;
 183 
 184         if (req->trb)
 185                 usb_gadget_unmap_request_by_dev(dwc->sysdev,
 186                                 &req->request, req->direction);
 187 
 188         req->trb = NULL;
 189         trace_dwc3_gadget_giveback(req);
 190 
 191         if (dep->number > 1)
 192                 pm_runtime_put(dwc->dev);
 193 }
 194 
 195 /**
 196  * dwc3_gadget_giveback - call struct usb_request's ->complete callback
 197  * @dep: The endpoint to whom the request belongs to
 198  * @req: The request we're giving back
 199  * @status: completion code for the request
 200  *
 201  * Must be called with controller's lock held and interrupts disabled. This
 202  * function will unmap @req and call its ->complete() callback to notify upper
 203  * layers that it has completed.
 204  */
 205 void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
 206                 int status)
 207 {
 208         struct dwc3                     *dwc = dep->dwc;
 209 
 210         dwc3_gadget_del_and_unmap_request(dep, req, status);
 211         req->status = DWC3_REQUEST_STATUS_COMPLETED;
 212 
 213         spin_unlock(&dwc->lock);
 214         usb_gadget_giveback_request(&dep->endpoint, &req->request);
 215         spin_lock(&dwc->lock);
 216 }
 217 
 218 /**
 219  * dwc3_send_gadget_generic_command - issue a generic command for the controller
 220  * @dwc: pointer to the controller context
 221  * @cmd: the command to be issued
 222  * @param: command parameter
 223  *
 224  * Caller should take care of locking. Issue @cmd with a given @param to @dwc
 225  * and wait for its completion.
 226  */
 227 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned cmd, u32 param)
 228 {
 229         u32             timeout = 500;
 230         int             status = 0;
 231         int             ret = 0;
 232         u32             reg;
 233 
 234         dwc3_writel(dwc->regs, DWC3_DGCMDPAR, param);
 235         dwc3_writel(dwc->regs, DWC3_DGCMD, cmd | DWC3_DGCMD_CMDACT);
 236 
 237         do {
 238                 reg = dwc3_readl(dwc->regs, DWC3_DGCMD);
 239                 if (!(reg & DWC3_DGCMD_CMDACT)) {
 240                         status = DWC3_DGCMD_STATUS(reg);
 241                         if (status)
 242                                 ret = -EINVAL;
 243                         break;
 244                 }
 245         } while (--timeout);
 246 
 247         if (!timeout) {
 248                 ret = -ETIMEDOUT;
 249                 status = -ETIMEDOUT;
 250         }
 251 
 252         trace_dwc3_gadget_generic_cmd(cmd, param, status);
 253 
 254         return ret;
 255 }
 256 
 257 static int __dwc3_gadget_wakeup(struct dwc3 *dwc);
 258 
 259 /**
 260  * dwc3_send_gadget_ep_cmd - issue an endpoint command
 261  * @dep: the endpoint to which the command is going to be issued
 262  * @cmd: the command to be issued
 263  * @params: parameters to the command
 264  *
 265  * Caller should handle locking. This function will issue @cmd with given
 266  * @params to @dep and wait for its completion.
 267  */
 268 int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned cmd,
 269                 struct dwc3_gadget_ep_cmd_params *params)
 270 {
 271         const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
 272         struct dwc3             *dwc = dep->dwc;
 273         u32                     timeout = 1000;
 274         u32                     saved_config = 0;
 275         u32                     reg;
 276 
 277         int                     cmd_status = 0;
 278         int                     ret = -EINVAL;
 279 
 280         /*
 281          * When operating in USB 2.0 speeds (HS/FS), if GUSB2PHYCFG.ENBLSLPM or
 282          * GUSB2PHYCFG.SUSPHY is set, it must be cleared before issuing an
 283          * endpoint command.
 284          *
 285          * Save and clear both GUSB2PHYCFG.ENBLSLPM and GUSB2PHYCFG.SUSPHY
 286          * settings. Restore them after the command is completed.
 287          *
 288          * DWC_usb3 3.30a and DWC_usb31 1.90a programming guide section 3.2.2
 289          */
 290         if (dwc->gadget.speed <= USB_SPEED_HIGH) {
 291                 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
 292                 if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) {
 293                         saved_config |= DWC3_GUSB2PHYCFG_SUSPHY;
 294                         reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
 295                 }
 296 
 297                 if (reg & DWC3_GUSB2PHYCFG_ENBLSLPM) {
 298                         saved_config |= DWC3_GUSB2PHYCFG_ENBLSLPM;
 299                         reg &= ~DWC3_GUSB2PHYCFG_ENBLSLPM;
 300                 }
 301 
 302                 if (saved_config)
 303                         dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
 304         }
 305 
 306         if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
 307                 int             needs_wakeup;
 308 
 309                 needs_wakeup = (dwc->link_state == DWC3_LINK_STATE_U1 ||
 310                                 dwc->link_state == DWC3_LINK_STATE_U2 ||
 311                                 dwc->link_state == DWC3_LINK_STATE_U3);
 312 
 313                 if (unlikely(needs_wakeup)) {
 314                         ret = __dwc3_gadget_wakeup(dwc);
 315                         dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n",
 316                                         ret);
 317                 }
 318         }
 319 
 320         dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0);
 321         dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1);
 322         dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2);
 323 
 324         /*
 325          * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're
 326          * not relying on XferNotReady, we can make use of a special "No
 327          * Response Update Transfer" command where we should clear both CmdAct
 328          * and CmdIOC bits.
 329          *
 330          * With this, we don't need to wait for command completion and can
 331          * straight away issue further commands to the endpoint.
 332          *
 333          * NOTICE: We're making an assumption that control endpoints will never
 334          * make use of Update Transfer command. This is a safe assumption
 335          * because we can never have more than one request at a time with
 336          * Control Endpoints. If anybody changes that assumption, this chunk
 337          * needs to be updated accordingly.
 338          */
 339         if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER &&
 340                         !usb_endpoint_xfer_isoc(desc))
 341                 cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT);
 342         else
 343                 cmd |= DWC3_DEPCMD_CMDACT;
 344 
 345         dwc3_writel(dep->regs, DWC3_DEPCMD, cmd);
 346         do {
 347                 reg = dwc3_readl(dep->regs, DWC3_DEPCMD);
 348                 if (!(reg & DWC3_DEPCMD_CMDACT)) {
 349                         cmd_status = DWC3_DEPCMD_STATUS(reg);
 350 
 351                         switch (cmd_status) {
 352                         case 0:
 353                                 ret = 0;
 354                                 break;
 355                         case DEPEVT_TRANSFER_NO_RESOURCE:
 356                                 ret = -EINVAL;
 357                                 break;
 358                         case DEPEVT_TRANSFER_BUS_EXPIRY:
 359                                 /*
 360                                  * SW issues START TRANSFER command to
 361                                  * isochronous ep with future frame interval. If
 362                                  * future interval time has already passed when
 363                                  * core receives the command, it will respond
 364                                  * with an error status of 'Bus Expiry'.
 365                                  *
 366                                  * Instead of always returning -EINVAL, let's
 367                                  * give a hint to the gadget driver that this is
 368                                  * the case by returning -EAGAIN.
 369                                  */
 370                                 ret = -EAGAIN;
 371                                 break;
 372                         default:
 373                                 dev_WARN(dwc->dev, "UNKNOWN cmd status\n");
 374                         }
 375 
 376                         break;
 377                 }
 378         } while (--timeout);
 379 
 380         if (timeout == 0) {
 381                 ret = -ETIMEDOUT;
 382                 cmd_status = -ETIMEDOUT;
 383         }
 384 
 385         trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status);
 386 
 387         if (ret == 0 && DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) {
 388                 dep->flags |= DWC3_EP_TRANSFER_STARTED;
 389                 dwc3_gadget_ep_get_transfer_index(dep);
 390         }
 391 
 392         if (saved_config) {
 393                 reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
 394                 reg |= saved_config;
 395                 dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
 396         }
 397 
 398         return ret;
 399 }
 400 
 401 static int dwc3_send_clear_stall_ep_cmd(struct dwc3_ep *dep)
 402 {
 403         struct dwc3 *dwc = dep->dwc;
 404         struct dwc3_gadget_ep_cmd_params params;
 405         u32 cmd = DWC3_DEPCMD_CLEARSTALL;
 406 
 407         /*
 408          * As of core revision 2.60a the recommended programming model
 409          * is to set the ClearPendIN bit when issuing a Clear Stall EP
 410          * command for IN endpoints. This is to prevent an issue where
 411          * some (non-compliant) hosts may not send ACK TPs for pending
 412          * IN transfers due to a mishandled error condition. Synopsys
 413          * STAR 9000614252.
 414          */
 415         if (dep->direction && (dwc->revision >= DWC3_REVISION_260A) &&
 416             (dwc->gadget.speed >= USB_SPEED_SUPER))
 417                 cmd |= DWC3_DEPCMD_CLEARPENDIN;
 418 
 419         memset(&params, 0, sizeof(params));
 420 
 421         return dwc3_send_gadget_ep_cmd(dep, cmd, &params);
 422 }
 423 
 424 static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
 425                 struct dwc3_trb *trb)
 426 {
 427         u32             offset = (char *) trb - (char *) dep->trb_pool;
 428 
 429         return dep->trb_pool_dma + offset;
 430 }
 431 
 432 static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
 433 {
 434         struct dwc3             *dwc = dep->dwc;
 435 
 436         if (dep->trb_pool)
 437                 return 0;
 438 
 439         dep->trb_pool = dma_alloc_coherent(dwc->sysdev,
 440                         sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
 441                         &dep->trb_pool_dma, GFP_KERNEL);
 442         if (!dep->trb_pool) {
 443                 dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
 444                                 dep->name);
 445                 return -ENOMEM;
 446         }
 447 
 448         return 0;
 449 }
 450 
 451 static void dwc3_free_trb_pool(struct dwc3_ep *dep)
 452 {
 453         struct dwc3             *dwc = dep->dwc;
 454 
 455         dma_free_coherent(dwc->sysdev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
 456                         dep->trb_pool, dep->trb_pool_dma);
 457 
 458         dep->trb_pool = NULL;
 459         dep->trb_pool_dma = 0;
 460 }
 461 
 462 static int dwc3_gadget_set_xfer_resource(struct dwc3_ep *dep)
 463 {
 464         struct dwc3_gadget_ep_cmd_params params;
 465 
 466         memset(&params, 0x00, sizeof(params));
 467 
 468         params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
 469 
 470         return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETTRANSFRESOURCE,
 471                         &params);
 472 }
 473 
 474 /**
 475  * dwc3_gadget_start_config - configure ep resources
 476  * @dep: endpoint that is being enabled
 477  *
 478  * Issue a %DWC3_DEPCMD_DEPSTARTCFG command to @dep. After the command's
 479  * completion, it will set Transfer Resource for all available endpoints.
 480  *
 481  * The assignment of transfer resources cannot perfectly follow the data book
 482  * due to the fact that the controller driver does not have all knowledge of the
 483  * configuration in advance. It is given this information piecemeal by the
 484  * composite gadget framework after every SET_CONFIGURATION and
 485  * SET_INTERFACE. Trying to follow the databook programming model in this
 486  * scenario can cause errors. For two reasons:
 487  *
 488  * 1) The databook says to do %DWC3_DEPCMD_DEPSTARTCFG for every
 489  * %USB_REQ_SET_CONFIGURATION and %USB_REQ_SET_INTERFACE (8.1.5). This is
 490  * incorrect in the scenario of multiple interfaces.
 491  *
 492  * 2) The databook does not mention doing more %DWC3_DEPCMD_DEPXFERCFG for new
 493  * endpoint on alt setting (8.1.6).
 494  *
 495  * The following simplified method is used instead:
 496  *
 497  * All hardware endpoints can be assigned a transfer resource and this setting
 498  * will stay persistent until either a core reset or hibernation. So whenever we
 499  * do a %DWC3_DEPCMD_DEPSTARTCFG(0) we can go ahead and do
 500  * %DWC3_DEPCMD_DEPXFERCFG for every hardware endpoint as well. We are
 501  * guaranteed that there are as many transfer resources as endpoints.
 502  *
 503  * This function is called for each endpoint when it is being enabled but is
 504  * triggered only when called for EP0-out, which always happens first, and which
 505  * should only happen in one of the above conditions.
 506  */
 507 static int dwc3_gadget_start_config(struct dwc3_ep *dep)
 508 {
 509         struct dwc3_gadget_ep_cmd_params params;
 510         struct dwc3             *dwc;
 511         u32                     cmd;
 512         int                     i;
 513         int                     ret;
 514 
 515         if (dep->number)
 516                 return 0;
 517 
 518         memset(&params, 0x00, sizeof(params));
 519         cmd = DWC3_DEPCMD_DEPSTARTCFG;
 520         dwc = dep->dwc;
 521 
 522         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
 523         if (ret)
 524                 return ret;
 525 
 526         for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
 527                 struct dwc3_ep *dep = dwc->eps[i];
 528 
 529                 if (!dep)
 530                         continue;
 531 
 532                 ret = dwc3_gadget_set_xfer_resource(dep);
 533                 if (ret)
 534                         return ret;
 535         }
 536 
 537         return 0;
 538 }
 539 
 540 static int dwc3_gadget_set_ep_config(struct dwc3_ep *dep, unsigned int action)
 541 {
 542         const struct usb_ss_ep_comp_descriptor *comp_desc;
 543         const struct usb_endpoint_descriptor *desc;
 544         struct dwc3_gadget_ep_cmd_params params;
 545         struct dwc3 *dwc = dep->dwc;
 546 
 547         comp_desc = dep->endpoint.comp_desc;
 548         desc = dep->endpoint.desc;
 549 
 550         memset(&params, 0x00, sizeof(params));
 551 
 552         params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
 553                 | DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc));
 554 
 555         /* Burst size is only needed in SuperSpeed mode */
 556         if (dwc->gadget.speed >= USB_SPEED_SUPER) {
 557                 u32 burst = dep->endpoint.maxburst;
 558                 params.param0 |= DWC3_DEPCFG_BURST_SIZE(burst - 1);
 559         }
 560 
 561         params.param0 |= action;
 562         if (action == DWC3_DEPCFG_ACTION_RESTORE)
 563                 params.param2 |= dep->saved_state;
 564 
 565         if (usb_endpoint_xfer_control(desc))
 566                 params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN;
 567 
 568         if (dep->number <= 1 || usb_endpoint_xfer_isoc(desc))
 569                 params.param1 |= DWC3_DEPCFG_XFER_NOT_READY_EN;
 570 
 571         if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
 572                 params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
 573                         | DWC3_DEPCFG_STREAM_EVENT_EN;
 574                 dep->stream_capable = true;
 575         }
 576 
 577         if (!usb_endpoint_xfer_control(desc))
 578                 params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
 579 
 580         /*
 581          * We are doing 1:1 mapping for endpoints, meaning
 582          * Physical Endpoints 2 maps to Logical Endpoint 2 and
 583          * so on. We consider the direction bit as part of the physical
 584          * endpoint number. So USB endpoint 0x81 is 0x03.
 585          */
 586         params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
 587 
 588         /*
 589          * We must use the lower 16 TX FIFOs even though
 590          * HW might have more
 591          */
 592         if (dep->direction)
 593                 params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
 594 
 595         if (desc->bInterval) {
 596                 params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(desc->bInterval - 1);
 597                 dep->interval = 1 << (desc->bInterval - 1);
 598         }
 599 
 600         return dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETEPCONFIG, &params);
 601 }
 602 
 603 /**
 604  * __dwc3_gadget_ep_enable - initializes a hw endpoint
 605  * @dep: endpoint to be initialized
 606  * @action: one of INIT, MODIFY or RESTORE
 607  *
 608  * Caller should take care of locking. Execute all necessary commands to
 609  * initialize a HW endpoint so it can be used by a gadget driver.
 610  */
 611 static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action)
 612 {
 613         const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
 614         struct dwc3             *dwc = dep->dwc;
 615 
 616         u32                     reg;
 617         int                     ret;
 618 
 619         if (!(dep->flags & DWC3_EP_ENABLED)) {
 620                 ret = dwc3_gadget_start_config(dep);
 621                 if (ret)
 622                         return ret;
 623         }
 624 
 625         ret = dwc3_gadget_set_ep_config(dep, action);
 626         if (ret)
 627                 return ret;
 628 
 629         if (!(dep->flags & DWC3_EP_ENABLED)) {
 630                 struct dwc3_trb *trb_st_hw;
 631                 struct dwc3_trb *trb_link;
 632 
 633                 dep->type = usb_endpoint_type(desc);
 634                 dep->flags |= DWC3_EP_ENABLED;
 635 
 636                 reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
 637                 reg |= DWC3_DALEPENA_EP(dep->number);
 638                 dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
 639 
 640                 if (usb_endpoint_xfer_control(desc))
 641                         goto out;
 642 
 643                 /* Initialize the TRB ring */
 644                 dep->trb_dequeue = 0;
 645                 dep->trb_enqueue = 0;
 646                 memset(dep->trb_pool, 0,
 647                        sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
 648 
 649                 /* Link TRB. The HWO bit is never reset */
 650                 trb_st_hw = &dep->trb_pool[0];
 651 
 652                 trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
 653                 trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
 654                 trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
 655                 trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
 656                 trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
 657         }
 658 
 659         /*
 660          * Issue StartTransfer here with no-op TRB so we can always rely on No
 661          * Response Update Transfer command.
 662          */
 663         if ((usb_endpoint_xfer_bulk(desc) && !dep->stream_capable) ||
 664                         usb_endpoint_xfer_int(desc)) {
 665                 struct dwc3_gadget_ep_cmd_params params;
 666                 struct dwc3_trb *trb;
 667                 dma_addr_t trb_dma;
 668                 u32 cmd;
 669 
 670                 memset(&params, 0, sizeof(params));
 671                 trb = &dep->trb_pool[0];
 672                 trb_dma = dwc3_trb_dma_offset(dep, trb);
 673 
 674                 params.param0 = upper_32_bits(trb_dma);
 675                 params.param1 = lower_32_bits(trb_dma);
 676 
 677                 cmd = DWC3_DEPCMD_STARTTRANSFER;
 678 
 679                 ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
 680                 if (ret < 0)
 681                         return ret;
 682         }
 683 
 684 out:
 685         trace_dwc3_gadget_ep_enable(dep);
 686 
 687         return 0;
 688 }
 689 
 690 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
 691                 bool interrupt);
 692 static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
 693 {
 694         struct dwc3_request             *req;
 695 
 696         dwc3_stop_active_transfer(dep, true, false);
 697 
 698         /* - giveback all requests to gadget driver */
 699         while (!list_empty(&dep->started_list)) {
 700                 req = next_request(&dep->started_list);
 701 
 702                 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
 703         }
 704 
 705         while (!list_empty(&dep->pending_list)) {
 706                 req = next_request(&dep->pending_list);
 707 
 708                 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
 709         }
 710 
 711         while (!list_empty(&dep->cancelled_list)) {
 712                 req = next_request(&dep->cancelled_list);
 713 
 714                 dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
 715         }
 716 }
 717 
 718 /**
 719  * __dwc3_gadget_ep_disable - disables a hw endpoint
 720  * @dep: the endpoint to disable
 721  *
 722  * This function undoes what __dwc3_gadget_ep_enable did and also removes
 723  * requests which are currently being processed by the hardware and those which
 724  * are not yet scheduled.
 725  *
 726  * Caller should take care of locking.
 727  */
 728 static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
 729 {
 730         struct dwc3             *dwc = dep->dwc;
 731         u32                     reg;
 732 
 733         trace_dwc3_gadget_ep_disable(dep);
 734 
 735         dwc3_remove_requests(dwc, dep);
 736 
 737         /* make sure HW endpoint isn't stalled */
 738         if (dep->flags & DWC3_EP_STALL)
 739                 __dwc3_gadget_ep_set_halt(dep, 0, false);
 740 
 741         reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
 742         reg &= ~DWC3_DALEPENA_EP(dep->number);
 743         dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
 744 
 745         dep->stream_capable = false;
 746         dep->type = 0;
 747         dep->flags = 0;
 748 
 749         /* Clear out the ep descriptors for non-ep0 */
 750         if (dep->number > 1) {
 751                 dep->endpoint.comp_desc = NULL;
 752                 dep->endpoint.desc = NULL;
 753         }
 754 
 755         return 0;
 756 }
 757 
 758 /* -------------------------------------------------------------------------- */
 759 
 760 static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
 761                 const struct usb_endpoint_descriptor *desc)
 762 {
 763         return -EINVAL;
 764 }
 765 
 766 static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
 767 {
 768         return -EINVAL;
 769 }
 770 
 771 /* -------------------------------------------------------------------------- */
 772 
 773 static int dwc3_gadget_ep_enable(struct usb_ep *ep,
 774                 const struct usb_endpoint_descriptor *desc)
 775 {
 776         struct dwc3_ep                  *dep;
 777         struct dwc3                     *dwc;
 778         unsigned long                   flags;
 779         int                             ret;
 780 
 781         if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
 782                 pr_debug("dwc3: invalid parameters\n");
 783                 return -EINVAL;
 784         }
 785 
 786         if (!desc->wMaxPacketSize) {
 787                 pr_debug("dwc3: missing wMaxPacketSize\n");
 788                 return -EINVAL;
 789         }
 790 
 791         dep = to_dwc3_ep(ep);
 792         dwc = dep->dwc;
 793 
 794         if (dev_WARN_ONCE(dwc->dev, dep->flags & DWC3_EP_ENABLED,
 795                                         "%s is already enabled\n",
 796                                         dep->name))
 797                 return 0;
 798 
 799         spin_lock_irqsave(&dwc->lock, flags);
 800         ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
 801         spin_unlock_irqrestore(&dwc->lock, flags);
 802 
 803         return ret;
 804 }
 805 
 806 static int dwc3_gadget_ep_disable(struct usb_ep *ep)
 807 {
 808         struct dwc3_ep                  *dep;
 809         struct dwc3                     *dwc;
 810         unsigned long                   flags;
 811         int                             ret;
 812 
 813         if (!ep) {
 814                 pr_debug("dwc3: invalid parameters\n");
 815                 return -EINVAL;
 816         }
 817 
 818         dep = to_dwc3_ep(ep);
 819         dwc = dep->dwc;
 820 
 821         if (dev_WARN_ONCE(dwc->dev, !(dep->flags & DWC3_EP_ENABLED),
 822                                         "%s is already disabled\n",
 823                                         dep->name))
 824                 return 0;
 825 
 826         spin_lock_irqsave(&dwc->lock, flags);
 827         ret = __dwc3_gadget_ep_disable(dep);
 828         spin_unlock_irqrestore(&dwc->lock, flags);
 829 
 830         return ret;
 831 }
 832 
 833 static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
 834                 gfp_t gfp_flags)
 835 {
 836         struct dwc3_request             *req;
 837         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
 838 
 839         req = kzalloc(sizeof(*req), gfp_flags);
 840         if (!req)
 841                 return NULL;
 842 
 843         req->direction  = dep->direction;
 844         req->epnum      = dep->number;
 845         req->dep        = dep;
 846         req->status     = DWC3_REQUEST_STATUS_UNKNOWN;
 847 
 848         trace_dwc3_alloc_request(req);
 849 
 850         return &req->request;
 851 }
 852 
 853 static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
 854                 struct usb_request *request)
 855 {
 856         struct dwc3_request             *req = to_dwc3_request(request);
 857 
 858         trace_dwc3_free_request(req);
 859         kfree(req);
 860 }
 861 
 862 /**
 863  * dwc3_ep_prev_trb - returns the previous TRB in the ring
 864  * @dep: The endpoint with the TRB ring
 865  * @index: The index of the current TRB in the ring
 866  *
 867  * Returns the TRB prior to the one pointed to by the index. If the
 868  * index is 0, we will wrap backwards, skip the link TRB, and return
 869  * the one just before that.
 870  */
 871 static struct dwc3_trb *dwc3_ep_prev_trb(struct dwc3_ep *dep, u8 index)
 872 {
 873         u8 tmp = index;
 874 
 875         if (!tmp)
 876                 tmp = DWC3_TRB_NUM - 1;
 877 
 878         return &dep->trb_pool[tmp - 1];
 879 }
 880 
 881 static u32 dwc3_calc_trbs_left(struct dwc3_ep *dep)
 882 {
 883         struct dwc3_trb         *tmp;
 884         u8                      trbs_left;
 885 
 886         /*
 887          * If enqueue & dequeue are equal than it is either full or empty.
 888          *
 889          * One way to know for sure is if the TRB right before us has HWO bit
 890          * set or not. If it has, then we're definitely full and can't fit any
 891          * more transfers in our ring.
 892          */
 893         if (dep->trb_enqueue == dep->trb_dequeue) {
 894                 tmp = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
 895                 if (tmp->ctrl & DWC3_TRB_CTRL_HWO)
 896                         return 0;
 897 
 898                 return DWC3_TRB_NUM - 1;
 899         }
 900 
 901         trbs_left = dep->trb_dequeue - dep->trb_enqueue;
 902         trbs_left &= (DWC3_TRB_NUM - 1);
 903 
 904         if (dep->trb_dequeue < dep->trb_enqueue)
 905                 trbs_left--;
 906 
 907         return trbs_left;
 908 }
 909 
 910 static void __dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_trb *trb,
 911                 dma_addr_t dma, unsigned length, unsigned chain, unsigned node,
 912                 unsigned stream_id, unsigned short_not_ok, unsigned no_interrupt)
 913 {
 914         struct dwc3             *dwc = dep->dwc;
 915         struct usb_gadget       *gadget = &dwc->gadget;
 916         enum usb_device_speed   speed = gadget->speed;
 917 
 918         trb->size = DWC3_TRB_SIZE_LENGTH(length);
 919         trb->bpl = lower_32_bits(dma);
 920         trb->bph = upper_32_bits(dma);
 921 
 922         switch (usb_endpoint_type(dep->endpoint.desc)) {
 923         case USB_ENDPOINT_XFER_CONTROL:
 924                 trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
 925                 break;
 926 
 927         case USB_ENDPOINT_XFER_ISOC:
 928                 if (!node) {
 929                         trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
 930 
 931                         /*
 932                          * USB Specification 2.0 Section 5.9.2 states that: "If
 933                          * there is only a single transaction in the microframe,
 934                          * only a DATA0 data packet PID is used.  If there are
 935                          * two transactions per microframe, DATA1 is used for
 936                          * the first transaction data packet and DATA0 is used
 937                          * for the second transaction data packet.  If there are
 938                          * three transactions per microframe, DATA2 is used for
 939                          * the first transaction data packet, DATA1 is used for
 940                          * the second, and DATA0 is used for the third."
 941                          *
 942                          * IOW, we should satisfy the following cases:
 943                          *
 944                          * 1) length <= maxpacket
 945                          *      - DATA0
 946                          *
 947                          * 2) maxpacket < length <= (2 * maxpacket)
 948                          *      - DATA1, DATA0
 949                          *
 950                          * 3) (2 * maxpacket) < length <= (3 * maxpacket)
 951                          *      - DATA2, DATA1, DATA0
 952                          */
 953                         if (speed == USB_SPEED_HIGH) {
 954                                 struct usb_ep *ep = &dep->endpoint;
 955                                 unsigned int mult = 2;
 956                                 unsigned int maxp = usb_endpoint_maxp(ep->desc);
 957 
 958                                 if (length <= (2 * maxp))
 959                                         mult--;
 960 
 961                                 if (length <= maxp)
 962                                         mult--;
 963 
 964                                 trb->size |= DWC3_TRB_SIZE_PCM1(mult);
 965                         }
 966                 } else {
 967                         trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS;
 968                 }
 969 
 970                 /* always enable Interrupt on Missed ISOC */
 971                 trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
 972                 break;
 973 
 974         case USB_ENDPOINT_XFER_BULK:
 975         case USB_ENDPOINT_XFER_INT:
 976                 trb->ctrl = DWC3_TRBCTL_NORMAL;
 977                 break;
 978         default:
 979                 /*
 980                  * This is only possible with faulty memory because we
 981                  * checked it already :)
 982                  */
 983                 dev_WARN(dwc->dev, "Unknown endpoint type %d\n",
 984                                 usb_endpoint_type(dep->endpoint.desc));
 985         }
 986 
 987         /*
 988          * Enable Continue on Short Packet
 989          * when endpoint is not a stream capable
 990          */
 991         if (usb_endpoint_dir_out(dep->endpoint.desc)) {
 992                 if (!dep->stream_capable)
 993                         trb->ctrl |= DWC3_TRB_CTRL_CSP;
 994 
 995                 if (short_not_ok)
 996                         trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
 997         }
 998 
 999         if ((!no_interrupt && !chain) ||
1000                         (dwc3_calc_trbs_left(dep) == 1))
1001                 trb->ctrl |= DWC3_TRB_CTRL_IOC;
1002 
1003         if (chain)
1004                 trb->ctrl |= DWC3_TRB_CTRL_CHN;
1005 
1006         if (usb_endpoint_xfer_bulk(dep->endpoint.desc) && dep->stream_capable)
1007                 trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(stream_id);
1008 
1009         trb->ctrl |= DWC3_TRB_CTRL_HWO;
1010 
1011         dwc3_ep_inc_enq(dep);
1012 
1013         trace_dwc3_prepare_trb(dep, trb);
1014 }
1015 
1016 /**
1017  * dwc3_prepare_one_trb - setup one TRB from one request
1018  * @dep: endpoint for which this request is prepared
1019  * @req: dwc3_request pointer
1020  * @chain: should this TRB be chained to the next?
1021  * @node: only for isochronous endpoints. First TRB needs different type.
1022  */
1023 static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
1024                 struct dwc3_request *req, unsigned chain, unsigned node)
1025 {
1026         struct dwc3_trb         *trb;
1027         unsigned int            length;
1028         dma_addr_t              dma;
1029         unsigned                stream_id = req->request.stream_id;
1030         unsigned                short_not_ok = req->request.short_not_ok;
1031         unsigned                no_interrupt = req->request.no_interrupt;
1032 
1033         if (req->request.num_sgs > 0) {
1034                 length = sg_dma_len(req->start_sg);
1035                 dma = sg_dma_address(req->start_sg);
1036         } else {
1037                 length = req->request.length;
1038                 dma = req->request.dma;
1039         }
1040 
1041         trb = &dep->trb_pool[dep->trb_enqueue];
1042 
1043         if (!req->trb) {
1044                 dwc3_gadget_move_started_request(req);
1045                 req->trb = trb;
1046                 req->trb_dma = dwc3_trb_dma_offset(dep, trb);
1047         }
1048 
1049         req->num_trbs++;
1050 
1051         __dwc3_prepare_one_trb(dep, trb, dma, length, chain, node,
1052                         stream_id, short_not_ok, no_interrupt);
1053 }
1054 
1055 static void dwc3_prepare_one_trb_sg(struct dwc3_ep *dep,
1056                 struct dwc3_request *req)
1057 {
1058         struct scatterlist *sg = req->start_sg;
1059         struct scatterlist *s;
1060         int             i;
1061 
1062         unsigned int remaining = req->request.num_mapped_sgs
1063                 - req->num_queued_sgs;
1064 
1065         for_each_sg(sg, s, remaining, i) {
1066                 unsigned int length = req->request.length;
1067                 unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1068                 unsigned int rem = length % maxp;
1069                 unsigned chain = true;
1070 
1071                 /*
1072                  * IOMMU driver is coalescing the list of sgs which shares a
1073                  * page boundary into one and giving it to USB driver. With
1074                  * this the number of sgs mapped is not equal to the number of
1075                  * sgs passed. So mark the chain bit to false if it isthe last
1076                  * mapped sg.
1077                  */
1078                 if (i == remaining - 1)
1079                         chain = false;
1080 
1081                 if (rem && usb_endpoint_dir_out(dep->endpoint.desc) && !chain) {
1082                         struct dwc3     *dwc = dep->dwc;
1083                         struct dwc3_trb *trb;
1084 
1085                         req->needs_extra_trb = true;
1086 
1087                         /* prepare normal TRB */
1088                         dwc3_prepare_one_trb(dep, req, true, i);
1089 
1090                         /* Now prepare one extra TRB to align transfer size */
1091                         trb = &dep->trb_pool[dep->trb_enqueue];
1092                         req->num_trbs++;
1093                         __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr,
1094                                         maxp - rem, false, 1,
1095                                         req->request.stream_id,
1096                                         req->request.short_not_ok,
1097                                         req->request.no_interrupt);
1098                 } else {
1099                         dwc3_prepare_one_trb(dep, req, chain, i);
1100                 }
1101 
1102                 /*
1103                  * There can be a situation where all sgs in sglist are not
1104                  * queued because of insufficient trb number. To handle this
1105                  * case, update start_sg to next sg to be queued, so that
1106                  * we have free trbs we can continue queuing from where we
1107                  * previously stopped
1108                  */
1109                 if (chain)
1110                         req->start_sg = sg_next(s);
1111 
1112                 req->num_queued_sgs++;
1113 
1114                 if (!dwc3_calc_trbs_left(dep))
1115                         break;
1116         }
1117 }
1118 
1119 static void dwc3_prepare_one_trb_linear(struct dwc3_ep *dep,
1120                 struct dwc3_request *req)
1121 {
1122         unsigned int length = req->request.length;
1123         unsigned int maxp = usb_endpoint_maxp(dep->endpoint.desc);
1124         unsigned int rem = length % maxp;
1125 
1126         if ((!length || rem) && usb_endpoint_dir_out(dep->endpoint.desc)) {
1127                 struct dwc3     *dwc = dep->dwc;
1128                 struct dwc3_trb *trb;
1129 
1130                 req->needs_extra_trb = true;
1131 
1132                 /* prepare normal TRB */
1133                 dwc3_prepare_one_trb(dep, req, true, 0);
1134 
1135                 /* Now prepare one extra TRB to align transfer size */
1136                 trb = &dep->trb_pool[dep->trb_enqueue];
1137                 req->num_trbs++;
1138                 __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, maxp - rem,
1139                                 false, 1, req->request.stream_id,
1140                                 req->request.short_not_ok,
1141                                 req->request.no_interrupt);
1142         } else if (req->request.zero && req->request.length &&
1143                    (IS_ALIGNED(req->request.length, maxp))) {
1144                 struct dwc3     *dwc = dep->dwc;
1145                 struct dwc3_trb *trb;
1146 
1147                 req->needs_extra_trb = true;
1148 
1149                 /* prepare normal TRB */
1150                 dwc3_prepare_one_trb(dep, req, true, 0);
1151 
1152                 /* Now prepare one extra TRB to handle ZLP */
1153                 trb = &dep->trb_pool[dep->trb_enqueue];
1154                 req->num_trbs++;
1155                 __dwc3_prepare_one_trb(dep, trb, dwc->bounce_addr, 0,
1156                                 false, 1, req->request.stream_id,
1157                                 req->request.short_not_ok,
1158                                 req->request.no_interrupt);
1159         } else {
1160                 dwc3_prepare_one_trb(dep, req, false, 0);
1161         }
1162 }
1163 
1164 /*
1165  * dwc3_prepare_trbs - setup TRBs from requests
1166  * @dep: endpoint for which requests are being prepared
1167  *
1168  * The function goes through the requests list and sets up TRBs for the
1169  * transfers. The function returns once there are no more TRBs available or
1170  * it runs out of requests.
1171  */
1172 static void dwc3_prepare_trbs(struct dwc3_ep *dep)
1173 {
1174         struct dwc3_request     *req, *n;
1175 
1176         BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
1177 
1178         /*
1179          * We can get in a situation where there's a request in the started list
1180          * but there weren't enough TRBs to fully kick it in the first time
1181          * around, so it has been waiting for more TRBs to be freed up.
1182          *
1183          * In that case, we should check if we have a request with pending_sgs
1184          * in the started list and prepare TRBs for that request first,
1185          * otherwise we will prepare TRBs completely out of order and that will
1186          * break things.
1187          */
1188         list_for_each_entry(req, &dep->started_list, list) {
1189                 if (req->num_pending_sgs > 0)
1190                         dwc3_prepare_one_trb_sg(dep, req);
1191 
1192                 if (!dwc3_calc_trbs_left(dep))
1193                         return;
1194         }
1195 
1196         list_for_each_entry_safe(req, n, &dep->pending_list, list) {
1197                 struct dwc3     *dwc = dep->dwc;
1198                 int             ret;
1199 
1200                 ret = usb_gadget_map_request_by_dev(dwc->sysdev, &req->request,
1201                                                     dep->direction);
1202                 if (ret)
1203                         return;
1204 
1205                 req->sg                 = req->request.sg;
1206                 req->start_sg           = req->sg;
1207                 req->num_queued_sgs     = 0;
1208                 req->num_pending_sgs    = req->request.num_mapped_sgs;
1209 
1210                 if (req->num_pending_sgs > 0)
1211                         dwc3_prepare_one_trb_sg(dep, req);
1212                 else
1213                         dwc3_prepare_one_trb_linear(dep, req);
1214 
1215                 if (!dwc3_calc_trbs_left(dep))
1216                         return;
1217         }
1218 }
1219 
1220 static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
1221 {
1222         struct dwc3_gadget_ep_cmd_params params;
1223         struct dwc3_request             *req;
1224         int                             starting;
1225         int                             ret;
1226         u32                             cmd;
1227 
1228         if (!dwc3_calc_trbs_left(dep))
1229                 return 0;
1230 
1231         starting = !(dep->flags & DWC3_EP_TRANSFER_STARTED);
1232 
1233         dwc3_prepare_trbs(dep);
1234         req = next_request(&dep->started_list);
1235         if (!req) {
1236                 dep->flags |= DWC3_EP_PENDING_REQUEST;
1237                 return 0;
1238         }
1239 
1240         memset(&params, 0, sizeof(params));
1241 
1242         if (starting) {
1243                 params.param0 = upper_32_bits(req->trb_dma);
1244                 params.param1 = lower_32_bits(req->trb_dma);
1245                 cmd = DWC3_DEPCMD_STARTTRANSFER;
1246 
1247                 if (dep->stream_capable)
1248                         cmd |= DWC3_DEPCMD_PARAM(req->request.stream_id);
1249 
1250                 if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
1251                         cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
1252         } else {
1253                 cmd = DWC3_DEPCMD_UPDATETRANSFER |
1254                         DWC3_DEPCMD_PARAM(dep->resource_index);
1255         }
1256 
1257         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1258         if (ret < 0) {
1259                 /*
1260                  * FIXME we need to iterate over the list of requests
1261                  * here and stop, unmap, free and del each of the linked
1262                  * requests instead of what we do now.
1263                  */
1264                 if (req->trb)
1265                         memset(req->trb, 0, sizeof(struct dwc3_trb));
1266                 dwc3_gadget_del_and_unmap_request(dep, req, ret);
1267                 return ret;
1268         }
1269 
1270         return 0;
1271 }
1272 
1273 static int __dwc3_gadget_get_frame(struct dwc3 *dwc)
1274 {
1275         u32                     reg;
1276 
1277         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1278         return DWC3_DSTS_SOFFN(reg);
1279 }
1280 
1281 /**
1282  * dwc3_gadget_start_isoc_quirk - workaround invalid frame number
1283  * @dep: isoc endpoint
1284  *
1285  * This function tests for the correct combination of BIT[15:14] from the 16-bit
1286  * microframe number reported by the XferNotReady event for the future frame
1287  * number to start the isoc transfer.
1288  *
1289  * In DWC_usb31 version 1.70a-ea06 and prior, for highspeed and fullspeed
1290  * isochronous IN, BIT[15:14] of the 16-bit microframe number reported by the
1291  * XferNotReady event are invalid. The driver uses this number to schedule the
1292  * isochronous transfer and passes it to the START TRANSFER command. Because
1293  * this number is invalid, the command may fail. If BIT[15:14] matches the
1294  * internal 16-bit microframe, the START TRANSFER command will pass and the
1295  * transfer will start at the scheduled time, if it is off by 1, the command
1296  * will still pass, but the transfer will start 2 seconds in the future. For all
1297  * other conditions, the START TRANSFER command will fail with bus-expiry.
1298  *
1299  * In order to workaround this issue, we can test for the correct combination of
1300  * BIT[15:14] by sending START TRANSFER commands with different values of
1301  * BIT[15:14]: 'b00, 'b01, 'b10, and 'b11. Each combination is 2^14 uframe apart
1302  * (or 2 seconds). 4 seconds into the future will result in a bus-expiry status.
1303  * As the result, within the 4 possible combinations for BIT[15:14], there will
1304  * be 2 successful and 2 failure START COMMAND status. One of the 2 successful
1305  * command status will result in a 2-second delay start. The smaller BIT[15:14]
1306  * value is the correct combination.
1307  *
1308  * Since there are only 4 outcomes and the results are ordered, we can simply
1309  * test 2 START TRANSFER commands with BIT[15:14] combinations 'b00 and 'b01 to
1310  * deduce the smaller successful combination.
1311  *
1312  * Let test0 = test status for combination 'b00 and test1 = test status for 'b01
1313  * of BIT[15:14]. The correct combination is as follow:
1314  *
1315  * if test0 fails and test1 passes, BIT[15:14] is 'b01
1316  * if test0 fails and test1 fails, BIT[15:14] is 'b10
1317  * if test0 passes and test1 fails, BIT[15:14] is 'b11
1318  * if test0 passes and test1 passes, BIT[15:14] is 'b00
1319  *
1320  * Synopsys STAR 9001202023: Wrong microframe number for isochronous IN
1321  * endpoints.
1322  */
1323 static int dwc3_gadget_start_isoc_quirk(struct dwc3_ep *dep)
1324 {
1325         int cmd_status = 0;
1326         bool test0;
1327         bool test1;
1328 
1329         while (dep->combo_num < 2) {
1330                 struct dwc3_gadget_ep_cmd_params params;
1331                 u32 test_frame_number;
1332                 u32 cmd;
1333 
1334                 /*
1335                  * Check if we can start isoc transfer on the next interval or
1336                  * 4 uframes in the future with BIT[15:14] as dep->combo_num
1337                  */
1338                 test_frame_number = dep->frame_number & 0x3fff;
1339                 test_frame_number |= dep->combo_num << 14;
1340                 test_frame_number += max_t(u32, 4, dep->interval);
1341 
1342                 params.param0 = upper_32_bits(dep->dwc->bounce_addr);
1343                 params.param1 = lower_32_bits(dep->dwc->bounce_addr);
1344 
1345                 cmd = DWC3_DEPCMD_STARTTRANSFER;
1346                 cmd |= DWC3_DEPCMD_PARAM(test_frame_number);
1347                 cmd_status = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
1348 
1349                 /* Redo if some other failure beside bus-expiry is received */
1350                 if (cmd_status && cmd_status != -EAGAIN) {
1351                         dep->start_cmd_status = 0;
1352                         dep->combo_num = 0;
1353                         return 0;
1354                 }
1355 
1356                 /* Store the first test status */
1357                 if (dep->combo_num == 0)
1358                         dep->start_cmd_status = cmd_status;
1359 
1360                 dep->combo_num++;
1361 
1362                 /*
1363                  * End the transfer if the START_TRANSFER command is successful
1364                  * to wait for the next XferNotReady to test the command again
1365                  */
1366                 if (cmd_status == 0) {
1367                         dwc3_stop_active_transfer(dep, true, true);
1368                         return 0;
1369                 }
1370         }
1371 
1372         /* test0 and test1 are both completed at this point */
1373         test0 = (dep->start_cmd_status == 0);
1374         test1 = (cmd_status == 0);
1375 
1376         if (!test0 && test1)
1377                 dep->combo_num = 1;
1378         else if (!test0 && !test1)
1379                 dep->combo_num = 2;
1380         else if (test0 && !test1)
1381                 dep->combo_num = 3;
1382         else if (test0 && test1)
1383                 dep->combo_num = 0;
1384 
1385         dep->frame_number &= 0x3fff;
1386         dep->frame_number |= dep->combo_num << 14;
1387         dep->frame_number += max_t(u32, 4, dep->interval);
1388 
1389         /* Reinitialize test variables */
1390         dep->start_cmd_status = 0;
1391         dep->combo_num = 0;
1392 
1393         return __dwc3_gadget_kick_transfer(dep);
1394 }
1395 
1396 static int __dwc3_gadget_start_isoc(struct dwc3_ep *dep)
1397 {
1398         struct dwc3 *dwc = dep->dwc;
1399         int ret;
1400         int i;
1401 
1402         if (list_empty(&dep->pending_list)) {
1403                 dep->flags |= DWC3_EP_PENDING_REQUEST;
1404                 return -EAGAIN;
1405         }
1406 
1407         if (!dwc->dis_start_transfer_quirk && dwc3_is_usb31(dwc) &&
1408             (dwc->revision <= DWC3_USB31_REVISION_160A ||
1409              (dwc->revision == DWC3_USB31_REVISION_170A &&
1410               dwc->version_type >= DWC31_VERSIONTYPE_EA01 &&
1411               dwc->version_type <= DWC31_VERSIONTYPE_EA06))) {
1412 
1413                 if (dwc->gadget.speed <= USB_SPEED_HIGH && dep->direction)
1414                         return dwc3_gadget_start_isoc_quirk(dep);
1415         }
1416 
1417         for (i = 0; i < DWC3_ISOC_MAX_RETRIES; i++) {
1418                 dep->frame_number = DWC3_ALIGN_FRAME(dep, i + 1);
1419 
1420                 ret = __dwc3_gadget_kick_transfer(dep);
1421                 if (ret != -EAGAIN)
1422                         break;
1423         }
1424 
1425         return ret;
1426 }
1427 
1428 static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
1429 {
1430         struct dwc3             *dwc = dep->dwc;
1431 
1432         if (!dep->endpoint.desc) {
1433                 dev_err(dwc->dev, "%s: can't queue to disabled endpoint\n",
1434                                 dep->name);
1435                 return -ESHUTDOWN;
1436         }
1437 
1438         if (WARN(req->dep != dep, "request %pK belongs to '%s'\n",
1439                                 &req->request, req->dep->name))
1440                 return -EINVAL;
1441 
1442         if (WARN(req->status < DWC3_REQUEST_STATUS_COMPLETED,
1443                                 "%s: request %pK already in flight\n",
1444                                 dep->name, &req->request))
1445                 return -EINVAL;
1446 
1447         pm_runtime_get(dwc->dev);
1448 
1449         req->request.actual     = 0;
1450         req->request.status     = -EINPROGRESS;
1451 
1452         trace_dwc3_ep_queue(req);
1453 
1454         list_add_tail(&req->list, &dep->pending_list);
1455         req->status = DWC3_REQUEST_STATUS_QUEUED;
1456 
1457         /* Start the transfer only after the END_TRANSFER is completed */
1458         if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) {
1459                 dep->flags |= DWC3_EP_DELAY_START;
1460                 return 0;
1461         }
1462 
1463         /*
1464          * NOTICE: Isochronous endpoints should NEVER be prestarted. We must
1465          * wait for a XferNotReady event so we will know what's the current
1466          * (micro-)frame number.
1467          *
1468          * Without this trick, we are very, very likely gonna get Bus Expiry
1469          * errors which will force us issue EndTransfer command.
1470          */
1471         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1472                 if (!(dep->flags & DWC3_EP_PENDING_REQUEST) &&
1473                                 !(dep->flags & DWC3_EP_TRANSFER_STARTED))
1474                         return 0;
1475 
1476                 if ((dep->flags & DWC3_EP_PENDING_REQUEST)) {
1477                         if (!(dep->flags & DWC3_EP_TRANSFER_STARTED)) {
1478                                 return __dwc3_gadget_start_isoc(dep);
1479                         }
1480                 }
1481         }
1482 
1483         return __dwc3_gadget_kick_transfer(dep);
1484 }
1485 
1486 static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
1487         gfp_t gfp_flags)
1488 {
1489         struct dwc3_request             *req = to_dwc3_request(request);
1490         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1491         struct dwc3                     *dwc = dep->dwc;
1492 
1493         unsigned long                   flags;
1494 
1495         int                             ret;
1496 
1497         spin_lock_irqsave(&dwc->lock, flags);
1498         ret = __dwc3_gadget_ep_queue(dep, req);
1499         spin_unlock_irqrestore(&dwc->lock, flags);
1500 
1501         return ret;
1502 }
1503 
1504 static void dwc3_gadget_ep_skip_trbs(struct dwc3_ep *dep, struct dwc3_request *req)
1505 {
1506         int i;
1507 
1508         /*
1509          * If request was already started, this means we had to
1510          * stop the transfer. With that we also need to ignore
1511          * all TRBs used by the request, however TRBs can only
1512          * be modified after completion of END_TRANSFER
1513          * command. So what we do here is that we wait for
1514          * END_TRANSFER completion and only after that, we jump
1515          * over TRBs by clearing HWO and incrementing dequeue
1516          * pointer.
1517          */
1518         for (i = 0; i < req->num_trbs; i++) {
1519                 struct dwc3_trb *trb;
1520 
1521                 trb = &dep->trb_pool[dep->trb_dequeue];
1522                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
1523                 dwc3_ep_inc_deq(dep);
1524         }
1525 
1526         req->num_trbs = 0;
1527 }
1528 
1529 static void dwc3_gadget_ep_cleanup_cancelled_requests(struct dwc3_ep *dep)
1530 {
1531         struct dwc3_request             *req;
1532         struct dwc3_request             *tmp;
1533 
1534         list_for_each_entry_safe(req, tmp, &dep->cancelled_list, list) {
1535                 dwc3_gadget_ep_skip_trbs(dep, req);
1536                 dwc3_gadget_giveback(dep, req, -ECONNRESET);
1537         }
1538 }
1539 
1540 static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
1541                 struct usb_request *request)
1542 {
1543         struct dwc3_request             *req = to_dwc3_request(request);
1544         struct dwc3_request             *r = NULL;
1545 
1546         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1547         struct dwc3                     *dwc = dep->dwc;
1548 
1549         unsigned long                   flags;
1550         int                             ret = 0;
1551 
1552         trace_dwc3_ep_dequeue(req);
1553 
1554         spin_lock_irqsave(&dwc->lock, flags);
1555 
1556         list_for_each_entry(r, &dep->pending_list, list) {
1557                 if (r == req)
1558                         break;
1559         }
1560 
1561         if (r != req) {
1562                 list_for_each_entry(r, &dep->started_list, list) {
1563                         if (r == req)
1564                                 break;
1565                 }
1566                 if (r == req) {
1567                         /* wait until it is processed */
1568                         dwc3_stop_active_transfer(dep, true, true);
1569 
1570                         if (!r->trb)
1571                                 goto out0;
1572 
1573                         dwc3_gadget_move_cancelled_request(req);
1574                         if (dep->flags & DWC3_EP_TRANSFER_STARTED)
1575                                 goto out0;
1576                         else
1577                                 goto out1;
1578                 }
1579                 dev_err(dwc->dev, "request %pK was not queued to %s\n",
1580                                 request, ep->name);
1581                 ret = -EINVAL;
1582                 goto out0;
1583         }
1584 
1585 out1:
1586         dwc3_gadget_giveback(dep, req, -ECONNRESET);
1587 
1588 out0:
1589         spin_unlock_irqrestore(&dwc->lock, flags);
1590 
1591         return ret;
1592 }
1593 
1594 int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
1595 {
1596         struct dwc3_gadget_ep_cmd_params        params;
1597         struct dwc3                             *dwc = dep->dwc;
1598         int                                     ret;
1599 
1600         if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
1601                 dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
1602                 return -EINVAL;
1603         }
1604 
1605         memset(&params, 0x00, sizeof(params));
1606 
1607         if (value) {
1608                 struct dwc3_trb *trb;
1609 
1610                 unsigned transfer_in_flight;
1611                 unsigned started;
1612 
1613                 if (dep->number > 1)
1614                         trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
1615                 else
1616                         trb = &dwc->ep0_trb[dep->trb_enqueue];
1617 
1618                 transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
1619                 started = !list_empty(&dep->started_list);
1620 
1621                 if (!protocol && ((dep->direction && transfer_in_flight) ||
1622                                 (!dep->direction && started))) {
1623                         return -EAGAIN;
1624                 }
1625 
1626                 ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
1627                                 &params);
1628                 if (ret)
1629                         dev_err(dwc->dev, "failed to set STALL on %s\n",
1630                                         dep->name);
1631                 else
1632                         dep->flags |= DWC3_EP_STALL;
1633         } else {
1634 
1635                 ret = dwc3_send_clear_stall_ep_cmd(dep);
1636                 if (ret)
1637                         dev_err(dwc->dev, "failed to clear STALL on %s\n",
1638                                         dep->name);
1639                 else
1640                         dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
1641         }
1642 
1643         return ret;
1644 }
1645 
1646 static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
1647 {
1648         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1649         struct dwc3                     *dwc = dep->dwc;
1650 
1651         unsigned long                   flags;
1652 
1653         int                             ret;
1654 
1655         spin_lock_irqsave(&dwc->lock, flags);
1656         ret = __dwc3_gadget_ep_set_halt(dep, value, false);
1657         spin_unlock_irqrestore(&dwc->lock, flags);
1658 
1659         return ret;
1660 }
1661 
1662 static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
1663 {
1664         struct dwc3_ep                  *dep = to_dwc3_ep(ep);
1665         struct dwc3                     *dwc = dep->dwc;
1666         unsigned long                   flags;
1667         int                             ret;
1668 
1669         spin_lock_irqsave(&dwc->lock, flags);
1670         dep->flags |= DWC3_EP_WEDGE;
1671 
1672         if (dep->number == 0 || dep->number == 1)
1673                 ret = __dwc3_gadget_ep0_set_halt(ep, 1);
1674         else
1675                 ret = __dwc3_gadget_ep_set_halt(dep, 1, false);
1676         spin_unlock_irqrestore(&dwc->lock, flags);
1677 
1678         return ret;
1679 }
1680 
1681 /* -------------------------------------------------------------------------- */
1682 
1683 static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
1684         .bLength        = USB_DT_ENDPOINT_SIZE,
1685         .bDescriptorType = USB_DT_ENDPOINT,
1686         .bmAttributes   = USB_ENDPOINT_XFER_CONTROL,
1687 };
1688 
1689 static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
1690         .enable         = dwc3_gadget_ep0_enable,
1691         .disable        = dwc3_gadget_ep0_disable,
1692         .alloc_request  = dwc3_gadget_ep_alloc_request,
1693         .free_request   = dwc3_gadget_ep_free_request,
1694         .queue          = dwc3_gadget_ep0_queue,
1695         .dequeue        = dwc3_gadget_ep_dequeue,
1696         .set_halt       = dwc3_gadget_ep0_set_halt,
1697         .set_wedge      = dwc3_gadget_ep_set_wedge,
1698 };
1699 
1700 static const struct usb_ep_ops dwc3_gadget_ep_ops = {
1701         .enable         = dwc3_gadget_ep_enable,
1702         .disable        = dwc3_gadget_ep_disable,
1703         .alloc_request  = dwc3_gadget_ep_alloc_request,
1704         .free_request   = dwc3_gadget_ep_free_request,
1705         .queue          = dwc3_gadget_ep_queue,
1706         .dequeue        = dwc3_gadget_ep_dequeue,
1707         .set_halt       = dwc3_gadget_ep_set_halt,
1708         .set_wedge      = dwc3_gadget_ep_set_wedge,
1709 };
1710 
1711 /* -------------------------------------------------------------------------- */
1712 
1713 static int dwc3_gadget_get_frame(struct usb_gadget *g)
1714 {
1715         struct dwc3             *dwc = gadget_to_dwc(g);
1716 
1717         return __dwc3_gadget_get_frame(dwc);
1718 }
1719 
1720 static int __dwc3_gadget_wakeup(struct dwc3 *dwc)
1721 {
1722         int                     retries;
1723 
1724         int                     ret;
1725         u32                     reg;
1726 
1727         u8                      link_state;
1728 
1729         /*
1730          * According to the Databook Remote wakeup request should
1731          * be issued only when the device is in early suspend state.
1732          *
1733          * We can check that via USB Link State bits in DSTS register.
1734          */
1735         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1736 
1737         link_state = DWC3_DSTS_USBLNKST(reg);
1738 
1739         switch (link_state) {
1740         case DWC3_LINK_STATE_RESET:
1741         case DWC3_LINK_STATE_RX_DET:    /* in HS, means Early Suspend */
1742         case DWC3_LINK_STATE_U3:        /* in HS, means SUSPEND */
1743         case DWC3_LINK_STATE_RESUME:
1744                 break;
1745         default:
1746                 return -EINVAL;
1747         }
1748 
1749         ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
1750         if (ret < 0) {
1751                 dev_err(dwc->dev, "failed to put link in Recovery\n");
1752                 return ret;
1753         }
1754 
1755         /* Recent versions do this automatically */
1756         if (dwc->revision < DWC3_REVISION_194A) {
1757                 /* write zeroes to Link Change Request */
1758                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1759                 reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
1760                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1761         }
1762 
1763         /* poll until Link State changes to ON */
1764         retries = 20000;
1765 
1766         while (retries--) {
1767                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1768 
1769                 /* in HS, means ON */
1770                 if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
1771                         break;
1772         }
1773 
1774         if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
1775                 dev_err(dwc->dev, "failed to send remote wakeup\n");
1776                 return -EINVAL;
1777         }
1778 
1779         return 0;
1780 }
1781 
1782 static int dwc3_gadget_wakeup(struct usb_gadget *g)
1783 {
1784         struct dwc3             *dwc = gadget_to_dwc(g);
1785         unsigned long           flags;
1786         int                     ret;
1787 
1788         spin_lock_irqsave(&dwc->lock, flags);
1789         ret = __dwc3_gadget_wakeup(dwc);
1790         spin_unlock_irqrestore(&dwc->lock, flags);
1791 
1792         return ret;
1793 }
1794 
1795 static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
1796                 int is_selfpowered)
1797 {
1798         struct dwc3             *dwc = gadget_to_dwc(g);
1799         unsigned long           flags;
1800 
1801         spin_lock_irqsave(&dwc->lock, flags);
1802         g->is_selfpowered = !!is_selfpowered;
1803         spin_unlock_irqrestore(&dwc->lock, flags);
1804 
1805         return 0;
1806 }
1807 
1808 static int dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on, int suspend)
1809 {
1810         u32                     reg;
1811         u32                     timeout = 500;
1812 
1813         if (pm_runtime_suspended(dwc->dev))
1814                 return 0;
1815 
1816         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
1817         if (is_on) {
1818                 if (dwc->revision <= DWC3_REVISION_187A) {
1819                         reg &= ~DWC3_DCTL_TRGTULST_MASK;
1820                         reg |= DWC3_DCTL_TRGTULST_RX_DET;
1821                 }
1822 
1823                 if (dwc->revision >= DWC3_REVISION_194A)
1824                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1825                 reg |= DWC3_DCTL_RUN_STOP;
1826 
1827                 if (dwc->has_hibernation)
1828                         reg |= DWC3_DCTL_KEEP_CONNECT;
1829 
1830                 dwc->pullups_connected = true;
1831         } else {
1832                 reg &= ~DWC3_DCTL_RUN_STOP;
1833 
1834                 if (dwc->has_hibernation && !suspend)
1835                         reg &= ~DWC3_DCTL_KEEP_CONNECT;
1836 
1837                 dwc->pullups_connected = false;
1838         }
1839 
1840         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
1841 
1842         do {
1843                 reg = dwc3_readl(dwc->regs, DWC3_DSTS);
1844                 reg &= DWC3_DSTS_DEVCTRLHLT;
1845         } while (--timeout && !(!is_on ^ !reg));
1846 
1847         if (!timeout)
1848                 return -ETIMEDOUT;
1849 
1850         return 0;
1851 }
1852 
1853 static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
1854 {
1855         struct dwc3             *dwc = gadget_to_dwc(g);
1856         unsigned long           flags;
1857         int                     ret;
1858 
1859         is_on = !!is_on;
1860 
1861         /*
1862          * Per databook, when we want to stop the gadget, if a control transfer
1863          * is still in process, complete it and get the core into setup phase.
1864          */
1865         if (!is_on && dwc->ep0state != EP0_SETUP_PHASE) {
1866                 reinit_completion(&dwc->ep0_in_setup);
1867 
1868                 ret = wait_for_completion_timeout(&dwc->ep0_in_setup,
1869                                 msecs_to_jiffies(DWC3_PULL_UP_TIMEOUT));
1870                 if (ret == 0) {
1871                         dev_err(dwc->dev, "timed out waiting for SETUP phase\n");
1872                         return -ETIMEDOUT;
1873                 }
1874         }
1875 
1876         spin_lock_irqsave(&dwc->lock, flags);
1877         ret = dwc3_gadget_run_stop(dwc, is_on, false);
1878         spin_unlock_irqrestore(&dwc->lock, flags);
1879 
1880         return ret;
1881 }
1882 
1883 static void dwc3_gadget_enable_irq(struct dwc3 *dwc)
1884 {
1885         u32                     reg;
1886 
1887         /* Enable all but Start and End of Frame IRQs */
1888         reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
1889                         DWC3_DEVTEN_EVNTOVERFLOWEN |
1890                         DWC3_DEVTEN_CMDCMPLTEN |
1891                         DWC3_DEVTEN_ERRTICERREN |
1892                         DWC3_DEVTEN_WKUPEVTEN |
1893                         DWC3_DEVTEN_CONNECTDONEEN |
1894                         DWC3_DEVTEN_USBRSTEN |
1895                         DWC3_DEVTEN_DISCONNEVTEN);
1896 
1897         if (dwc->revision < DWC3_REVISION_250A)
1898                 reg |= DWC3_DEVTEN_ULSTCNGEN;
1899 
1900         dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
1901 }
1902 
1903 static void dwc3_gadget_disable_irq(struct dwc3 *dwc)
1904 {
1905         /* mask all interrupts */
1906         dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
1907 }
1908 
1909 static irqreturn_t dwc3_interrupt(int irq, void *_dwc);
1910 static irqreturn_t dwc3_thread_interrupt(int irq, void *_dwc);
1911 
1912 /**
1913  * dwc3_gadget_setup_nump - calculate and initialize NUMP field of %DWC3_DCFG
1914  * @dwc: pointer to our context structure
1915  *
1916  * The following looks like complex but it's actually very simple. In order to
1917  * calculate the number of packets we can burst at once on OUT transfers, we're
1918  * gonna use RxFIFO size.
1919  *
1920  * To calculate RxFIFO size we need two numbers:
1921  * MDWIDTH = size, in bits, of the internal memory bus
1922  * RAM2_DEPTH = depth, in MDWIDTH, of internal RAM2 (where RxFIFO sits)
1923  *
1924  * Given these two numbers, the formula is simple:
1925  *
1926  * RxFIFO Size = (RAM2_DEPTH * MDWIDTH / 8) - 24 - 16;
1927  *
1928  * 24 bytes is for 3x SETUP packets
1929  * 16 bytes is a clock domain crossing tolerance
1930  *
1931  * Given RxFIFO Size, NUMP = RxFIFOSize / 1024;
1932  */
1933 static void dwc3_gadget_setup_nump(struct dwc3 *dwc)
1934 {
1935         u32 ram2_depth;
1936         u32 mdwidth;
1937         u32 nump;
1938         u32 reg;
1939 
1940         ram2_depth = DWC3_GHWPARAMS7_RAM2_DEPTH(dwc->hwparams.hwparams7);
1941         mdwidth = DWC3_GHWPARAMS0_MDWIDTH(dwc->hwparams.hwparams0);
1942 
1943         nump = ((ram2_depth * mdwidth / 8) - 24 - 16) / 1024;
1944         nump = min_t(u32, nump, 16);
1945 
1946         /* update NumP */
1947         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
1948         reg &= ~DWC3_DCFG_NUMP_MASK;
1949         reg |= nump << DWC3_DCFG_NUMP_SHIFT;
1950         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
1951 }
1952 
1953 static int __dwc3_gadget_start(struct dwc3 *dwc)
1954 {
1955         struct dwc3_ep          *dep;
1956         int                     ret = 0;
1957         u32                     reg;
1958 
1959         /*
1960          * Use IMOD if enabled via dwc->imod_interval. Otherwise, if
1961          * the core supports IMOD, disable it.
1962          */
1963         if (dwc->imod_interval) {
1964                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
1965                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
1966         } else if (dwc3_has_imod(dwc)) {
1967                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), 0);
1968         }
1969 
1970         /*
1971          * We are telling dwc3 that we want to use DCFG.NUMP as ACK TP's NUMP
1972          * field instead of letting dwc3 itself calculate that automatically.
1973          *
1974          * This way, we maximize the chances that we'll be able to get several
1975          * bursts of data without going through any sort of endpoint throttling.
1976          */
1977         reg = dwc3_readl(dwc->regs, DWC3_GRXTHRCFG);
1978         if (dwc3_is_usb31(dwc))
1979                 reg &= ~DWC31_GRXTHRCFG_PKTCNTSEL;
1980         else
1981                 reg &= ~DWC3_GRXTHRCFG_PKTCNTSEL;
1982 
1983         dwc3_writel(dwc->regs, DWC3_GRXTHRCFG, reg);
1984 
1985         dwc3_gadget_setup_nump(dwc);
1986 
1987         /* Start with SuperSpeed Default */
1988         dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
1989 
1990         dep = dwc->eps[0];
1991         ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1992         if (ret) {
1993                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
1994                 goto err0;
1995         }
1996 
1997         dep = dwc->eps[1];
1998         ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
1999         if (ret) {
2000                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2001                 goto err1;
2002         }
2003 
2004         /* begin to receive SETUP packets */
2005         dwc->ep0state = EP0_SETUP_PHASE;
2006         dwc->link_state = DWC3_LINK_STATE_SS_DIS;
2007         dwc3_ep0_out_start(dwc);
2008 
2009         dwc3_gadget_enable_irq(dwc);
2010 
2011         return 0;
2012 
2013 err1:
2014         __dwc3_gadget_ep_disable(dwc->eps[0]);
2015 
2016 err0:
2017         return ret;
2018 }
2019 
2020 static int dwc3_gadget_start(struct usb_gadget *g,
2021                 struct usb_gadget_driver *driver)
2022 {
2023         struct dwc3             *dwc = gadget_to_dwc(g);
2024         unsigned long           flags;
2025         int                     ret = 0;
2026         int                     irq;
2027 
2028         irq = dwc->irq_gadget;
2029         ret = request_threaded_irq(irq, dwc3_interrupt, dwc3_thread_interrupt,
2030                         IRQF_SHARED, "dwc3", dwc->ev_buf);
2031         if (ret) {
2032                 dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
2033                                 irq, ret);
2034                 goto err0;
2035         }
2036 
2037         spin_lock_irqsave(&dwc->lock, flags);
2038         if (dwc->gadget_driver) {
2039                 dev_err(dwc->dev, "%s is already bound to %s\n",
2040                                 dwc->gadget.name,
2041                                 dwc->gadget_driver->driver.name);
2042                 ret = -EBUSY;
2043                 goto err1;
2044         }
2045 
2046         dwc->gadget_driver      = driver;
2047 
2048         if (pm_runtime_active(dwc->dev))
2049                 __dwc3_gadget_start(dwc);
2050 
2051         spin_unlock_irqrestore(&dwc->lock, flags);
2052 
2053         return 0;
2054 
2055 err1:
2056         spin_unlock_irqrestore(&dwc->lock, flags);
2057         free_irq(irq, dwc);
2058 
2059 err0:
2060         return ret;
2061 }
2062 
2063 static void __dwc3_gadget_stop(struct dwc3 *dwc)
2064 {
2065         dwc3_gadget_disable_irq(dwc);
2066         __dwc3_gadget_ep_disable(dwc->eps[0]);
2067         __dwc3_gadget_ep_disable(dwc->eps[1]);
2068 }
2069 
2070 static int dwc3_gadget_stop(struct usb_gadget *g)
2071 {
2072         struct dwc3             *dwc = gadget_to_dwc(g);
2073         unsigned long           flags;
2074 
2075         spin_lock_irqsave(&dwc->lock, flags);
2076 
2077         if (pm_runtime_suspended(dwc->dev))
2078                 goto out;
2079 
2080         __dwc3_gadget_stop(dwc);
2081 
2082 out:
2083         dwc->gadget_driver      = NULL;
2084         spin_unlock_irqrestore(&dwc->lock, flags);
2085 
2086         free_irq(dwc->irq_gadget, dwc->ev_buf);
2087 
2088         return 0;
2089 }
2090 
2091 static void dwc3_gadget_config_params(struct usb_gadget *g,
2092                                       struct usb_dcd_config_params *params)
2093 {
2094         struct dwc3             *dwc = gadget_to_dwc(g);
2095 
2096         params->besl_baseline = USB_DEFAULT_BESL_UNSPECIFIED;
2097         params->besl_deep = USB_DEFAULT_BESL_UNSPECIFIED;
2098 
2099         /* Recommended BESL */
2100         if (!dwc->dis_enblslpm_quirk) {
2101                 /*
2102                  * If the recommended BESL baseline is 0 or if the BESL deep is
2103                  * less than 2, Microsoft's Windows 10 host usb stack will issue
2104                  * a usb reset immediately after it receives the extended BOS
2105                  * descriptor and the enumeration will fail. To maintain
2106                  * compatibility with the Windows' usb stack, let's set the
2107                  * recommended BESL baseline to 1 and clamp the BESL deep to be
2108                  * within 2 to 15.
2109                  */
2110                 params->besl_baseline = 1;
2111                 if (dwc->is_utmi_l1_suspend)
2112                         params->besl_deep =
2113                                 clamp_t(u8, dwc->hird_threshold, 2, 15);
2114         }
2115 
2116         /* U1 Device exit Latency */
2117         if (dwc->dis_u1_entry_quirk)
2118                 params->bU1devExitLat = 0;
2119         else
2120                 params->bU1devExitLat = DWC3_DEFAULT_U1_DEV_EXIT_LAT;
2121 
2122         /* U2 Device exit Latency */
2123         if (dwc->dis_u2_entry_quirk)
2124                 params->bU2DevExitLat = 0;
2125         else
2126                 params->bU2DevExitLat =
2127                                 cpu_to_le16(DWC3_DEFAULT_U2_DEV_EXIT_LAT);
2128 }
2129 
2130 static void dwc3_gadget_set_speed(struct usb_gadget *g,
2131                                   enum usb_device_speed speed)
2132 {
2133         struct dwc3             *dwc = gadget_to_dwc(g);
2134         unsigned long           flags;
2135         u32                     reg;
2136 
2137         spin_lock_irqsave(&dwc->lock, flags);
2138         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2139         reg &= ~(DWC3_DCFG_SPEED_MASK);
2140 
2141         /*
2142          * WORKAROUND: DWC3 revision < 2.20a have an issue
2143          * which would cause metastability state on Run/Stop
2144          * bit if we try to force the IP to USB2-only mode.
2145          *
2146          * Because of that, we cannot configure the IP to any
2147          * speed other than the SuperSpeed
2148          *
2149          * Refers to:
2150          *
2151          * STAR#9000525659: Clock Domain Crossing on DCTL in
2152          * USB 2.0 Mode
2153          */
2154         if (dwc->revision < DWC3_REVISION_220A &&
2155             !dwc->dis_metastability_quirk) {
2156                 reg |= DWC3_DCFG_SUPERSPEED;
2157         } else {
2158                 switch (speed) {
2159                 case USB_SPEED_LOW:
2160                         reg |= DWC3_DCFG_LOWSPEED;
2161                         break;
2162                 case USB_SPEED_FULL:
2163                         reg |= DWC3_DCFG_FULLSPEED;
2164                         break;
2165                 case USB_SPEED_HIGH:
2166                         reg |= DWC3_DCFG_HIGHSPEED;
2167                         break;
2168                 case USB_SPEED_SUPER:
2169                         reg |= DWC3_DCFG_SUPERSPEED;
2170                         break;
2171                 case USB_SPEED_SUPER_PLUS:
2172                         if (dwc3_is_usb31(dwc))
2173                                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2174                         else
2175                                 reg |= DWC3_DCFG_SUPERSPEED;
2176                         break;
2177                 default:
2178                         dev_err(dwc->dev, "invalid speed (%d)\n", speed);
2179 
2180                         if (dwc->revision & DWC3_REVISION_IS_DWC31)
2181                                 reg |= DWC3_DCFG_SUPERSPEED_PLUS;
2182                         else
2183                                 reg |= DWC3_DCFG_SUPERSPEED;
2184                 }
2185         }
2186         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2187 
2188         spin_unlock_irqrestore(&dwc->lock, flags);
2189 }
2190 
2191 static const struct usb_gadget_ops dwc3_gadget_ops = {
2192         .get_frame              = dwc3_gadget_get_frame,
2193         .wakeup                 = dwc3_gadget_wakeup,
2194         .set_selfpowered        = dwc3_gadget_set_selfpowered,
2195         .pullup                 = dwc3_gadget_pullup,
2196         .udc_start              = dwc3_gadget_start,
2197         .udc_stop               = dwc3_gadget_stop,
2198         .udc_set_speed          = dwc3_gadget_set_speed,
2199         .get_config_params      = dwc3_gadget_config_params,
2200 };
2201 
2202 /* -------------------------------------------------------------------------- */
2203 
2204 static int dwc3_gadget_init_control_endpoint(struct dwc3_ep *dep)
2205 {
2206         struct dwc3 *dwc = dep->dwc;
2207 
2208         usb_ep_set_maxpacket_limit(&dep->endpoint, 512);
2209         dep->endpoint.maxburst = 1;
2210         dep->endpoint.ops = &dwc3_gadget_ep0_ops;
2211         if (!dep->direction)
2212                 dwc->gadget.ep0 = &dep->endpoint;
2213 
2214         dep->endpoint.caps.type_control = true;
2215 
2216         return 0;
2217 }
2218 
2219 static int dwc3_gadget_init_in_endpoint(struct dwc3_ep *dep)
2220 {
2221         struct dwc3 *dwc = dep->dwc;
2222         int mdwidth;
2223         int size;
2224 
2225         mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2226         /* MDWIDTH is represented in bits, we need it in bytes */
2227         mdwidth /= 8;
2228 
2229         size = dwc3_readl(dwc->regs, DWC3_GTXFIFOSIZ(dep->number >> 1));
2230         if (dwc3_is_usb31(dwc))
2231                 size = DWC31_GTXFIFOSIZ_TXFDEF(size);
2232         else
2233                 size = DWC3_GTXFIFOSIZ_TXFDEF(size);
2234 
2235         /* FIFO Depth is in MDWDITH bytes. Multiply */
2236         size *= mdwidth;
2237 
2238         /*
2239          * To meet performance requirement, a minimum TxFIFO size of 3x
2240          * MaxPacketSize is recommended for endpoints that support burst and a
2241          * minimum TxFIFO size of 2x MaxPacketSize for endpoints that don't
2242          * support burst. Use those numbers and we can calculate the max packet
2243          * limit as below.
2244          */
2245         if (dwc->maximum_speed >= USB_SPEED_SUPER)
2246                 size /= 3;
2247         else
2248                 size /= 2;
2249 
2250         usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2251 
2252         dep->endpoint.max_streams = 15;
2253         dep->endpoint.ops = &dwc3_gadget_ep_ops;
2254         list_add_tail(&dep->endpoint.ep_list,
2255                         &dwc->gadget.ep_list);
2256         dep->endpoint.caps.type_iso = true;
2257         dep->endpoint.caps.type_bulk = true;
2258         dep->endpoint.caps.type_int = true;
2259 
2260         return dwc3_alloc_trb_pool(dep);
2261 }
2262 
2263 static int dwc3_gadget_init_out_endpoint(struct dwc3_ep *dep)
2264 {
2265         struct dwc3 *dwc = dep->dwc;
2266         int mdwidth;
2267         int size;
2268 
2269         mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
2270 
2271         /* MDWIDTH is represented in bits, convert to bytes */
2272         mdwidth /= 8;
2273 
2274         /* All OUT endpoints share a single RxFIFO space */
2275         size = dwc3_readl(dwc->regs, DWC3_GRXFIFOSIZ(0));
2276         if (dwc3_is_usb31(dwc))
2277                 size = DWC31_GRXFIFOSIZ_RXFDEP(size);
2278         else
2279                 size = DWC3_GRXFIFOSIZ_RXFDEP(size);
2280 
2281         /* FIFO depth is in MDWDITH bytes */
2282         size *= mdwidth;
2283 
2284         /*
2285          * To meet performance requirement, a minimum recommended RxFIFO size
2286          * is defined as follow:
2287          * RxFIFO size >= (3 x MaxPacketSize) +
2288          * (3 x 8 bytes setup packets size) + (16 bytes clock crossing margin)
2289          *
2290          * Then calculate the max packet limit as below.
2291          */
2292         size -= (3 * 8) + 16;
2293         if (size < 0)
2294                 size = 0;
2295         else
2296                 size /= 3;
2297 
2298         usb_ep_set_maxpacket_limit(&dep->endpoint, size);
2299         dep->endpoint.max_streams = 15;
2300         dep->endpoint.ops = &dwc3_gadget_ep_ops;
2301         list_add_tail(&dep->endpoint.ep_list,
2302                         &dwc->gadget.ep_list);
2303         dep->endpoint.caps.type_iso = true;
2304         dep->endpoint.caps.type_bulk = true;
2305         dep->endpoint.caps.type_int = true;
2306 
2307         return dwc3_alloc_trb_pool(dep);
2308 }
2309 
2310 static int dwc3_gadget_init_endpoint(struct dwc3 *dwc, u8 epnum)
2311 {
2312         struct dwc3_ep                  *dep;
2313         bool                            direction = epnum & 1;
2314         int                             ret;
2315         u8                              num = epnum >> 1;
2316 
2317         dep = kzalloc(sizeof(*dep), GFP_KERNEL);
2318         if (!dep)
2319                 return -ENOMEM;
2320 
2321         dep->dwc = dwc;
2322         dep->number = epnum;
2323         dep->direction = direction;
2324         dep->regs = dwc->regs + DWC3_DEP_BASE(epnum);
2325         dwc->eps[epnum] = dep;
2326         dep->combo_num = 0;
2327         dep->start_cmd_status = 0;
2328 
2329         snprintf(dep->name, sizeof(dep->name), "ep%u%s", num,
2330                         direction ? "in" : "out");
2331 
2332         dep->endpoint.name = dep->name;
2333 
2334         if (!(dep->number > 1)) {
2335                 dep->endpoint.desc = &dwc3_gadget_ep0_desc;
2336                 dep->endpoint.comp_desc = NULL;
2337         }
2338 
2339         if (num == 0)
2340                 ret = dwc3_gadget_init_control_endpoint(dep);
2341         else if (direction)
2342                 ret = dwc3_gadget_init_in_endpoint(dep);
2343         else
2344                 ret = dwc3_gadget_init_out_endpoint(dep);
2345 
2346         if (ret)
2347                 return ret;
2348 
2349         dep->endpoint.caps.dir_in = direction;
2350         dep->endpoint.caps.dir_out = !direction;
2351 
2352         INIT_LIST_HEAD(&dep->pending_list);
2353         INIT_LIST_HEAD(&dep->started_list);
2354         INIT_LIST_HEAD(&dep->cancelled_list);
2355 
2356         return 0;
2357 }
2358 
2359 static int dwc3_gadget_init_endpoints(struct dwc3 *dwc, u8 total)
2360 {
2361         u8                              epnum;
2362 
2363         INIT_LIST_HEAD(&dwc->gadget.ep_list);
2364 
2365         for (epnum = 0; epnum < total; epnum++) {
2366                 int                     ret;
2367 
2368                 ret = dwc3_gadget_init_endpoint(dwc, epnum);
2369                 if (ret)
2370                         return ret;
2371         }
2372 
2373         return 0;
2374 }
2375 
2376 static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
2377 {
2378         struct dwc3_ep                  *dep;
2379         u8                              epnum;
2380 
2381         for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2382                 dep = dwc->eps[epnum];
2383                 if (!dep)
2384                         continue;
2385                 /*
2386                  * Physical endpoints 0 and 1 are special; they form the
2387                  * bi-directional USB endpoint 0.
2388                  *
2389                  * For those two physical endpoints, we don't allocate a TRB
2390                  * pool nor do we add them the endpoints list. Due to that, we
2391                  * shouldn't do these two operations otherwise we would end up
2392                  * with all sorts of bugs when removing dwc3.ko.
2393                  */
2394                 if (epnum != 0 && epnum != 1) {
2395                         dwc3_free_trb_pool(dep);
2396                         list_del(&dep->endpoint.ep_list);
2397                 }
2398 
2399                 kfree(dep);
2400         }
2401 }
2402 
2403 /* -------------------------------------------------------------------------- */
2404 
2405 static int dwc3_gadget_ep_reclaim_completed_trb(struct dwc3_ep *dep,
2406                 struct dwc3_request *req, struct dwc3_trb *trb,
2407                 const struct dwc3_event_depevt *event, int status, int chain)
2408 {
2409         unsigned int            count;
2410 
2411         dwc3_ep_inc_deq(dep);
2412 
2413         trace_dwc3_complete_trb(dep, trb);
2414         req->num_trbs--;
2415 
2416         /*
2417          * If we're in the middle of series of chained TRBs and we
2418          * receive a short transfer along the way, DWC3 will skip
2419          * through all TRBs including the last TRB in the chain (the
2420          * where CHN bit is zero. DWC3 will also avoid clearing HWO
2421          * bit and SW has to do it manually.
2422          *
2423          * We're going to do that here to avoid problems of HW trying
2424          * to use bogus TRBs for transfers.
2425          */
2426         if (chain && (trb->ctrl & DWC3_TRB_CTRL_HWO))
2427                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2428 
2429         /*
2430          * For isochronous transfers, the first TRB in a service interval must
2431          * have the Isoc-First type. Track and report its interval frame number.
2432          */
2433         if (usb_endpoint_xfer_isoc(dep->endpoint.desc) &&
2434             (trb->ctrl & DWC3_TRBCTL_ISOCHRONOUS_FIRST)) {
2435                 unsigned int frame_number;
2436 
2437                 frame_number = DWC3_TRB_CTRL_GET_SID_SOFN(trb->ctrl);
2438                 frame_number &= ~(dep->interval - 1);
2439                 req->request.frame_number = frame_number;
2440         }
2441 
2442         /*
2443          * If we're dealing with unaligned size OUT transfer, we will be left
2444          * with one TRB pending in the ring. We need to manually clear HWO bit
2445          * from that TRB.
2446          */
2447 
2448         if (req->needs_extra_trb && !(trb->ctrl & DWC3_TRB_CTRL_CHN)) {
2449                 trb->ctrl &= ~DWC3_TRB_CTRL_HWO;
2450                 return 1;
2451         }
2452 
2453         count = trb->size & DWC3_TRB_SIZE_MASK;
2454         req->remaining += count;
2455 
2456         if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
2457                 return 1;
2458 
2459         if (event->status & DEPEVT_STATUS_SHORT && !chain)
2460                 return 1;
2461 
2462         if ((trb->ctrl & DWC3_TRB_CTRL_IOC) ||
2463             (trb->ctrl & DWC3_TRB_CTRL_LST))
2464                 return 1;
2465 
2466         return 0;
2467 }
2468 
2469 static int dwc3_gadget_ep_reclaim_trb_sg(struct dwc3_ep *dep,
2470                 struct dwc3_request *req, const struct dwc3_event_depevt *event,
2471                 int status)
2472 {
2473         struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2474         struct scatterlist *sg = req->sg;
2475         struct scatterlist *s;
2476         unsigned int pending = req->num_pending_sgs;
2477         unsigned int i;
2478         int ret = 0;
2479 
2480         for_each_sg(sg, s, pending, i) {
2481                 trb = &dep->trb_pool[dep->trb_dequeue];
2482 
2483                 req->sg = sg_next(s);
2484                 req->num_pending_sgs--;
2485 
2486                 ret = dwc3_gadget_ep_reclaim_completed_trb(dep, req,
2487                                 trb, event, status, true);
2488                 if (ret)
2489                         break;
2490         }
2491 
2492         return ret;
2493 }
2494 
2495 static int dwc3_gadget_ep_reclaim_trb_linear(struct dwc3_ep *dep,
2496                 struct dwc3_request *req, const struct dwc3_event_depevt *event,
2497                 int status)
2498 {
2499         struct dwc3_trb *trb = &dep->trb_pool[dep->trb_dequeue];
2500 
2501         return dwc3_gadget_ep_reclaim_completed_trb(dep, req, trb,
2502                         event, status, false);
2503 }
2504 
2505 static bool dwc3_gadget_ep_request_completed(struct dwc3_request *req)
2506 {
2507         return req->num_pending_sgs == 0;
2508 }
2509 
2510 static int dwc3_gadget_ep_cleanup_completed_request(struct dwc3_ep *dep,
2511                 const struct dwc3_event_depevt *event,
2512                 struct dwc3_request *req, int status)
2513 {
2514         int ret;
2515 
2516         if (req->num_pending_sgs)
2517                 ret = dwc3_gadget_ep_reclaim_trb_sg(dep, req, event,
2518                                 status);
2519         else
2520                 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2521                                 status);
2522 
2523         if (req->needs_extra_trb) {
2524                 ret = dwc3_gadget_ep_reclaim_trb_linear(dep, req, event,
2525                                 status);
2526                 req->needs_extra_trb = false;
2527         }
2528 
2529         req->request.actual = req->request.length - req->remaining;
2530 
2531         if (!dwc3_gadget_ep_request_completed(req)) {
2532                 __dwc3_gadget_kick_transfer(dep);
2533                 goto out;
2534         }
2535 
2536         dwc3_gadget_giveback(dep, req, status);
2537 
2538 out:
2539         return ret;
2540 }
2541 
2542 static void dwc3_gadget_ep_cleanup_completed_requests(struct dwc3_ep *dep,
2543                 const struct dwc3_event_depevt *event, int status)
2544 {
2545         struct dwc3_request     *req;
2546         struct dwc3_request     *tmp;
2547 
2548         list_for_each_entry_safe(req, tmp, &dep->started_list, list) {
2549                 int ret;
2550 
2551                 ret = dwc3_gadget_ep_cleanup_completed_request(dep, event,
2552                                 req, status);
2553                 if (ret)
2554                         break;
2555         }
2556 }
2557 
2558 static void dwc3_gadget_endpoint_frame_from_event(struct dwc3_ep *dep,
2559                 const struct dwc3_event_depevt *event)
2560 {
2561         dep->frame_number = event->parameters;
2562 }
2563 
2564 static void dwc3_gadget_endpoint_transfer_in_progress(struct dwc3_ep *dep,
2565                 const struct dwc3_event_depevt *event)
2566 {
2567         struct dwc3             *dwc = dep->dwc;
2568         unsigned                status = 0;
2569         bool                    stop = false;
2570 
2571         dwc3_gadget_endpoint_frame_from_event(dep, event);
2572 
2573         if (event->status & DEPEVT_STATUS_BUSERR)
2574                 status = -ECONNRESET;
2575 
2576         if (event->status & DEPEVT_STATUS_MISSED_ISOC) {
2577                 status = -EXDEV;
2578 
2579                 if (list_empty(&dep->started_list))
2580                         stop = true;
2581         }
2582 
2583         dwc3_gadget_ep_cleanup_completed_requests(dep, event, status);
2584 
2585         if (stop)
2586                 dwc3_stop_active_transfer(dep, true, true);
2587 
2588         /*
2589          * WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
2590          * See dwc3_gadget_linksts_change_interrupt() for 1st half.
2591          */
2592         if (dwc->revision < DWC3_REVISION_183A) {
2593                 u32             reg;
2594                 int             i;
2595 
2596                 for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
2597                         dep = dwc->eps[i];
2598 
2599                         if (!(dep->flags & DWC3_EP_ENABLED))
2600                                 continue;
2601 
2602                         if (!list_empty(&dep->started_list))
2603                                 return;
2604                 }
2605 
2606                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2607                 reg |= dwc->u1u2;
2608                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2609 
2610                 dwc->u1u2 = 0;
2611         }
2612 }
2613 
2614 static void dwc3_gadget_endpoint_transfer_not_ready(struct dwc3_ep *dep,
2615                 const struct dwc3_event_depevt *event)
2616 {
2617         dwc3_gadget_endpoint_frame_from_event(dep, event);
2618         (void) __dwc3_gadget_start_isoc(dep);
2619 }
2620 
2621 static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
2622                 const struct dwc3_event_depevt *event)
2623 {
2624         struct dwc3_ep          *dep;
2625         u8                      epnum = event->endpoint_number;
2626         u8                      cmd;
2627 
2628         dep = dwc->eps[epnum];
2629 
2630         if (!(dep->flags & DWC3_EP_ENABLED)) {
2631                 if (!(dep->flags & DWC3_EP_TRANSFER_STARTED))
2632                         return;
2633 
2634                 /* Handle only EPCMDCMPLT when EP disabled */
2635                 if (event->endpoint_event != DWC3_DEPEVT_EPCMDCMPLT)
2636                         return;
2637         }
2638 
2639         if (epnum == 0 || epnum == 1) {
2640                 dwc3_ep0_interrupt(dwc, event);
2641                 return;
2642         }
2643 
2644         switch (event->endpoint_event) {
2645         case DWC3_DEPEVT_XFERINPROGRESS:
2646                 dwc3_gadget_endpoint_transfer_in_progress(dep, event);
2647                 break;
2648         case DWC3_DEPEVT_XFERNOTREADY:
2649                 dwc3_gadget_endpoint_transfer_not_ready(dep, event);
2650                 break;
2651         case DWC3_DEPEVT_EPCMDCMPLT:
2652                 cmd = DEPEVT_PARAMETER_CMD(event->parameters);
2653 
2654                 if (cmd == DWC3_DEPCMD_ENDTRANSFER) {
2655                         dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
2656                         dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
2657                         dwc3_gadget_ep_cleanup_cancelled_requests(dep);
2658                         if ((dep->flags & DWC3_EP_DELAY_START) &&
2659                             !usb_endpoint_xfer_isoc(dep->endpoint.desc))
2660                                 __dwc3_gadget_kick_transfer(dep);
2661 
2662                         dep->flags &= ~DWC3_EP_DELAY_START;
2663                 }
2664                 break;
2665         case DWC3_DEPEVT_STREAMEVT:
2666         case DWC3_DEPEVT_XFERCOMPLETE:
2667         case DWC3_DEPEVT_RXTXFIFOEVT:
2668                 break;
2669         }
2670 }
2671 
2672 static void dwc3_disconnect_gadget(struct dwc3 *dwc)
2673 {
2674         if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
2675                 spin_unlock(&dwc->lock);
2676                 dwc->gadget_driver->disconnect(&dwc->gadget);
2677                 spin_lock(&dwc->lock);
2678         }
2679 }
2680 
2681 static void dwc3_suspend_gadget(struct dwc3 *dwc)
2682 {
2683         if (dwc->gadget_driver && dwc->gadget_driver->suspend) {
2684                 spin_unlock(&dwc->lock);
2685                 dwc->gadget_driver->suspend(&dwc->gadget);
2686                 spin_lock(&dwc->lock);
2687         }
2688 }
2689 
2690 static void dwc3_resume_gadget(struct dwc3 *dwc)
2691 {
2692         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2693                 spin_unlock(&dwc->lock);
2694                 dwc->gadget_driver->resume(&dwc->gadget);
2695                 spin_lock(&dwc->lock);
2696         }
2697 }
2698 
2699 static void dwc3_reset_gadget(struct dwc3 *dwc)
2700 {
2701         if (!dwc->gadget_driver)
2702                 return;
2703 
2704         if (dwc->gadget.speed != USB_SPEED_UNKNOWN) {
2705                 spin_unlock(&dwc->lock);
2706                 usb_gadget_udc_reset(&dwc->gadget, dwc->gadget_driver);
2707                 spin_lock(&dwc->lock);
2708         }
2709 }
2710 
2711 static void dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force,
2712         bool interrupt)
2713 {
2714         struct dwc3 *dwc = dep->dwc;
2715         struct dwc3_gadget_ep_cmd_params params;
2716         u32 cmd;
2717         int ret;
2718 
2719         if (!(dep->flags & DWC3_EP_TRANSFER_STARTED) ||
2720             (dep->flags & DWC3_EP_END_TRANSFER_PENDING))
2721                 return;
2722 
2723         /*
2724          * NOTICE: We are violating what the Databook says about the
2725          * EndTransfer command. Ideally we would _always_ wait for the
2726          * EndTransfer Command Completion IRQ, but that's causing too
2727          * much trouble synchronizing between us and gadget driver.
2728          *
2729          * We have discussed this with the IP Provider and it was
2730          * suggested to giveback all requests here, but give HW some
2731          * extra time to synchronize with the interconnect. We're using
2732          * an arbitrary 100us delay for that.
2733          *
2734          * Note also that a similar handling was tested by Synopsys
2735          * (thanks a lot Paul) and nothing bad has come out of it.
2736          * In short, what we're doing is:
2737          *
2738          * - Issue EndTransfer WITH CMDIOC bit set
2739          * - Wait 100us
2740          *
2741          * As of IP version 3.10a of the DWC_usb3 IP, the controller
2742          * supports a mode to work around the above limitation. The
2743          * software can poll the CMDACT bit in the DEPCMD register
2744          * after issuing a EndTransfer command. This mode is enabled
2745          * by writing GUCTL2[14]. This polling is already done in the
2746          * dwc3_send_gadget_ep_cmd() function so if the mode is
2747          * enabled, the EndTransfer command will have completed upon
2748          * returning from this function and we don't need to delay for
2749          * 100us.
2750          *
2751          * This mode is NOT available on the DWC_usb31 IP.
2752          */
2753 
2754         cmd = DWC3_DEPCMD_ENDTRANSFER;
2755         cmd |= force ? DWC3_DEPCMD_HIPRI_FORCERM : 0;
2756         cmd |= interrupt ? DWC3_DEPCMD_CMDIOC : 0;
2757         cmd |= DWC3_DEPCMD_PARAM(dep->resource_index);
2758         memset(&params, 0, sizeof(params));
2759         ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
2760         WARN_ON_ONCE(ret);
2761         dep->resource_index = 0;
2762 
2763         if (!interrupt)
2764                 dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
2765         else
2766                 dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
2767 
2768         if (dwc3_is_usb31(dwc) || dwc->revision < DWC3_REVISION_310A)
2769                 udelay(100);
2770 }
2771 
2772 static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
2773 {
2774         u32 epnum;
2775 
2776         for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
2777                 struct dwc3_ep *dep;
2778                 int ret;
2779 
2780                 dep = dwc->eps[epnum];
2781                 if (!dep)
2782                         continue;
2783 
2784                 if (!(dep->flags & DWC3_EP_STALL))
2785                         continue;
2786 
2787                 dep->flags &= ~DWC3_EP_STALL;
2788 
2789                 ret = dwc3_send_clear_stall_ep_cmd(dep);
2790                 WARN_ON_ONCE(ret);
2791         }
2792 }
2793 
2794 static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
2795 {
2796         int                     reg;
2797 
2798         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2799         reg &= ~DWC3_DCTL_INITU1ENA;
2800         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2801 
2802         reg &= ~DWC3_DCTL_INITU2ENA;
2803         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2804 
2805         dwc3_disconnect_gadget(dwc);
2806 
2807         dwc->gadget.speed = USB_SPEED_UNKNOWN;
2808         dwc->setup_packet_pending = false;
2809         usb_gadget_set_state(&dwc->gadget, USB_STATE_NOTATTACHED);
2810 
2811         dwc->connected = false;
2812 }
2813 
2814 static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
2815 {
2816         u32                     reg;
2817 
2818         dwc->connected = true;
2819 
2820         /*
2821          * WORKAROUND: DWC3 revisions <1.88a have an issue which
2822          * would cause a missing Disconnect Event if there's a
2823          * pending Setup Packet in the FIFO.
2824          *
2825          * There's no suggested workaround on the official Bug
2826          * report, which states that "unless the driver/application
2827          * is doing any special handling of a disconnect event,
2828          * there is no functional issue".
2829          *
2830          * Unfortunately, it turns out that we _do_ some special
2831          * handling of a disconnect event, namely complete all
2832          * pending transfers, notify gadget driver of the
2833          * disconnection, and so on.
2834          *
2835          * Our suggested workaround is to follow the Disconnect
2836          * Event steps here, instead, based on a setup_packet_pending
2837          * flag. Such flag gets set whenever we have a SETUP_PENDING
2838          * status for EP0 TRBs and gets cleared on XferComplete for the
2839          * same endpoint.
2840          *
2841          * Refers to:
2842          *
2843          * STAR#9000466709: RTL: Device : Disconnect event not
2844          * generated if setup packet pending in FIFO
2845          */
2846         if (dwc->revision < DWC3_REVISION_188A) {
2847                 if (dwc->setup_packet_pending)
2848                         dwc3_gadget_disconnect_interrupt(dwc);
2849         }
2850 
2851         dwc3_reset_gadget(dwc);
2852 
2853         reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2854         reg &= ~DWC3_DCTL_TSTCTRL_MASK;
2855         dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2856         dwc->test_mode = false;
2857         dwc3_clear_stall_all_ep(dwc);
2858 
2859         /* Reset device address to zero */
2860         reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2861         reg &= ~(DWC3_DCFG_DEVADDR_MASK);
2862         dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2863 }
2864 
2865 static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
2866 {
2867         struct dwc3_ep          *dep;
2868         int                     ret;
2869         u32                     reg;
2870         u8                      speed;
2871 
2872         reg = dwc3_readl(dwc->regs, DWC3_DSTS);
2873         speed = reg & DWC3_DSTS_CONNECTSPD;
2874         dwc->speed = speed;
2875 
2876         /*
2877          * RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
2878          * each time on Connect Done.
2879          *
2880          * Currently we always use the reset value. If any platform
2881          * wants to set this to a different value, we need to add a
2882          * setting and update GCTL.RAMCLKSEL here.
2883          */
2884 
2885         switch (speed) {
2886         case DWC3_DSTS_SUPERSPEED_PLUS:
2887                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2888                 dwc->gadget.ep0->maxpacket = 512;
2889                 dwc->gadget.speed = USB_SPEED_SUPER_PLUS;
2890                 break;
2891         case DWC3_DSTS_SUPERSPEED:
2892                 /*
2893                  * WORKAROUND: DWC3 revisions <1.90a have an issue which
2894                  * would cause a missing USB3 Reset event.
2895                  *
2896                  * In such situations, we should force a USB3 Reset
2897                  * event by calling our dwc3_gadget_reset_interrupt()
2898                  * routine.
2899                  *
2900                  * Refers to:
2901                  *
2902                  * STAR#9000483510: RTL: SS : USB3 reset event may
2903                  * not be generated always when the link enters poll
2904                  */
2905                 if (dwc->revision < DWC3_REVISION_190A)
2906                         dwc3_gadget_reset_interrupt(dwc);
2907 
2908                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
2909                 dwc->gadget.ep0->maxpacket = 512;
2910                 dwc->gadget.speed = USB_SPEED_SUPER;
2911                 break;
2912         case DWC3_DSTS_HIGHSPEED:
2913                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2914                 dwc->gadget.ep0->maxpacket = 64;
2915                 dwc->gadget.speed = USB_SPEED_HIGH;
2916                 break;
2917         case DWC3_DSTS_FULLSPEED:
2918                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
2919                 dwc->gadget.ep0->maxpacket = 64;
2920                 dwc->gadget.speed = USB_SPEED_FULL;
2921                 break;
2922         case DWC3_DSTS_LOWSPEED:
2923                 dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
2924                 dwc->gadget.ep0->maxpacket = 8;
2925                 dwc->gadget.speed = USB_SPEED_LOW;
2926                 break;
2927         }
2928 
2929         dwc->eps[1]->endpoint.maxpacket = dwc->gadget.ep0->maxpacket;
2930 
2931         /* Enable USB2 LPM Capability */
2932 
2933         if ((dwc->revision > DWC3_REVISION_194A) &&
2934             (speed != DWC3_DSTS_SUPERSPEED) &&
2935             (speed != DWC3_DSTS_SUPERSPEED_PLUS)) {
2936                 reg = dwc3_readl(dwc->regs, DWC3_DCFG);
2937                 reg |= DWC3_DCFG_LPM_CAP;
2938                 dwc3_writel(dwc->regs, DWC3_DCFG, reg);
2939 
2940                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2941                 reg &= ~(DWC3_DCTL_HIRD_THRES_MASK | DWC3_DCTL_L1_HIBER_EN);
2942 
2943                 reg |= DWC3_DCTL_HIRD_THRES(dwc->hird_threshold |
2944                                             (dwc->is_utmi_l1_suspend << 4));
2945 
2946                 /*
2947                  * When dwc3 revisions >= 2.40a, LPM Erratum is enabled and
2948                  * DCFG.LPMCap is set, core responses with an ACK and the
2949                  * BESL value in the LPM token is less than or equal to LPM
2950                  * NYET threshold.
2951                  */
2952                 WARN_ONCE(dwc->revision < DWC3_REVISION_240A
2953                                 && dwc->has_lpm_erratum,
2954                                 "LPM Erratum not available on dwc3 revisions < 2.40a\n");
2955 
2956                 if (dwc->has_lpm_erratum && dwc->revision >= DWC3_REVISION_240A)
2957                         reg |= DWC3_DCTL_NYET_THRES(dwc->lpm_nyet_threshold);
2958 
2959                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2960         } else {
2961                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
2962                 reg &= ~DWC3_DCTL_HIRD_THRES_MASK;
2963                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
2964         }
2965 
2966         dep = dwc->eps[0];
2967         ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
2968         if (ret) {
2969                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2970                 return;
2971         }
2972 
2973         dep = dwc->eps[1];
2974         ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_MODIFY);
2975         if (ret) {
2976                 dev_err(dwc->dev, "failed to enable %s\n", dep->name);
2977                 return;
2978         }
2979 
2980         /*
2981          * Configure PHY via GUSB3PIPECTLn if required.
2982          *
2983          * Update GTXFIFOSIZn
2984          *
2985          * In both cases reset values should be sufficient.
2986          */
2987 }
2988 
2989 static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
2990 {
2991         /*
2992          * TODO take core out of low power mode when that's
2993          * implemented.
2994          */
2995 
2996         if (dwc->gadget_driver && dwc->gadget_driver->resume) {
2997                 spin_unlock(&dwc->lock);
2998                 dwc->gadget_driver->resume(&dwc->gadget);
2999                 spin_lock(&dwc->lock);
3000         }
3001 }
3002 
3003 static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
3004                 unsigned int evtinfo)
3005 {
3006         enum dwc3_link_state    next = evtinfo & DWC3_LINK_STATE_MASK;
3007         unsigned int            pwropt;
3008 
3009         /*
3010          * WORKAROUND: DWC3 < 2.50a have an issue when configured without
3011          * Hibernation mode enabled which would show up when device detects
3012          * host-initiated U3 exit.
3013          *
3014          * In that case, device will generate a Link State Change Interrupt
3015          * from U3 to RESUME which is only necessary if Hibernation is
3016          * configured in.
3017          *
3018          * There are no functional changes due to such spurious event and we
3019          * just need to ignore it.
3020          *
3021          * Refers to:
3022          *
3023          * STAR#9000570034 RTL: SS Resume event generated in non-Hibernation
3024          * operational mode
3025          */
3026         pwropt = DWC3_GHWPARAMS1_EN_PWROPT(dwc->hwparams.hwparams1);
3027         if ((dwc->revision < DWC3_REVISION_250A) &&
3028                         (pwropt != DWC3_GHWPARAMS1_EN_PWROPT_HIB)) {
3029                 if ((dwc->link_state == DWC3_LINK_STATE_U3) &&
3030                                 (next == DWC3_LINK_STATE_RESUME)) {
3031                         return;
3032                 }
3033         }
3034 
3035         /*
3036          * WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
3037          * on the link partner, the USB session might do multiple entry/exit
3038          * of low power states before a transfer takes place.
3039          *
3040          * Due to this problem, we might experience lower throughput. The
3041          * suggested workaround is to disable DCTL[12:9] bits if we're
3042          * transitioning from U1/U2 to U0 and enable those bits again
3043          * after a transfer completes and there are no pending transfers
3044          * on any of the enabled endpoints.
3045          *
3046          * This is the first half of that workaround.
3047          *
3048          * Refers to:
3049          *
3050          * STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
3051          * core send LGO_Ux entering U0
3052          */
3053         if (dwc->revision < DWC3_REVISION_183A) {
3054                 if (next == DWC3_LINK_STATE_U0) {
3055                         u32     u1u2;
3056                         u32     reg;
3057 
3058                         switch (dwc->link_state) {
3059                         case DWC3_LINK_STATE_U1:
3060                         case DWC3_LINK_STATE_U2:
3061                                 reg = dwc3_readl(dwc->regs, DWC3_DCTL);
3062                                 u1u2 = reg & (DWC3_DCTL_INITU2ENA
3063                                                 | DWC3_DCTL_ACCEPTU2ENA
3064                                                 | DWC3_DCTL_INITU1ENA
3065                                                 | DWC3_DCTL_ACCEPTU1ENA);
3066 
3067                                 if (!dwc->u1u2)
3068                                         dwc->u1u2 = reg & u1u2;
3069 
3070                                 reg &= ~u1u2;
3071 
3072                                 dwc3_writel(dwc->regs, DWC3_DCTL, reg);
3073                                 break;
3074                         default:
3075                                 /* do nothing */
3076                                 break;
3077                         }
3078                 }
3079         }
3080 
3081         switch (next) {
3082         case DWC3_LINK_STATE_U1:
3083                 if (dwc->speed == USB_SPEED_SUPER)
3084                         dwc3_suspend_gadget(dwc);
3085                 break;
3086         case DWC3_LINK_STATE_U2:
3087         case DWC3_LINK_STATE_U3:
3088                 dwc3_suspend_gadget(dwc);
3089                 break;
3090         case DWC3_LINK_STATE_RESUME:
3091                 dwc3_resume_gadget(dwc);
3092                 break;
3093         default:
3094                 /* do nothing */
3095                 break;
3096         }
3097 
3098         dwc->link_state = next;
3099 }
3100 
3101 static void dwc3_gadget_suspend_interrupt(struct dwc3 *dwc,
3102                                           unsigned int evtinfo)
3103 {
3104         enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
3105 
3106         if (dwc->link_state != next && next == DWC3_LINK_STATE_U3)
3107                 dwc3_suspend_gadget(dwc);
3108 
3109         dwc->link_state = next;
3110 }
3111 
3112 static void dwc3_gadget_hibernation_interrupt(struct dwc3 *dwc,
3113                 unsigned int evtinfo)
3114 {
3115         unsigned int is_ss = evtinfo & BIT(4);
3116 
3117         /*
3118          * WORKAROUND: DWC3 revison 2.20a with hibernation support
3119          * have a known issue which can cause USB CV TD.9.23 to fail
3120          * randomly.
3121          *
3122          * Because of this issue, core could generate bogus hibernation
3123          * events which SW needs to ignore.
3124          *
3125          * Refers to:
3126          *
3127          * STAR#9000546576: Device Mode Hibernation: Issue in USB 2.0
3128          * Device Fallback from SuperSpeed
3129          */
3130         if (is_ss ^ (dwc->speed == USB_SPEED_SUPER))
3131                 return;
3132 
3133         /* enter hibernation here */
3134 }
3135 
3136 static void dwc3_gadget_interrupt(struct dwc3 *dwc,
3137                 const struct dwc3_event_devt *event)
3138 {
3139         switch (event->type) {
3140         case DWC3_DEVICE_EVENT_DISCONNECT:
3141                 dwc3_gadget_disconnect_interrupt(dwc);
3142                 break;
3143         case DWC3_DEVICE_EVENT_RESET:
3144                 dwc3_gadget_reset_interrupt(dwc);
3145                 break;
3146         case DWC3_DEVICE_EVENT_CONNECT_DONE:
3147                 dwc3_gadget_conndone_interrupt(dwc);
3148                 break;
3149         case DWC3_DEVICE_EVENT_WAKEUP:
3150                 dwc3_gadget_wakeup_interrupt(dwc);
3151                 break;
3152         case DWC3_DEVICE_EVENT_HIBER_REQ:
3153                 if (dev_WARN_ONCE(dwc->dev, !dwc->has_hibernation,
3154                                         "unexpected hibernation event\n"))
3155                         break;
3156 
3157                 dwc3_gadget_hibernation_interrupt(dwc, event->event_info);
3158                 break;
3159         case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
3160                 dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
3161                 break;
3162         case DWC3_DEVICE_EVENT_EOPF:
3163                 /* It changed to be suspend event for version 2.30a and above */
3164                 if (dwc->revision >= DWC3_REVISION_230A) {
3165                         /*
3166                          * Ignore suspend event until the gadget enters into
3167                          * USB_STATE_CONFIGURED state.
3168                          */
3169                         if (dwc->gadget.state >= USB_STATE_CONFIGURED)
3170                                 dwc3_gadget_suspend_interrupt(dwc,
3171                                                 event->event_info);
3172                 }
3173                 break;
3174         case DWC3_DEVICE_EVENT_SOF:
3175         case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
3176         case DWC3_DEVICE_EVENT_CMD_CMPL:
3177         case DWC3_DEVICE_EVENT_OVERFLOW:
3178                 break;
3179         default:
3180                 dev_WARN(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
3181         }
3182 }
3183 
3184 static void dwc3_process_event_entry(struct dwc3 *dwc,
3185                 const union dwc3_event *event)
3186 {
3187         trace_dwc3_event(event->raw, dwc);
3188 
3189         if (!event->type.is_devspec)
3190                 dwc3_endpoint_interrupt(dwc, &event->depevt);
3191         else if (event->type.type == DWC3_EVENT_TYPE_DEV)
3192                 dwc3_gadget_interrupt(dwc, &event->devt);
3193         else
3194                 dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
3195 }
3196 
3197 static irqreturn_t dwc3_process_event_buf(struct dwc3_event_buffer *evt)
3198 {
3199         struct dwc3 *dwc = evt->dwc;
3200         irqreturn_t ret = IRQ_NONE;
3201         int left;
3202         u32 reg;
3203 
3204         left = evt->count;
3205 
3206         if (!(evt->flags & DWC3_EVENT_PENDING))
3207                 return IRQ_NONE;
3208 
3209         while (left > 0) {
3210                 union dwc3_event event;
3211 
3212                 event.raw = *(u32 *) (evt->cache + evt->lpos);
3213 
3214                 dwc3_process_event_entry(dwc, &event);
3215 
3216                 /*
3217                  * FIXME we wrap around correctly to the next entry as
3218                  * almost all entries are 4 bytes in size. There is one
3219                  * entry which has 12 bytes which is a regular entry
3220                  * followed by 8 bytes data. ATM I don't know how
3221                  * things are organized if we get next to the a
3222                  * boundary so I worry about that once we try to handle
3223                  * that.
3224                  */
3225                 evt->lpos = (evt->lpos + 4) % evt->length;
3226                 left -= 4;
3227         }
3228 
3229         evt->count = 0;
3230         evt->flags &= ~DWC3_EVENT_PENDING;
3231         ret = IRQ_HANDLED;
3232 
3233         /* Unmask interrupt */
3234         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3235         reg &= ~DWC3_GEVNTSIZ_INTMASK;
3236         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3237 
3238         if (dwc->imod_interval) {
3239                 dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), DWC3_GEVNTCOUNT_EHB);
3240                 dwc3_writel(dwc->regs, DWC3_DEV_IMOD(0), dwc->imod_interval);
3241         }
3242 
3243         return ret;
3244 }
3245 
3246 static irqreturn_t dwc3_thread_interrupt(int irq, void *_evt)
3247 {
3248         struct dwc3_event_buffer *evt = _evt;
3249         struct dwc3 *dwc = evt->dwc;
3250         unsigned long flags;
3251         irqreturn_t ret = IRQ_NONE;
3252 
3253         spin_lock_irqsave(&dwc->lock, flags);
3254         ret = dwc3_process_event_buf(evt);
3255         spin_unlock_irqrestore(&dwc->lock, flags);
3256 
3257         return ret;
3258 }
3259 
3260 static irqreturn_t dwc3_check_event_buf(struct dwc3_event_buffer *evt)
3261 {
3262         struct dwc3 *dwc = evt->dwc;
3263         u32 amount;
3264         u32 count;
3265         u32 reg;
3266 
3267         if (pm_runtime_suspended(dwc->dev)) {
3268                 pm_runtime_get(dwc->dev);
3269                 disable_irq_nosync(dwc->irq_gadget);
3270                 dwc->pending_events = true;
3271                 return IRQ_HANDLED;
3272         }
3273 
3274         /*
3275          * With PCIe legacy interrupt, test shows that top-half irq handler can
3276          * be called again after HW interrupt deassertion. Check if bottom-half
3277          * irq event handler completes before caching new event to prevent
3278          * losing events.
3279          */
3280         if (evt->flags & DWC3_EVENT_PENDING)
3281                 return IRQ_HANDLED;
3282 
3283         count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(0));
3284         count &= DWC3_GEVNTCOUNT_MASK;
3285         if (!count)
3286                 return IRQ_NONE;
3287 
3288         evt->count = count;
3289         evt->flags |= DWC3_EVENT_PENDING;
3290 
3291         /* Mask interrupt */
3292         reg = dwc3_readl(dwc->regs, DWC3_GEVNTSIZ(0));
3293         reg |= DWC3_GEVNTSIZ_INTMASK;
3294         dwc3_writel(dwc->regs, DWC3_GEVNTSIZ(0), reg);
3295 
3296         amount = min(count, evt->length - evt->lpos);
3297         memcpy(evt->cache + evt->lpos, evt->buf + evt->lpos, amount);
3298 
3299         if (amount < count)
3300                 memcpy(evt->cache, evt->buf, count - amount);
3301 
3302         dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(0), count);
3303 
3304         return IRQ_WAKE_THREAD;
3305 }
3306 
3307 static irqreturn_t dwc3_interrupt(int irq, void *_evt)
3308 {
3309         struct dwc3_event_buffer        *evt = _evt;
3310 
3311         return dwc3_check_event_buf(evt);
3312 }
3313 
3314 static int dwc3_gadget_get_irq(struct dwc3 *dwc)
3315 {
3316         struct platform_device *dwc3_pdev = to_platform_device(dwc->dev);
3317         int irq;
3318 
3319         irq = platform_get_irq_byname_optional(dwc3_pdev, "peripheral");
3320         if (irq > 0)
3321                 goto out;
3322 
3323         if (irq == -EPROBE_DEFER)
3324                 goto out;
3325 
3326         irq = platform_get_irq_byname_optional(dwc3_pdev, "dwc_usb3");
3327         if (irq > 0)
3328                 goto out;
3329 
3330         if (irq == -EPROBE_DEFER)
3331                 goto out;
3332 
3333         irq = platform_get_irq(dwc3_pdev, 0);
3334         if (irq > 0)
3335                 goto out;
3336 
3337         if (!irq)
3338                 irq = -EINVAL;
3339 
3340 out:
3341         return irq;
3342 }
3343 
3344 /**
3345  * dwc3_gadget_init - initializes gadget related registers
3346  * @dwc: pointer to our controller context structure
3347  *
3348  * Returns 0 on success otherwise negative errno.
3349  */
3350 int dwc3_gadget_init(struct dwc3 *dwc)
3351 {
3352         int ret;
3353         int irq;
3354 
3355         irq = dwc3_gadget_get_irq(dwc);
3356         if (irq < 0) {
3357                 ret = irq;
3358                 goto err0;
3359         }
3360 
3361         dwc->irq_gadget = irq;
3362 
3363         dwc->ep0_trb = dma_alloc_coherent(dwc->sysdev,
3364                                           sizeof(*dwc->ep0_trb) * 2,
3365                                           &dwc->ep0_trb_addr, GFP_KERNEL);
3366         if (!dwc->ep0_trb) {
3367                 dev_err(dwc->dev, "failed to allocate ep0 trb\n");
3368                 ret = -ENOMEM;
3369                 goto err0;
3370         }
3371 
3372         dwc->setup_buf = kzalloc(DWC3_EP0_SETUP_SIZE, GFP_KERNEL);
3373         if (!dwc->setup_buf) {
3374                 ret = -ENOMEM;
3375                 goto err1;
3376         }
3377 
3378         dwc->bounce = dma_alloc_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE,
3379                         &dwc->bounce_addr, GFP_KERNEL);
3380         if (!dwc->bounce) {
3381                 ret = -ENOMEM;
3382                 goto err2;
3383         }
3384 
3385         init_completion(&dwc->ep0_in_setup);
3386 
3387         dwc->gadget.ops                 = &dwc3_gadget_ops;
3388         dwc->gadget.speed               = USB_SPEED_UNKNOWN;
3389         dwc->gadget.sg_supported        = true;
3390         dwc->gadget.name                = "dwc3-gadget";
3391         dwc->gadget.lpm_capable         = true;
3392 
3393         /*
3394          * FIXME We might be setting max_speed to <SUPER, however versions
3395          * <2.20a of dwc3 have an issue with metastability (documented
3396          * elsewhere in this driver) which tells us we can't set max speed to
3397          * anything lower than SUPER.
3398          *
3399          * Because gadget.max_speed is only used by composite.c and function
3400          * drivers (i.e. it won't go into dwc3's registers) we are allowing this
3401          * to happen so we avoid sending SuperSpeed Capability descriptor
3402          * together with our BOS descriptor as that could confuse host into
3403          * thinking we can handle super speed.
3404          *
3405          * Note that, in fact, we won't even support GetBOS requests when speed
3406          * is less than super speed because we don't have means, yet, to tell
3407          * composite.c that we are USB 2.0 + LPM ECN.
3408          */
3409         if (dwc->revision < DWC3_REVISION_220A &&
3410             !dwc->dis_metastability_quirk)
3411                 dev_info(dwc->dev, "changing max_speed on rev %08x\n",
3412                                 dwc->revision);
3413 
3414         dwc->gadget.max_speed           = dwc->maximum_speed;
3415 
3416         /*
3417          * REVISIT: Here we should clear all pending IRQs to be
3418          * sure we're starting from a well known location.
3419          */
3420 
3421         ret = dwc3_gadget_init_endpoints(dwc, dwc->num_eps);
3422         if (ret)
3423                 goto err3;
3424 
3425         ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
3426         if (ret) {
3427                 dev_err(dwc->dev, "failed to register udc\n");
3428                 goto err4;
3429         }
3430 
3431         dwc3_gadget_set_speed(&dwc->gadget, dwc->maximum_speed);
3432 
3433         return 0;
3434 
3435 err4:
3436         dwc3_gadget_free_endpoints(dwc);
3437 
3438 err3:
3439         dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3440                         dwc->bounce_addr);
3441 
3442 err2:
3443         kfree(dwc->setup_buf);
3444 
3445 err1:
3446         dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3447                         dwc->ep0_trb, dwc->ep0_trb_addr);
3448 
3449 err0:
3450         return ret;
3451 }
3452 
3453 /* -------------------------------------------------------------------------- */
3454 
3455 void dwc3_gadget_exit(struct dwc3 *dwc)
3456 {
3457         usb_del_gadget_udc(&dwc->gadget);
3458         dwc3_gadget_free_endpoints(dwc);
3459         dma_free_coherent(dwc->sysdev, DWC3_BOUNCE_SIZE, dwc->bounce,
3460                           dwc->bounce_addr);
3461         kfree(dwc->setup_buf);
3462         dma_free_coherent(dwc->sysdev, sizeof(*dwc->ep0_trb) * 2,
3463                           dwc->ep0_trb, dwc->ep0_trb_addr);
3464 }
3465 
3466 int dwc3_gadget_suspend(struct dwc3 *dwc)
3467 {
3468         if (!dwc->gadget_driver)
3469                 return 0;
3470 
3471         dwc3_gadget_run_stop(dwc, false, false);
3472         dwc3_disconnect_gadget(dwc);
3473         __dwc3_gadget_stop(dwc);
3474 
3475         return 0;
3476 }
3477 
3478 int dwc3_gadget_resume(struct dwc3 *dwc)
3479 {
3480         int                     ret;
3481 
3482         if (!dwc->gadget_driver)
3483                 return 0;
3484 
3485         ret = __dwc3_gadget_start(dwc);
3486         if (ret < 0)
3487                 goto err0;
3488 
3489         ret = dwc3_gadget_run_stop(dwc, true, false);
3490         if (ret < 0)
3491                 goto err1;
3492 
3493         return 0;
3494 
3495 err1:
3496         __dwc3_gadget_stop(dwc);
3497 
3498 err0:
3499         return ret;
3500 }
3501 
3502 void dwc3_gadget_process_pending_events(struct dwc3 *dwc)
3503 {
3504         if (dwc->pending_events) {
3505                 dwc3_interrupt(dwc->irq_gadget, dwc->ev_buf);
3506                 dwc->pending_events = false;
3507                 enable_irq(dwc->irq_gadget);
3508         }
3509 }

/* [<][>][^][v][top][bottom][index][help] */