aboutsummaryrefslogtreecommitdiffstats
path: root/libmaple/usb/usb.c
blob: ec189d678ed4ff90bee1b082f8643fa6f002cfd7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/******************************************************************************
 * The MIT License
 *
 * Copyright (c) 2010 LeafLabs LLC.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *****************************************************************************/

/**
 * @file usb.c
 * @brief USB support.
 */

#include "usb.h"

#include "libmaple.h"
#include "gpio.h"
#include "delay.h"
#include "nvic.h"
#include "rcc.h"

#include "usb_reg_map.h"
#include "usb_lib_globals.h"

#include "usb_type.h"
#include "usb_core.h"

static void dispatch_ctr_lp(void);

/*
 * usb_lib/ globals
 */

uint16 SaveTState;              /* caches TX status for later use */
uint16 SaveRState;              /* caches RX status for later use */

/*
 * Other state
 */

struct {
  volatile RESUME_STATE eState;
  volatile uint8 bESOFcnt;
} ResumeS;

static usblib_dev usblib = {
    .irq_mask = USB_ISR_MSK,
    .state = USB_UNCONNECTED,
};
usblib_dev *USBLIB = &usblib;

/*
 * Routines
 */

void usb_init_usblib(void (**ep_int_in)(void), void (**ep_int_out)(void)) {
    rcc_clk_enable(RCC_USB);

    USBLIB->ep_int_in = ep_int_in;
    USBLIB->ep_int_out = ep_int_out;

    /* usb_lib/ declares both and then assumes that pFoo points to Foo
     * (even though the names don't always match), which is stupid for
     * all of the obvious reasons, but whatever.  Here we are. */
    pInformation = &Device_Info;
    pProperty = &Device_Property;
    pUser_Standard_Requests = &User_Standard_Requests;

    pInformation->ControlState = 2; /* FIXME [0.0.12] use
                                       CONTROL_STATE enumerator */
    pProperty->Init();
}

void usbSuspend(void) {
  uint16 cntr;

  /* TODO decide if read/modify/write is really what we want
   * (e.g. usbResumeInit() reconfigures CNTR). */
  cntr = USB_BASE->CNTR;
  cntr |= USB_CNTR_FSUSP;
  USB_BASE->CNTR = cntr;
  cntr |= USB_CNTR_LP_MODE;
  USB_BASE->CNTR = cntr;

  USBLIB->state = USB_SUSPENDED;
}

void usbResumeInit(void) {
  uint16 cntr;

  cntr = USB_BASE->CNTR;
  cntr &= ~USB_CNTR_LP_MODE;
  USB_BASE->CNTR = cntr;

  /* Enable interrupt lines */
  USB_BASE->CNTR = USB_ISR_MSK;
}

void usbResume(RESUME_STATE eResumeSetVal) {
  uint16 cntr;

  if (eResumeSetVal != RESUME_ESOF)
    ResumeS.eState = eResumeSetVal;

  switch (ResumeS.eState)
    {
    case RESUME_EXTERNAL:
      usbResumeInit();
      ResumeS.eState = RESUME_OFF;
      break;
    case RESUME_INTERNAL:
      usbResumeInit();
      ResumeS.eState = RESUME_START;
      break;
    case RESUME_LATER:
      ResumeS.bESOFcnt = 2;
      ResumeS.eState = RESUME_WAIT;
      break;
    case RESUME_WAIT:
      ResumeS.bESOFcnt--;
      if (ResumeS.bESOFcnt == 0)
        ResumeS.eState = RESUME_START;
      break;
    case RESUME_START:
      cntr = USB_BASE->CNTR;
      cntr |= USB_CNTR_RESUME;
      USB_BASE->CNTR = cntr;
      ResumeS.eState = RESUME_ON;
      ResumeS.bESOFcnt = 10;
      break;
    case RESUME_ON:
      ResumeS.bESOFcnt--;
      if (ResumeS.bESOFcnt == 0) {
          cntr = USB_BASE->CNTR;
          cntr &= ~USB_CNTR_RESUME;
          USB_BASE->CNTR = cntr;
          ResumeS.eState = RESUME_OFF;
      }
      break;
    case RESUME_OFF:
    case RESUME_ESOF:
    default:
      ResumeS.eState = RESUME_OFF;
      break;
    }
}

