2 * main.c - main routine of neug
5 * Copyright (C) 2011, 2012 Free Software Initiative of Japan
6 * Author: NIIBE Yutaka <gniibe@fsij.org>
8 * This file is a part of NeuG, a Random Number Generator
11 * NeuG is free software: you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * Gnuk is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
19 * License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35 * We are trying to avoid dependency to C library.
36 * GCC built-in function(s) are declared here.
38 extern void *memcpy(void *dest, const void *src, size_t n);
39 extern void *memset (void *s, int c, size_t n);
41 static Thread *main_thread = NULL;
44 #define ENDP0_RXADDR (0x40)
45 #define ENDP0_TXADDR (0x80)
46 #define ENDP1_TXADDR (0xc0)
47 #define ENDP2_TXADDR (0x100)
48 #define ENDP3_RXADDR (0x140)
50 #define USB_CDC_REQ_SET_LINE_CODING 0x20
51 #define USB_CDC_REQ_GET_LINE_CODING 0x21
52 #define USB_CDC_REQ_SET_CONTROL_LINE_STATE 0x22
53 #define USB_CDC_REQ_SEND_BREAK 0x23
55 /* USB Device Descriptor */
56 static const uint8_t vcom_device_desc[18] = {
58 USB_DEVICE_DESCRIPTOR_TYPE, /* bDescriptorType */
59 0x10, 0x01, /* bcdUSB = 1.1 */
60 0x02, /* bDeviceClass (CDC). */
61 0x00, /* bDeviceSubClass. */
62 0x00, /* bDeviceProtocol. */
63 0x40, /* bMaxPacketSize. */
64 #include "usb-vid-pid-ver.c.inc"
65 1, /* iManufacturer. */
67 3, /* iSerialNumber. */
68 1 /* bNumConfigurations. */
71 /* Configuration Descriptor tree for a CDC.*/
72 static const uint8_t vcom_configuration_desc[67] = {
74 USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType: Configuration */
75 /* Configuration Descriptor.*/
76 67, 0x00, /* wTotalLength. */
77 0x02, /* bNumInterfaces. */
78 0x01, /* bConfigurationValue. */
79 0, /* iConfiguration. */
80 0x80, /* bmAttributes (bus powered). */
81 50, /* bMaxPower (100mA). */
82 /* Interface Descriptor.*/
84 USB_INTERFACE_DESCRIPTOR_TYPE,
85 0x00, /* bInterfaceNumber. */
86 0x00, /* bAlternateSetting. */
87 0x01, /* bNumEndpoints. */
88 0x02, /* bInterfaceClass (Communications Interface Class,
90 0x02, /* bInterfaceSubClass (Abstract Control Model, CDC
92 0x01, /* bInterfaceProtocol (AT commands, CDC section
95 /* Header Functional Descriptor (CDC section 5.2.3).*/
97 0x24, /* bDescriptorType (CS_INTERFACE). */
98 0x00, /* bDescriptorSubtype (Header Functional Descriptor). */
99 0x10, 0x01, /* bcdCDC. */
100 /* Call Management Functional Descriptor. */
101 5, /* bFunctionLength. */
102 0x24, /* bDescriptorType (CS_INTERFACE). */
103 0x01, /* bDescriptorSubtype (Call Management Functional
105 0x03, /* bmCapabilities (D0+D1). */
106 0x01, /* bDataInterface. */
107 /* ACM Functional Descriptor.*/
108 4, /* bFunctionLength. */
109 0x24, /* bDescriptorType (CS_INTERFACE). */
110 0x02, /* bDescriptorSubtype (Abstract Control Management
112 0x02, /* bmCapabilities. */
113 /* Union Functional Descriptor.*/
114 5, /* bFunctionLength. */
115 0x24, /* bDescriptorType (CS_INTERFACE). */
116 0x06, /* bDescriptorSubtype (Union Functional
118 0x00, /* bMasterInterface (Communication Class
120 0x01, /* bSlaveInterface0 (Data Class Interface). */
121 /* Endpoint 2 Descriptor.*/
123 USB_ENDPOINT_DESCRIPTOR_TYPE,
124 ENDP2|0x80, /* bEndpointAddress. */
125 0x03, /* bmAttributes (Interrupt). */
126 0x08, 0x00, /* wMaxPacketSize. */
127 0xFF, /* bInterval. */
128 /* Interface Descriptor.*/
130 USB_INTERFACE_DESCRIPTOR_TYPE, /* bDescriptorType: */
131 0x01, /* bInterfaceNumber. */
132 0x00, /* bAlternateSetting. */
133 0x02, /* bNumEndpoints. */
134 0x0A, /* bInterfaceClass (Data Class Interface, CDC section 4.5). */
135 0x00, /* bInterfaceSubClass (CDC section 4.6). */
136 0x00, /* bInterfaceProtocol (CDC section 4.7). */
137 0x00, /* iInterface. */
138 /* Endpoint 3 Descriptor.*/
140 USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType: Endpoint */
141 ENDP3, /* bEndpointAddress. */
142 0x02, /* bmAttributes (Bulk). */
143 0x40, 0x00, /* wMaxPacketSize. */
144 0x00, /* bInterval. */
145 /* Endpoint 1 Descriptor.*/
147 USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType: Endpoint */
148 ENDP1|0x80, /* bEndpointAddress. */
149 0x02, /* bmAttributes (Bulk). */
150 0x40, 0x00, /* wMaxPacketSize. */
151 0x00 /* bInterval. */
156 * U.S. English language identifier.
158 static const uint8_t vcom_string0[4] = {
160 USB_STRING_DESCRIPTOR_TYPE,
161 0x09, 0x04 /* LangID = 0x0409: US-English */
164 #define USB_STRINGS_FOR_NEUG 1
165 #include "usb-strings.c.inc"
168 * Serial Number string. NOTE: This does not have CONST qualifier.
170 static uint8_t vcom_string3[28] = {
172 USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType. */
173 '0', 0, '.', 0, '0', 0, '2', 0, /* Version number of NeuG. */
175 0, 0, 0, 0, /* Filled by Unique device ID. */
181 static const struct Descriptor device_desc = {
183 sizeof (vcom_device_desc)
186 static const struct Descriptor config_desc = {
187 vcom_configuration_desc,
188 sizeof (vcom_configuration_desc)
191 static const struct Descriptor string_descs[] = {
192 {vcom_string0, sizeof vcom_string0},
193 {neug_string_vendor, sizeof (neug_string_vendor)},
194 {neug_string_product, sizeof (neug_string_product)},
195 {vcom_string3, sizeof (vcom_string3)},
196 {neug_revision_detail, sizeof (neug_revision_detail)},
197 {neug_config_options, sizeof (neug_config_options)},
198 {sys_version, sizeof (sys_version)},
201 #define NUM_STRING_DESC (sizeof (string_descs)/sizeof (struct Descriptor))
203 #define NUM_INTERFACES 2
205 uint32_t bDeviceState = UNCONNECTED; /* USB device status */
209 neug_device_reset (void)
211 /* Set DEVICE as not configured */
212 usb_lld_set_configuration (0);
214 /* Current Feature initialization */
215 usb_lld_set_feature (config_desc.Descriptor[7]);
219 /* Initialize Endpoint 0 */
220 usb_lld_setup_endpoint (ENDP0, EP_CONTROL, 0, ENDP0_RXADDR, ENDP0_TXADDR, 64);
223 extern uint8_t _regnual_start, __heap_end__;
225 static const uint8_t *const mem_info[] = { &_regnual_start, &__heap_end__, };
227 #define USB_FSIJ_MEMINFO 0
228 #define USB_FSIJ_DOWNLOAD 1
229 #define USB_FSIJ_EXEC 2
230 #define USB_NEUG_EXIT 255 /* exit and receive reGNUal */
233 FSIJ_DEVICE_RUNNING = 0,
235 FSIJ_DEVICE_EXEC_REQUESTED,
237 FSIJ_DEVICE_NEUG_EXIT_REQUESTED = 255
240 static uint8_t fsij_device_state = FSIJ_DEVICE_RUNNING;
242 static uint32_t rbit (uint32_t v)
246 asm ("rbit %0, %1" : "=r" (r) : "r" (v));
250 /* After calling this function, CRC module remain enabled. */
251 static int download_check_crc32 (const uint32_t *end_p)
253 uint32_t crc32 = *end_p;
256 RCC->AHBENR |= RCC_AHBENR_CRCEN;
257 CRC->CR = CRC_CR_RESET;
259 for (p = (const uint32_t *)&_regnual_start; p < end_p; p++)
262 if ((rbit (CRC->DR) ^ crc32) == 0xffffffff)
265 return USB_UNSUPPORT;
268 static void neug_ctrl_write_finish (uint8_t req, uint8_t req_no,
269 uint16_t value, uint16_t index,
272 uint8_t type_rcp = req & (REQUEST_TYPE|RECIPIENT);
274 if (type_rcp == (VENDOR_REQUEST | DEVICE_RECIPIENT)
275 && USB_SETUP_SET (req) && req_no == USB_FSIJ_EXEC && len == 0)
277 if (fsij_device_state != FSIJ_DEVICE_EXITED)
280 (void)value; (void)index;
281 usb_lld_prepare_shutdown (); /* No further USB communication */
282 fsij_device_state = FSIJ_DEVICE_EXEC_REQUESTED;
294 static struct line_coding line_coding = {
295 115200, /* baud rate: 115200 */
296 0x00, /* stop bits: 1 */
297 0x00, /* parity: none */
301 static uint8_t connected;
304 vcom_port_data_setup (uint8_t req, uint8_t req_no, uint16_t value)
306 if (USB_SETUP_GET (req))
308 if (req_no == USB_CDC_REQ_GET_LINE_CODING)
310 usb_lld_set_data_to_send (&line_coding, sizeof(line_coding));
314 else /* USB_SETUP_SET (req) */
316 if (req_no == USB_CDC_REQ_SET_LINE_CODING)
318 usb_lld_set_data_to_recv (&line_coding, sizeof(line_coding));
321 else if (req_no == USB_CDC_REQ_SET_CONTROL_LINE_STATE)
325 if ((connected & 1) == 0)
337 return USB_UNSUPPORT;
341 neug_setup (uint8_t req, uint8_t req_no,
342 uint16_t value, uint16_t index, uint16_t len)
344 uint8_t type_rcp = req & (REQUEST_TYPE|RECIPIENT);
346 if (type_rcp == (VENDOR_REQUEST | DEVICE_RECIPIENT))
348 if (USB_SETUP_GET (req))
350 if (req_no == USB_FSIJ_MEMINFO)
352 usb_lld_set_data_to_send (mem_info, sizeof (mem_info));
358 uint8_t *addr = (uint8_t *)(0x20000000 + value * 0x100 + index);
360 if (req_no == USB_FSIJ_DOWNLOAD)
362 if (fsij_device_state != FSIJ_DEVICE_EXITED)
363 return USB_UNSUPPORT;
365 if (addr < &_regnual_start || addr + len > &__heap_end__)
366 return USB_UNSUPPORT;
368 if (index + len < 256)
369 memset (addr + index + len, 0, 256 - (index + len));
371 usb_lld_set_data_to_recv (addr, len);
374 else if (req_no == USB_FSIJ_EXEC && len == 0)
376 if (fsij_device_state != FSIJ_DEVICE_EXITED)
377 return USB_UNSUPPORT;
379 if (((uint32_t)addr & 0x03))
380 return USB_UNSUPPORT;
382 return download_check_crc32 ((uint32_t *)addr);
384 else if (req_no == USB_NEUG_EXIT && len == 0)
386 if (fsij_device_state != FSIJ_DEVICE_RUNNING)
387 return USB_UNSUPPORT;
389 fsij_device_state = FSIJ_DEVICE_NEUG_EXIT_REQUESTED;
390 chEvtSignalFlagsI (main_thread, 1);
391 chSchReadyI (main_thread);
396 else if (type_rcp == (CLASS_REQUEST | INTERFACE_RECIPIENT))
398 return vcom_port_data_setup (req, req_no, value);
400 return USB_UNSUPPORT;
404 neug_get_descriptor (uint8_t desc_type, uint16_t index, uint16_t value)
407 if (desc_type == DEVICE_DESCRIPTOR)
409 usb_lld_set_data_to_send (device_desc.Descriptor,
410 device_desc.Descriptor_Size);
413 else if (desc_type == CONFIG_DESCRIPTOR)
415 usb_lld_set_data_to_send (config_desc.Descriptor,
416 config_desc.Descriptor_Size);
419 else if (desc_type == STRING_DESCRIPTOR)
421 uint8_t desc_index = value & 0xff;
423 if (desc_index < NUM_STRING_DESC)
425 usb_lld_set_data_to_send (string_descs[desc_index].Descriptor,
426 string_descs[desc_index].Descriptor_Size);
431 return USB_UNSUPPORT;
435 neug_setup_endpoints_for_interface (uint16_t interface, int stop)
440 usb_lld_setup_endpoint (ENDP2, EP_INTERRUPT, 0, 0, ENDP2_TXADDR, 0);
442 usb_lld_stall_tx (ENDP2);
444 else if (interface == 1)
448 usb_lld_setup_endpoint (ENDP1, EP_BULK, 0, 0, ENDP1_TXADDR, 0);
449 usb_lld_setup_endpoint (ENDP3, EP_BULK, 0, ENDP3_RXADDR, 0, 64);
453 usb_lld_stall_tx (ENDP1);
454 usb_lld_stall_rx (ENDP3);
459 static int neug_usb_event (uint8_t event_type, uint16_t value)
462 uint8_t current_conf;
466 case USB_EVENT_ADDRESS:
467 bDeviceState = ADDRESSED;
469 case USB_EVENT_CONFIG:
470 current_conf = usb_lld_current_configuration ();
471 if (current_conf == 0)
474 return USB_UNSUPPORT;
476 usb_lld_set_configuration (1);
477 for (i = 0; i < NUM_INTERFACES; i++)
478 neug_setup_endpoints_for_interface (i, 0);
479 bDeviceState = CONFIGURED;
481 else if (current_conf != value)
484 return USB_UNSUPPORT;
486 usb_lld_set_configuration (0);
487 for (i = 0; i < NUM_INTERFACES; i++)
488 neug_setup_endpoints_for_interface (i, 1);
489 bDeviceState = ADDRESSED;
491 /* Do nothing when current_conf == value */
499 return USB_UNSUPPORT;
503 static int neug_interface (uint8_t cmd, uint16_t interface, uint16_t alt)
505 static uint8_t zero = 0;
507 if (interface >= NUM_INTERFACES)
508 return USB_UNSUPPORT;
512 case USB_SET_INTERFACE:
514 return USB_UNSUPPORT;
517 neug_setup_endpoints_for_interface (interface, 0);
521 case USB_GET_INTERFACE:
522 usb_lld_set_data_to_send (&zero, 1);
526 case USB_QUERY_INTERFACE:
531 const struct usb_device_method Device_Method = {
533 neug_ctrl_write_finish,
542 static void fill_serial_no_by_unique_id (void)
544 extern const uint8_t * unique_device_id (void);
545 uint8_t *p = &vcom_string3[12];
546 const uint8_t *u = unique_device_id ();
549 for (i = 0; i < 4; i++)
555 nibble += (nibble >= 10 ? ('A' - 10) : '0');
558 nibble += (nibble >= 10 ? ('A' - 10) : '0');
563 CH_IRQ_HANDLER (Vector90)
568 usb_interrupt_handler ();
570 chSysUnlockFromIsr();
575 EP1_IN_Callback (void)
577 if (main_thread != NULL)
580 main_thread->p_u.rdymsg = RDY_OK;
581 chSchReadyI (main_thread);
582 chSysUnlockFromIsr ();
587 EP2_IN_Callback (void)
592 EP3_OUT_Callback (void)
594 usb_lld_rx_enable (ENDP3);
597 static WORKING_AREA(wa_led, 64);
599 #define LED_ONESHOT_SHORT ((eventmask_t)1)
600 #define LED_ONESHOT_LONG ((eventmask_t)2)
601 static Thread *led_thread;
604 * LED blinker: When notified, let LED emit for 100ms.
606 static msg_t led_blinker (void *arg)
610 led_thread = chThdSelf ();
617 m = chEvtWaitOne (ALL_EVENTS);
618 if (fsij_device_state != FSIJ_DEVICE_RUNNING)
622 if (m == LED_ONESHOT_SHORT)
623 chThdSleep (MS2ST (100));
625 chThdSleep (MS2ST (250));
632 #define RANDOM_BYTES_LENGTH 60
633 static uint32_t random_word[RANDOM_BYTES_LENGTH/sizeof (uint32_t)];
638 * NOTE: the main function is already a thread in the system on entry.
641 main (int argc, char **argv)
646 fill_serial_no_by_unique_id ();
651 main_thread = chThdSelf ();
653 usb_lld_init (config_desc.Descriptor[7]);
655 chThdCreateStatic (wa_led, sizeof (wa_led), NORMALPRIO, led_blinker, NULL);
657 neug_init (random_word, RANDOM_BYTES_LENGTH/sizeof (uint32_t));
661 unsigned int count = 0;
663 if (fsij_device_state != FSIJ_DEVICE_RUNNING)
667 while (count < NEUG_PRE_LOOP || bDeviceState != CONFIGURED)
669 if (fsij_device_state != FSIJ_DEVICE_RUNNING)
672 (void)neug_get (NEUG_KICK_FILLING);
673 if ((count & 0x000f) == 0)
674 chEvtSignalFlags (led_thread, LED_ONESHOT_SHORT);
675 chEvtWaitOneTimeout (ALL_EVENTS, MS2ST (25));
680 while ((connected & 1) == 0)
682 if (fsij_device_state != FSIJ_DEVICE_RUNNING)
686 chEvtSignalFlags (led_thread, LED_ONESHOT_LONG);
687 chEvtWaitOneTimeout (ALL_EVENTS, MS2ST (2500));
690 /* The connection opened. */
695 if (fsij_device_state != FSIJ_DEVICE_RUNNING)
698 if ((connected & 1) == 0)
699 goto waiting_connection;
701 if (bDeviceState != CONFIGURED)
706 if ((count & 0x00ff) == 0)
707 chEvtSignalFlags (led_thread, LED_ONESHOT_SHORT);
709 usb_lld_txcpy (random_word, ENDP1, 0, RANDOM_BYTES_LENGTH);
713 usb_lld_tx_enable (ENDP1, RANDOM_BYTES_LENGTH);
714 chSchGoSleepS (THD_STATE_SUSPENDED);
722 * We come here, because of FSIJ_DEVICE_NEUG_EXIT_REQUESTED.
726 chEvtSignalFlags (led_thread, LED_ONESHOT_SHORT);
727 chThdWait (led_thread);
729 fsij_device_state = FSIJ_DEVICE_EXITED;
731 while (fsij_device_state == FSIJ_DEVICE_EXITED)
732 chThdSleep (MS2ST (500));
734 flash_unlock (); /* Flash unlock should be done here */
737 /* Disable SysTick */
739 /* Disable all interrupts */
742 SCB->VTOR = (uint32_t)&_regnual_start;
744 #define FLASH_SYS_START_ADDR 0x08000000
745 #define FLASH_SYS_END_ADDR (0x08000000+0x1000)
749 handler *new_vector = (handler *)FLASH_SYS_START_ADDR;
750 void (*func) (void (*)(void)) = (void (*)(void (*)(void)))new_vector[10];
753 for (addr = FLASH_SYS_START_ADDR; addr < FLASH_SYS_END_ADDR;
754 addr += FLASH_PAGE_SIZE)
755 flash_erase_page (addr);
757 /* copy system service routines */
758 flash_write (FLASH_SYS_START_ADDR, &_sys, 0x1000);
760 /* Leave NeuG to exec reGNUal */
761 (*func) (*((void (**)(void))(&_regnual_start+4)));
765 /* Leave NeuG to exec reGNUal */
766 flash_erase_all_and_exec (*((void (**)(void))(&_regnual_start+4)));