/* * usb/usb.c -- USB 2.0 implementation * * Copyright (C) 2016-2017 Tomasz Kramkowski * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include "../uart/uart.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) */ __attribute__ ((aligned(512))) volatile struct usb0_bd usb_bdt[2][2][2]; /* 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); USB0_INTEN = BV(INTEN_STALLEN) | BV(INTEN_ERROREN) | BV(INTEN_USBRSTEN); /* NVIC Enable interrupt */ ISR_CLRPEND(73); ISR_SETENA(73); INTPRI(73) = 0x00; /* 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 (GET_BIT(stat, ISTAT_STALL)) { uart_puts("INT: stall"); USB0_ISTAT = BV(ISTAT_STALL); } if (GET_BIT(stat, ISTAT_TOKDNE)) { i_tokdne(); USB0_ISTAT = BV(ISTAT_TOKDNE); } if (GET_BIT(stat, ISTAT_ERROR)) { uart_printf("INT: error (0x%x)\n", (unsigned)USB0_ERRSTAT); USB0_ERRSTAT = USB0_ERRSTAT; USB0_ISTAT = BV(ISTAT_ERROR); } if (GET_BIT(stat, ISTAT_USBRST)) { i_usbrst(); USB0_ISTAT = BV(ISTAT_USBRST); } }