#define SUSPEND_ENABLED 1
void __irq_usb_lp_can_rx0(void) {
  uint16 istr = USB_BASE->ISTR;

  /* Use USB_ISR_MSK to only include code for bits we care about. */

#if (USB_ISR_MSK & USB_ISTR_RESET)
  if (istr & USB_ISTR_RESET & USBLIB->irq_mask) {
    USB_BASE->ISTR = ~USB_ISTR_RESET;
    pProperty->Reset();
  }
#endif

#if (USB_ISR_MSK & USB_ISTR_PMAOVR)
  if (istr & ISTR_PMAOVR & USBLIB->irq_mask) {
    USB_BASE->ISTR = ~USB_ISTR_PMAOVR;
  }
#endif

#if (USB_ISR_MSK & USB_ISTR_ERR)
  if (istr & USB_ISTR_ERR & USBLIB->irq_mask) {
    USB_BASE->ISTR = ~USB_ISTR_ERR;
  }
#endif

#if (USB_ISR_MSK & USB_ISTR_WKUP)
  if (istr & USB_ISTR_WKUP & USBLIB->irq_mask) {
    USB_BASE->ISTR = ~USB_ISTR_WKUP;
    usbResume(RESUME_EXTERNAL);
  }
#endif

#if (USB_ISR_MSK & USB_ISTR_SUSP)
  if (istr & USB_ISTR_SUSP & USBLIB->irq_mask) {
    /* check if SUSPEND is possible */
    if (SUSPEND_ENABLED) {
        usbSuspend();
    } else {
        /* if not possible then resume after xx ms */
        usbResume(RESUME_LATER);
    }
    /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */
    USB_BASE->ISTR = ~USB_ISTR_SUSP;
}
#endif

#if (USB_ISR_MSK & USB_ISTR_SOF)
  if (istr & USB_ISTR_SOF & USBLIB->irq_mask) {
    USB_BASE->ISTR = ~USB_ISTR_SOF;
  }
#endif

#if (USB_ISR_MSK & USB_ISTR_ESOF)
  if (istr & USB_ISTR_ESOF & USBLIB->irq_mask) {
    USB_BASE->ISTR = ~USB_ISTR_ESOF;
    /* resume handling timing is made with ESOFs */
    usbResume(RESUME_ESOF); /* request without change of the machine state */
  }
#endif

  /*
   * Service the correct transfer interrupt.
   */

#if (USB_ISR_MSK & USB_ISTR_CTR)
  if (istr & USB_ISTR_CTR & USBLIB->irq_mask) {
    dispatch_ctr_lp();
  }
#endif
}

#define RESET_DELAY                     100000
void usbWaitReset(void) {
  delay_us(RESET_DELAY);
  nvic_sys_reset();
}

uint8 usbIsConfigured() {
  return USBLIB->state == USB_CONFIGURED;
}

uint8 usbIsConnected() {
  return USBLIB->state != USB_UNCONNECTED;
}

/*
 * Auxiliary routines
 */

static inline uint8 dispatch_endpt_zero(uint16 istr_dir);
static inline void dispatch_endpt(uint8 ep);
static inline void set_rx_tx_status0(uint16 rx, uint16 tx);

static void handle_setup0(void);
static void handle_in0(void);
static void handle_out0(void);

static void dispatch_ctr_lp() {
    uint16 istr;
    while (((istr = USB_BASE->ISTR) & USB_ISTR_CTR) != 0) {
        /* TODO WTF, figure this out: RM0008 says CTR is read-only,
         * but ST's firmware claims it's clear-only, and emphasizes
         * the importance of clearing it in more than one place. */
        USB_BASE->ISTR = ~USB_ISTR_CTR;
        uint8 ep_id = istr & USB_ISTR_EP_ID;
        if (ep_id == 0) {
            /* TODO figure out why it's OK to break out of the loop
             * once we're done serving endpoint zero, but not okay if
             * there are multiple nonzero endpoint transfers to
             * handle. */
            if (dispatch_endpt_zero(istr & USB_ISTR_DIR))
                return;
        } else {
            dispatch_endpt(ep_id);
        }
    }
}

