diff options
Diffstat (limited to 'usb/usb.c')
-rw-r--r-- | usb/usb.c | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/usb/usb.c b/usb/usb.c new file mode 100644 index 0000000..ebd3179 --- /dev/null +++ b/usb/usb.c @@ -0,0 +1,94 @@ +#include <reg/sim.h> +#include <reg/usbotg.h> +#include <reg/gpio.h> +#include <stddef.h> + +#include "usb.h" +#include "bdt.h" +#include "endpt0.h" +#include "endpt1.h" + +#define USBFRAC_VAL 1 /* 72 MHz * 2 = 144 MHz (Top of Fraction) */ +#define USBDIV_VAL 2 /* 144 MHz / 3 = 48 MHz (Bottom of Fraction) */ + +/* TODO: Move this to lib somewhere */ +#define CLRPEND(n) REG_32(0xE000E280 + 4 * (n)) +#define ISR_CLRPEND(i) CLRPEND((i) / 32) = BV((i) % 32); + +#define SETENA(n) REG_32(0xE000E100 + 4 * (n)) +#define ISR_SETENA(i) SETENA((i) / 32) = BV((i) % 32); + + +__attribute__ ((aligned(512))) +struct usb0_bd usb_bdt[16 * 4]; /* TODO: Only use the number of endpoints that are needed */ + +/* usb_setup: Setup function for USB subsystem */ +void usb_setup(void) +{ + /* Clock Setup */ + SET_BIT(SIM_SOPT2, SOPT2_USBSRC); + SET_MASKED(SIM_CLKDIV2, CLKDIV2_USBDIV_M | BV(CLKDIV2_USBFRAC), + USBDIV_VAL << CLKDIV2_USBDIV | USBFRAC_VAL << CLKDIV2_USBFRAC); + SET_BIT(SIM_SCGC4, SCGC4_USBOTG); + + /* Reset USB and wait more than 2 USB clock cycles */ + SET_BIT(USB0_USBTRC0, USBTRC0_USBRESET); + for (int i = 0; i < 5; i++) + ; + + /* 512 bit aligned BDT address */ + USB0_BDTPAGE1 = (uintptr_t)usb_bdt >> 8 & 0xff; + USB0_BDTPAGE2 = (uintptr_t)usb_bdt >> 16 & 0xff; + USB0_BDTPAGE3 = (uintptr_t)usb_bdt >> 24 & 0xff; + + /* Initial Configuration */ + SET_MASKED(USB0_USBCTRL, BV(USBCTRL_SUSP) | BV(USBCTRL_PDE), 0); + SET_BIT(USB0_CONTROL, CONTROL_DPPULLUPNONOTG); + SET_BIT(USB0_INTEN, INTEN_USBRSTEN); + + /* NVIC Enable interrupt */ + ISR_CLRPEND(73); + ISR_SETENA(73); + + /* Enable USB */ + USB0_CTL = BV(CTL_USBENSOFEN); +} + +/* i_usbrst: Handler for USBRST USB interrupt */ +static void i_usbrst(void) +{ + SET_BIT(USB0_CTL, CTL_ODDRST); + + usb_endpt0_enable(); + usb_endpt1_disable(); + + USB0_ADDR = 0; + + SET_BIT(USB0_INTEN, INTEN_TOKDNEEN); +} + +/* i_tokdne: Handler for TOKDNE USB interrupt */ +static void i_tokdne(void) +{ + uint8_t stat = USB0_STAT; + + switch (GET_BITS(stat, STAT_ENDP)) { + case 0: usb_endpt0_token(stat); break; + case 1: usb_endpt1_token(stat); break; + } +} + +/* usb_isr: interrupt service routine for the USB FS SIE */ +void usb_isr(void) +{ + uint8_t stat = USB0_ISTAT; + + if (IS_BIT_SET(stat, ISTAT_TOKDNE)) { + i_tokdne(); + USB0_ISTAT = BV(ISTAT_TOKDNE); + } + if (IS_BIT_SET(stat, ISTAT_USBRST)) { + i_usbrst(); + USB0_ISTAT = BV(ISTAT_USBRST); + } +} |