/* FIXME Dataflow on endpoint 0 RX/TX status is based off of ST's
 * code, and is ugly/confusing in its use of SaveRState/SaveTState.
 * Fixing this requires filling in handle_in0(), handle_setup0(),
 * handle_out0(). */
static inline uint8 dispatch_endpt_zero(uint16 istr_dir) {
    uint32 epr = (uint16)USB_BASE->EP[0];

    if (!(epr & (USB_EP_CTR_TX | USB_EP_SETUP | USB_EP_CTR_RX))) {
        return 0;
    }

    /* Cache RX/TX statuses in SaveRState/SaveTState, respectively.
     * The various handle_foo0() may clobber these values
     * before we reset them at the end of this routine. */
    SaveRState = epr & USB_EP_STAT_RX;
    SaveTState = epr & USB_EP_STAT_TX;

    /* Set actual RX/TX statuses to NAK while we're thinking */
    set_rx_tx_status0(USB_EP_STAT_RX_NAK, USB_EP_STAT_TX_NAK);

    if (istr_dir == 0) {
        /* ST RM0008: "If DIR bit=0, CTR_TX bit is set in the USB_EPnR
         * register related to the interrupting endpoint.  The
         * interrupting transaction is of IN type (data transmitted by
         * the USB peripheral to the host PC)." */
        ASSERT_FAULT(epr & USB_EP_CTR_TX);
        usb_clear_ctr_tx(USB_EP0);
        handle_in0();
    } else {
        /* RM0008: "If DIR bit=1, CTR_RX bit or both CTR_TX/CTR_RX
         * are set in the USB_EPnR register related to the
         * interrupting endpoint. The interrupting transaction is of
         * OUT type (data received by the USB peripheral from the host
         * PC) or two pending transactions are waiting to be
         * processed."
         *
         * [mbolivar] Note how the following control flow (which
         * replicates ST's) doesn't seem to actually handle both
         * interrupts that are ostensibly pending when both CTR_RX and
         * CTR_TX are set.
         *
         * TODO sort this mess out.
         */
        if (epr & USB_EP_CTR_TX) {
            usb_clear_ctr_tx(USB_EP0);
            handle_in0();
        } else {                /* SETUP or CTR_RX */
            /* SETUP is held constant while CTR_RX is set, so clear it
             * either way */
            usb_clear_ctr_rx(USB_EP0);
            if (epr & USB_EP_SETUP) {
                handle_setup0();
            } else {            /* CTR_RX */
                handle_out0();
            }
        }
    }

    set_rx_tx_status0(SaveRState, SaveTState);
    return 1;
}

static inline void dispatch_endpt(uint8 ep) {
    uint32 epr = USB_BASE->EP[ep];
    /* If ISTR_CTR is set and the ISTR gave us this EP_ID to handle,
     * then presumably at least one of CTR_RX and CTR_TX is set, but
     * again, ST's control flow allows for the possibility of neither.
     *
     * TODO try to find out if neither being set is possible. */
    if (epr & USB_EP_CTR_RX) {
        usb_clear_ctr_rx(ep);
        (USBLIB->ep_int_out[ep - 1])();
    }
    if (epr & USB_EP_CTR_TX) {
        usb_clear_ctr_tx(ep);
        (USBLIB->ep_int_in[ep - 1])();
    }
}

static inline void set_rx_tx_status0(uint16 rx, uint16 tx) {
    usb_set_ep_rx_stat(USB_EP0, rx);
    usb_set_ep_tx_stat(USB_EP0, tx);
}

/* TODO Rip out usb_lib/ dependency from the following functions: */

static void handle_setup0(void) {
    Setup0_Process();
}

static void handle_in0(void) {
    In0_Process();
}

static void handle_out0(void) {
    Out0_Process();
}