]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Lib/mk20dx.c
Adding 72 MHz clock support for mk20dx256vlh7
[kiibohd-controller.git] / Lib / mk20dx.c
1 /* Teensyduino Core Library
2  * http://www.pjrc.com/teensy/
3  * Copyright (c) 2013 PJRC.COM, LLC.
4  * Modifications by Jacob Alexander 2014-2015
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * 1. The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * 2. If the Software is incorporated into a build system that allows
18  * selection among a list of target devices, then similar target
19  * devices manufactured by PJRC.COM must be included in the list of
20  * target devices and selectable in the same manner.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
26  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
27  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
28  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29  * SOFTWARE.
30  */
31
32 // ----- Includes -----
33
34 // Local Includes
35 #include "mk20dx.h"
36
37
38
39 // ----- Variables -----
40
41 extern unsigned long _stext;
42 extern unsigned long _etext;
43 extern unsigned long _sdata;
44 extern unsigned long _edata;
45 extern unsigned long _sbss;
46 extern unsigned long _ebss;
47 extern unsigned long _estack;
48
49 const uint8_t sys_reset_to_loader_magic[22] = "\xff\x00\x7fRESET TO LOADER\x7f\x00\xff";
50
51
52
53 // ----- Function Declarations -----
54
55 extern int main();
56 void ResetHandler();
57
58
59
60 // ----- Interrupts -----
61
62 // NVIC - Default ISR
63 void fault_isr()
64 {
65         while ( 1 )
66         {
67                 // keep polling some communication while in fault
68                 // mode, so we don't completely die.
69                 if ( SIM_SCGC4 & SIM_SCGC4_USBOTG ) usb_isr();
70                 if ( SIM_SCGC4 & SIM_SCGC4_UART0 )  uart0_status_isr();
71                 if ( SIM_SCGC4 & SIM_SCGC4_UART1 )  uart1_status_isr();
72                 if ( SIM_SCGC4 & SIM_SCGC4_UART2 )  uart2_status_isr();
73         }
74 }
75
76 void unused_isr()
77 {
78         fault_isr();
79 }
80
81
82 // NVIC - SysTick ISR
83 extern volatile uint32_t systick_millis_count;
84 void systick_default_isr()
85 {
86         systick_millis_count++;
87 }
88
89
90 // NVIC - Default ISR/Vector Linking
91 void nmi_isr()              __attribute__ ((weak, alias("unused_isr")));
92 void hard_fault_isr()       __attribute__ ((weak, alias("unused_isr")));
93 void memmanage_fault_isr()  __attribute__ ((weak, alias("unused_isr")));
94 void bus_fault_isr()        __attribute__ ((weak, alias("unused_isr")));
95 void usage_fault_isr()      __attribute__ ((weak, alias("unused_isr")));
96 void svcall_isr()           __attribute__ ((weak, alias("unused_isr")));
97 void debugmonitor_isr()     __attribute__ ((weak, alias("unused_isr")));
98 void pendablesrvreq_isr()   __attribute__ ((weak, alias("unused_isr")));
99 void systick_isr()          __attribute__ ((weak, alias("systick_default_isr")));
100
101 void dma_ch0_isr()          __attribute__ ((weak, alias("unused_isr")));
102 void dma_ch1_isr()          __attribute__ ((weak, alias("unused_isr")));
103 void dma_ch2_isr()          __attribute__ ((weak, alias("unused_isr")));
104 void dma_ch3_isr()          __attribute__ ((weak, alias("unused_isr")));
105 void dma_ch4_isr()          __attribute__ ((weak, alias("unused_isr")));
106 void dma_ch5_isr()          __attribute__ ((weak, alias("unused_isr")));
107 void dma_ch6_isr()          __attribute__ ((weak, alias("unused_isr")));
108 void dma_ch7_isr()          __attribute__ ((weak, alias("unused_isr")));
109 void dma_ch8_isr()          __attribute__ ((weak, alias("unused_isr")));
110 void dma_ch9_isr()          __attribute__ ((weak, alias("unused_isr")));
111 void dma_ch10_isr()         __attribute__ ((weak, alias("unused_isr")));
112 void dma_ch11_isr()         __attribute__ ((weak, alias("unused_isr")));
113 void dma_ch12_isr()         __attribute__ ((weak, alias("unused_isr")));
114 void dma_ch13_isr()         __attribute__ ((weak, alias("unused_isr")));
115 void dma_ch14_isr()         __attribute__ ((weak, alias("unused_isr")));
116 void dma_ch15_isr()         __attribute__ ((weak, alias("unused_isr")));
117 void dma_error_isr()        __attribute__ ((weak, alias("unused_isr")));
118 void mcm_isr()              __attribute__ ((weak, alias("unused_isr")));
119 void flash_cmd_isr()        __attribute__ ((weak, alias("unused_isr")));
120 void flash_error_isr()      __attribute__ ((weak, alias("unused_isr")));
121 void low_voltage_isr()      __attribute__ ((weak, alias("unused_isr")));
122 void wakeup_isr()           __attribute__ ((weak, alias("unused_isr")));
123 void watchdog_isr()         __attribute__ ((weak, alias("unused_isr")));
124 void i2c0_isr()             __attribute__ ((weak, alias("unused_isr")));
125 void i2c1_isr()             __attribute__ ((weak, alias("unused_isr")));
126 void i2c2_isr()             __attribute__ ((weak, alias("unused_isr")));
127 void spi0_isr()             __attribute__ ((weak, alias("unused_isr")));
128 void spi1_isr()             __attribute__ ((weak, alias("unused_isr")));
129 void spi2_isr()             __attribute__ ((weak, alias("unused_isr")));
130 void sdhc_isr()             __attribute__ ((weak, alias("unused_isr")));
131 void can0_message_isr()     __attribute__ ((weak, alias("unused_isr")));
132 void can0_bus_off_isr()     __attribute__ ((weak, alias("unused_isr")));
133 void can0_error_isr()       __attribute__ ((weak, alias("unused_isr")));
134 void can0_tx_warn_isr()     __attribute__ ((weak, alias("unused_isr")));
135 void can0_rx_warn_isr()     __attribute__ ((weak, alias("unused_isr")));
136 void can0_wakeup_isr()      __attribute__ ((weak, alias("unused_isr")));
137 void i2s0_tx_isr()          __attribute__ ((weak, alias("unused_isr")));
138 void i2s0_rx_isr()          __attribute__ ((weak, alias("unused_isr")));
139 void uart0_lon_isr()        __attribute__ ((weak, alias("unused_isr")));
140 void uart0_status_isr()     __attribute__ ((weak, alias("unused_isr")));
141 void uart0_error_isr()      __attribute__ ((weak, alias("unused_isr")));
142 void uart1_status_isr()     __attribute__ ((weak, alias("unused_isr")));
143 void uart1_error_isr()      __attribute__ ((weak, alias("unused_isr")));
144 void uart2_status_isr()     __attribute__ ((weak, alias("unused_isr")));
145 void uart2_error_isr()      __attribute__ ((weak, alias("unused_isr")));
146 void uart3_status_isr()     __attribute__ ((weak, alias("unused_isr")));
147 void uart3_error_isr()      __attribute__ ((weak, alias("unused_isr")));
148 void uart4_status_isr()     __attribute__ ((weak, alias("unused_isr")));
149 void uart4_error_isr()      __attribute__ ((weak, alias("unused_isr")));
150 void uart5_status_isr()     __attribute__ ((weak, alias("unused_isr")));
151 void uart5_error_isr()      __attribute__ ((weak, alias("unused_isr")));
152 void adc0_isr()             __attribute__ ((weak, alias("unused_isr")));
153 void adc1_isr()             __attribute__ ((weak, alias("unused_isr")));
154 void cmp0_isr()             __attribute__ ((weak, alias("unused_isr")));
155 void cmp1_isr()             __attribute__ ((weak, alias("unused_isr")));
156 void cmp2_isr()             __attribute__ ((weak, alias("unused_isr")));
157 void ftm0_isr()             __attribute__ ((weak, alias("unused_isr")));
158 void ftm1_isr()             __attribute__ ((weak, alias("unused_isr")));
159 void ftm2_isr()             __attribute__ ((weak, alias("unused_isr")));
160 void ftm3_isr()             __attribute__ ((weak, alias("unused_isr")));
161 void cmt_isr()              __attribute__ ((weak, alias("unused_isr")));
162 void rtc_alarm_isr()        __attribute__ ((weak, alias("unused_isr")));
163 void rtc_seconds_isr()      __attribute__ ((weak, alias("unused_isr")));
164 void pit0_isr()             __attribute__ ((weak, alias("unused_isr")));
165 void pit1_isr()             __attribute__ ((weak, alias("unused_isr")));
166 void pit2_isr()             __attribute__ ((weak, alias("unused_isr")));
167 void pit3_isr()             __attribute__ ((weak, alias("unused_isr")));
168 void pdb_isr()              __attribute__ ((weak, alias("unused_isr")));
169 void usb_isr()              __attribute__ ((weak, alias("unused_isr")));
170 void usb_charge_isr()       __attribute__ ((weak, alias("unused_isr")));
171 void dac0_isr()             __attribute__ ((weak, alias("unused_isr")));
172 void dac1_isr()             __attribute__ ((weak, alias("unused_isr")));
173 void tsi0_isr()             __attribute__ ((weak, alias("unused_isr")));
174 void mcg_isr()              __attribute__ ((weak, alias("unused_isr")));
175 void lptmr_isr()            __attribute__ ((weak, alias("unused_isr")));
176 void porta_isr()            __attribute__ ((weak, alias("unused_isr")));
177 void portb_isr()            __attribute__ ((weak, alias("unused_isr")));
178 void portc_isr()            __attribute__ ((weak, alias("unused_isr")));
179 void portd_isr()            __attribute__ ((weak, alias("unused_isr")));
180 void porte_isr()            __attribute__ ((weak, alias("unused_isr")));
181 void software_isr()         __attribute__ ((weak, alias("unused_isr")));
182
183
184 // NVIC - Interrupt Vector Table
185 __attribute__ ((section(".vectors"), used))
186 void (* const gVectors[])() =
187 {
188         (void (*)(void))((unsigned long)&_estack),      //  0 ARM: Initial Stack Pointer
189         ResetHandler,                                   //  1 ARM: Initial Program Counter
190         nmi_isr,                                        //  2 ARM: Non-maskable Interrupt (NMI)
191         hard_fault_isr,                                 //  3 ARM: Hard Fault
192         memmanage_fault_isr,                            //  4 ARM: MemManage Fault
193         bus_fault_isr,                                  //  5 ARM: Bus Fault
194         usage_fault_isr,                                //  6 ARM: Usage Fault
195         fault_isr,                                      //  7 --
196         fault_isr,                                      //  8 --
197         fault_isr,                                      //  9 --
198         fault_isr,                                      // 10 --
199         svcall_isr,                                     // 11 ARM: Supervisor call (SVCall)
200         debugmonitor_isr,                               // 12 ARM: Debug Monitor
201         fault_isr,                                      // 13 --
202         pendablesrvreq_isr,                             // 14 ARM: Pendable req serv(PendableSrvReq)
203         systick_isr,                                    // 15 ARM: System tick timer (SysTick)
204 #if defined(_mk20dx128_) || defined(_mk20dx128vlf5_)
205         dma_ch0_isr,                                    // 16 DMA channel 0 transfer complete
206         dma_ch1_isr,                                    // 17 DMA channel 1 transfer complete
207         dma_ch2_isr,                                    // 18 DMA channel 2 transfer complete
208         dma_ch3_isr,                                    // 19 DMA channel 3 transfer complete
209         dma_error_isr,                                  // 20 DMA error interrupt channel
210         unused_isr,                                     // 21 DMA --
211         flash_cmd_isr,                                  // 22 Flash Memory Command complete
212         flash_error_isr,                                // 23 Flash Read collision
213         low_voltage_isr,                                // 24 Low-voltage detect/warning
214         wakeup_isr,                                     // 25 Low Leakage Wakeup
215         watchdog_isr,                                   // 26 Both EWM and WDOG interrupt
216         i2c0_isr,                                       // 27 I2C0
217         spi0_isr,                                       // 28 SPI0
218         i2s0_tx_isr,                                    // 29 I2S0 Transmit
219         i2s0_rx_isr,                                    // 30 I2S0 Receive
220         uart0_lon_isr,                                  // 31 UART0 CEA709.1-B (LON) status
221         uart0_status_isr,                               // 32 UART0 status
222         uart0_error_isr,                                // 33 UART0 error
223         uart1_status_isr,                               // 34 UART1 status
224         uart1_error_isr,                                // 35 UART1 error
225         uart2_status_isr,                               // 36 UART2 status
226         uart2_error_isr,                                // 37 UART2 error
227         adc0_isr,                                       // 38 ADC0
228         cmp0_isr,                                       // 39 CMP0
229         cmp1_isr,                                       // 40 CMP1
230         ftm0_isr,                                       // 41 FTM0
231         ftm1_isr,                                       // 42 FTM1
232         cmt_isr,                                        // 43 CMT
233         rtc_alarm_isr,                                  // 44 RTC Alarm interrupt
234         rtc_seconds_isr,                                // 45 RTC Seconds interrupt
235         pit0_isr,                                       // 46 PIT Channel 0
236         pit1_isr,                                       // 47 PIT Channel 1
237         pit2_isr,                                       // 48 PIT Channel 2
238         pit3_isr,                                       // 49 PIT Channel 3
239         pdb_isr,                                        // 50 PDB Programmable Delay Block
240         usb_isr,                                        // 51 USB OTG
241         usb_charge_isr,                                 // 52 USB Charger Detect
242         tsi0_isr,                                       // 53 TSI0
243         mcg_isr,                                        // 54 MCG
244         lptmr_isr,                                      // 55 Low Power Timer
245         porta_isr,                                      // 56 Pin detect (Port A)
246         portb_isr,                                      // 57 Pin detect (Port B)
247         portc_isr,                                      // 58 Pin detect (Port C)
248         portd_isr,                                      // 59 Pin detect (Port D)
249         porte_isr,                                      // 60 Pin detect (Port E)
250         software_isr,                                   // 61 Software interrupt
251 #elif defined(_mk20dx256_) || defined(_mk20dx256vlh7_)
252         dma_ch0_isr,                                    // 16 DMA channel 0 transfer complete
253         dma_ch1_isr,                                    // 17 DMA channel 1 transfer complete
254         dma_ch2_isr,                                    // 18 DMA channel 2 transfer complete
255         dma_ch3_isr,                                    // 19 DMA channel 3 transfer complete
256         dma_ch4_isr,                                    // 20 DMA channel 4 transfer complete
257         dma_ch5_isr,                                    // 21 DMA channel 5 transfer complete
258         dma_ch6_isr,                                    // 22 DMA channel 6 transfer complete
259         dma_ch7_isr,                                    // 23 DMA channel 7 transfer complete
260         dma_ch8_isr,                                    // 24 DMA channel 8 transfer complete
261         dma_ch9_isr,                                    // 25 DMA channel 9 transfer complete
262         dma_ch10_isr,                                   // 26 DMA channel 10 transfer complete
263         dma_ch11_isr,                                   // 27 DMA channel 10 transfer complete
264         dma_ch12_isr,                                   // 28 DMA channel 10 transfer complete
265         dma_ch13_isr,                                   // 29 DMA channel 10 transfer complete
266         dma_ch14_isr,                                   // 30 DMA channel 10 transfer complete
267         dma_ch15_isr,                                   // 31 DMA channel 10 transfer complete
268         dma_error_isr,                                  // 32 DMA error interrupt channel
269         unused_isr,                                     // 33 --
270         flash_cmd_isr,                                  // 34 Flash Memory Command complete
271         flash_error_isr,                                // 35 Flash Read collision
272         low_voltage_isr,                                // 36 Low-voltage detect/warning
273         wakeup_isr,                                     // 37 Low Leakage Wakeup
274         watchdog_isr,                                   // 38 Both EWM and WDOG interrupt
275         unused_isr,                                     // 39 --
276         i2c0_isr,                                       // 40 I2C0
277         i2c1_isr,                                       // 41 I2C1
278         spi0_isr,                                       // 42 SPI0
279         spi1_isr,                                       // 43 SPI1
280         unused_isr,                                     // 44 --
281         can0_message_isr,                               // 45 CAN OR'ed Message buffer (0-15)
282         can0_bus_off_isr,                               // 46 CAN Bus Off
283         can0_error_isr,                                 // 47 CAN Error
284         can0_tx_warn_isr,                               // 48 CAN Transmit Warning
285         can0_rx_warn_isr,                               // 49 CAN Receive Warning
286         can0_wakeup_isr,                                // 50 CAN Wake Up
287         i2s0_tx_isr,                                    // 51 I2S0 Transmit
288         i2s0_rx_isr,                                    // 52 I2S0 Receive
289         unused_isr,                                     // 53 --
290         unused_isr,                                     // 54 --
291         unused_isr,                                     // 55 --
292         unused_isr,                                     // 56 --
293         unused_isr,                                     // 57 --
294         unused_isr,                                     // 58 --
295         unused_isr,                                     // 59 --
296         uart0_lon_isr,                                  // 60 UART0 CEA709.1-B (LON) status
297         uart0_status_isr,                               // 61 UART0 status
298         uart0_error_isr,                                // 62 UART0 error
299         uart1_status_isr,                               // 63 UART1 status
300         uart1_error_isr,                                // 64 UART1 error
301         uart2_status_isr,                               // 65 UART2 status
302         uart2_error_isr,                                // 66 UART2 error
303         unused_isr,                                     // 67 --
304         unused_isr,                                     // 68 --
305         unused_isr,                                     // 69 --
306         unused_isr,                                     // 70 --
307         unused_isr,                                     // 71 --
308         unused_isr,                                     // 72 --
309         adc0_isr,                                       // 73 ADC0
310         adc1_isr,                                       // 74 ADC1
311         cmp0_isr,                                       // 75 CMP0
312         cmp1_isr,                                       // 76 CMP1
313         cmp2_isr,                                       // 77 CMP2
314         ftm0_isr,                                       // 78 FTM0
315         ftm1_isr,                                       // 79 FTM1
316         ftm2_isr,                                       // 80 FTM2
317         cmt_isr,                                        // 81 CMT
318         rtc_alarm_isr,                                  // 82 RTC Alarm interrupt
319         rtc_seconds_isr,                                // 83 RTC Seconds interrupt
320         pit0_isr,                                       // 84 PIT Channel 0
321         pit1_isr,                                       // 85 PIT Channel 1
322         pit2_isr,                                       // 86 PIT Channel 2
323         pit3_isr,                                       // 87 PIT Channel 3
324         pdb_isr,                                        // 88 PDB Programmable Delay Block
325         usb_isr,                                        // 89 USB OTG
326         usb_charge_isr,                                 // 90 USB Charger Detect
327         unused_isr,                                     // 91 --
328         unused_isr,                                     // 92 --
329         unused_isr,                                     // 93 --
330         unused_isr,                                     // 94 --
331         unused_isr,                                     // 95 --
332         unused_isr,                                     // 96 --
333         dac0_isr,                                       // 97 DAC0
334         unused_isr,                                     // 98 --
335         tsi0_isr,                                       // 99 TSI0
336         mcg_isr,                                        // 100 MCG
337         lptmr_isr,                                      // 101 Low Power Timer
338         unused_isr,                                     // 102 --
339         porta_isr,                                      // 103 Pin detect (Port A)
340         portb_isr,                                      // 104 Pin detect (Port B)
341         portc_isr,                                      // 105 Pin detect (Port C)
342         portd_isr,                                      // 106 Pin detect (Port D)
343         porte_isr,                                      // 107 Pin detect (Port E)
344         unused_isr,                                     // 108 --
345         unused_isr,                                     // 109 --
346         software_isr,                                   // 110 Software interrupt
347 #endif
348 };
349
350
351 // ----- Flash Configuration -----
352
353 // Only necessary for Teensy 3s, MCHCK uses the Bootloader to handle this
354 #if defined(_mk20dx128_) || defined(_mk20dx256_)
355 __attribute__ ((section(".flashconfig"), used))
356 const uint8_t flashconfigbytes[16] = {
357         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
358         0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF
359 };
360 #elif defined(_mk20dx128vlf5_) && defined(_bootloader_)
361 // XXX Byte labels may be in incorrect positions, double check before modifying
362 //     FSEC is in correct location -Jacob
363 __attribute__ ((section(".flashconfig"), used))
364 const uint8_t flashconfigbytes[16] = {
365         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Backdoor Verif Key 28.3.1
366
367         //
368         // Protecting the first 4k of Flash memory from being over-written while running (bootloader protection)
369         // Still possible to overwrite the bootloader using an external flashing device
370         // For more details see:
371         //  http://cache.freescale.com/files/training/doc/dwf/AMF_ENT_T1031_Boston.pdf (page 8)
372         //  http://cache.freescale.com/files/microcontrollers/doc/app_note/AN4507.pdf
373         //  http://cache.freescale.com/files/32bit/doc/ref_manual/K20P48M50SF0RM.pdf (28.34.6)
374         //
375         0xFF, 0xFF, 0xFF, 0xFE, // Program Flash Protection Bytes FPROT0-3
376
377         0xBE, // Flash security byte FSEC
378         0x03, // Flash nonvolatile option byte FOPT
379         0xFF, // EEPROM Protection Byte FEPROT
380         0xFF, // Data Flash Protection Byte FDPROT
381 };
382 #elif defined(_mk20dx256vlh7_) && defined(_bootloader_)
383 // XXX Byte labels may be in incorrect positions, double check before modifying
384 //     FSEC is in correct location -Jacob
385 __attribute__ ((section(".flashconfig"), used))
386 const uint8_t flashconfigbytes[16] = {
387         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Backdoor Verif Key 28.3.1
388
389         //
390         // Protecting the first 8k of Flash memory from being over-written while running (bootloader protection)
391         // Still possible to overwrite the bootloader using an external flashing device
392         // For more details see:
393         //  http://cache.freescale.com/files/training/doc/dwf/AMF_ENT_T1031_Boston.pdf (page 8)
394         //  http://cache.freescale.com/files/microcontrollers/doc/app_note/AN4507.pdf
395         //  http://cache.freescale.com/files/32bit/doc/ref_manual/K20P64M72SF1RM.pdf (28.34.6)
396         //
397         0xFF, 0xFF, 0xFF, 0xFF, // Program Flash Protection Bytes FPROT0-3 // XXX TODO PROTECT
398
399         0xBE, // Flash security byte FSEC
400         0x03, // Flash nonvolatile option byte FOPT
401         0xFF, // EEPROM Protection Byte FEPROT
402         0xFF, // Data Flash Protection Byte FDPROT
403 };
404 #endif
405
406
407
408 // ----- Functions -----
409
410 #if ( defined(_mk20dx128vlf5_) || defined(_mk20dx256vlh7_) ) && defined(_bootloader_) // Bootloader Section
411 __attribute__((noreturn))
412 static inline void jump_to_app( uintptr_t addr )
413 {
414         // addr is in r0
415         __asm__("ldr sp, [%[addr], #0]\n"
416                 "ldr pc, [%[addr], #4]"
417                 :: [addr] "r" (addr));
418         // NOTREACHED
419         __builtin_unreachable();
420 }
421 #endif
422
423 void *memset( void *addr, int val, unsigned int len )
424 {
425         char *buf = addr;
426
427         for (; len > 0; --len, ++buf)
428                 *buf = val;
429         return (addr);
430 }
431
432 int memcmp( const void *a, const void *b, unsigned int len )
433 {
434         const uint8_t *ap = a, *bp = b;
435         int val = 0;
436
437         for (; len > 0 && (val = *ap - *bp) == 0; --len, ++ap, ++bp)
438                 /* NOTHING */;
439         return (val);
440 }
441
442 void *memcpy( void *dst, const void *src, unsigned int len )
443 {
444         char *dstbuf = dst;
445         const char *srcbuf = src;
446
447         for (; len > 0; --len, ++dstbuf, ++srcbuf)
448                 *dstbuf = *srcbuf;
449         return (dst);
450 }
451
452
453
454 // ----- Chip Entry Point -----
455
456 __attribute__ ((section(".startup")))
457 void ResetHandler()
458 {
459 #if ( defined(_mk20dx128vlf5_) || defined(_mk20dx256vlh7_) ) && defined(_bootloader_) // Bootloader Section
460         extern uint32_t _app_rom;
461
462         // We treat _app_rom as pointer to directly read the stack
463         // pointer and check for valid app code.  This is no fool
464         // proof method, but it should help for the first flash.
465         //
466         // Purposefully disabling the watchdog *after* the reset check this way
467         // if the chip goes into an odd state we'll reset to the bootloader (invalid firmware image)
468         // RCM_SRS0 & 0x20
469         //
470         // Also checking for ARM lock-up signal (invalid firmware image)
471         // RCM_SRS1 & 0x02
472         if (    // PIN  (External Reset Pin/Switch)
473                    RCM_SRS0 & 0x40
474                 // WDOG (Watchdog timeout)
475                 || RCM_SRS0 & 0x20
476                 // LOCKUP (ARM Core LOCKUP event)
477                 || RCM_SRS1 & 0x02
478                 // Blank flash check
479                 || _app_rom == 0xffffffff
480                 // Software reset
481                 || memcmp( (uint8_t*)&VBAT, sys_reset_to_loader_magic, sizeof(sys_reset_to_loader_magic) ) == 0
482         )
483         {
484                 memset( (uint8_t*)&VBAT, 0, sizeof(VBAT) );
485         }
486         else
487         {
488                 uint32_t addr = (uintptr_t)&_app_rom;
489                 SCB_VTOR = addr; // relocate vector table
490                 jump_to_app( addr );
491         }
492 #endif
493         // Disable Watchdog
494         WDOG_UNLOCK = WDOG_UNLOCK_SEQ1;
495         WDOG_UNLOCK = WDOG_UNLOCK_SEQ2;
496         WDOG_STCTRLH = WDOG_STCTRLH_ALLOWUPDATE;
497
498         uint32_t *src = (uint32_t*)&_etext;
499         uint32_t *dest = (uint32_t*)&_sdata;
500
501         // Enable clocks to always-used peripherals
502         SIM_SCGC5 = 0x00043F82; // Clocks active to all GPIO
503         SIM_SCGC6 = SIM_SCGC6_FTM0 | SIM_SCGC6_FTM1 | SIM_SCGC6_ADC0 | SIM_SCGC6_FTFL;
504 #if defined(_mk20dx128_)
505         SIM_SCGC6 |= SIM_SCGC6_RTC;
506 #elif defined(_mk20dx256_)
507         SIM_SCGC3 = SIM_SCGC3_ADC1 | SIM_SCGC3_FTM2;
508         SIM_SCGC6 |= SIM_SCGC6_RTC;
509 #endif
510
511 #if defined(_mk20dx128_) || defined(_mk20dx256_) // Teensy 3s
512         // if the RTC oscillator isn't enabled, get it started early
513         if ( !(RTC_CR & RTC_CR_OSCE) )
514         {
515                 RTC_SR = 0;
516                 RTC_CR = RTC_CR_SC16P | RTC_CR_SC4P | RTC_CR_OSCE;
517         }
518 #endif
519
520         // release I/O pins hold, if we woke up from VLLS mode
521         if ( PMC_REGSC & PMC_REGSC_ACKISO )
522         {
523                 PMC_REGSC |= PMC_REGSC_ACKISO;
524         }
525
526         // Prepare RAM
527         while ( dest < (uint32_t*)&_edata ) *dest++ = *src++;
528         dest = (uint32_t*)&_sbss;
529         while ( dest < (uint32_t*)&_ebss ) *dest++ = 0;
530
531 // MCHCK / Kiibohd-dfu
532 #if defined(_mk20dx128vlf5_)
533         // Default all interrupts to medium priority level
534         for ( unsigned int i = 0; i < NVIC_NUM_INTERRUPTS; i++ )
535         {
536                 NVIC_SET_PRIORITY( i, 128 );
537         }
538
539         // FLL at 48MHz
540         MCG_C4 = MCG_C4_DMX32 | MCG_C4_DRST_DRS( 1 );
541
542         // USB Clock and FLL select
543         SIM_SOPT2 = SIM_SOPT2_USBSRC | SIM_SOPT2_TRACECLKSEL;
544
545 // Teensy 3.0 and 3.1 and Kiibohd-dfu (mk20dx256vlh7)
546 #else
547         SCB_VTOR = 0;   // use vector table in flash
548
549         // default all interrupts to medium priority level
550         for ( unsigned int i = 0; i < NVIC_NUM_INTERRUPTS; i++ )
551         {
552                 NVIC_SET_PRIORITY( i, 128 );
553         }
554
555         // start in FEI mode
556         // enable capacitors for crystal
557         OSC0_CR = OSC_SC8P | OSC_SC2P;
558
559         // enable osc, 8-32 MHz range, low power mode
560         MCG_C2 = MCG_C2_RANGE0( 2 ) | MCG_C2_EREFS;
561
562         // switch to crystal as clock source, FLL input = 16 MHz / 512
563         MCG_C1 =  MCG_C1_CLKS( 2 ) | MCG_C1_FRDIV( 4 );
564
565         // wait for crystal oscillator to begin
566         while ( (MCG_S & MCG_S_OSCINIT0) == 0 );
567
568         // wait for FLL to use oscillator
569         while ( (MCG_S & MCG_S_IREFST) != 0 );
570
571         // wait for MCGOUT to use oscillator
572         while ( (MCG_S & MCG_S_CLKST_MASK) != MCG_S_CLKST( 2 ) );
573
574         // now we're in FBE mode
575 #if F_CPU == 72000000
576         // config PLL input for 16 MHz Crystal / 8 = 2 MHz
577         MCG_C5 = MCG_C5_PRDIV0( 7 );
578 #else
579         // config PLL input for 16 MHz Crystal / 4 = 4 MHz
580         MCG_C5 = MCG_C5_PRDIV0( 3 );
581 #endif
582
583 #if F_CPU == 72000000
584         // config PLL for 72 MHz output (36 * 2 MHz Ext PLL)
585         MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0( 12 );
586 #else
587         // config PLL for 96 MHz output
588         MCG_C6 = MCG_C6_PLLS | MCG_C6_VDIV0( 0 );
589 #endif
590
591         // wait for PLL to start using xtal as its input
592         while ( !(MCG_S & MCG_S_PLLST) );
593
594         // wait for PLL to lock
595         while ( !(MCG_S & MCG_S_LOCK0) );
596
597         // now we're in PBE mode
598 #if F_CPU == 96000000
599         // config divisors: 96 MHz core, 48 MHz bus, 24 MHz flash
600         SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1( 0 ) | SIM_CLKDIV1_OUTDIV2( 1 ) | SIM_CLKDIV1_OUTDIV4( 3 );
601 #elif F_CPU == 72000000
602         // config divisors: 72 MHz core, 36 MHz bus, 24 MHz flash
603         SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1( 0 ) | SIM_CLKDIV1_OUTDIV2( 1 ) | SIM_CLKDIV1_OUTDIV4( 2 );
604 #elif F_CPU == 48000000
605         // config divisors: 48 MHz core, 48 MHz bus, 24 MHz flash
606         SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1( 1 ) | SIM_CLKDIV1_OUTDIV2( 1 ) | SIM_CLKDIV1_OUTDIV4( 3 );
607 #elif F_CPU == 24000000
608         // config divisors: 24 MHz core, 24 MHz bus, 24 MHz flash
609         SIM_CLKDIV1 = SIM_CLKDIV1_OUTDIV1( 3 ) | SIM_CLKDIV1_OUTDIV2( 3 ) | SIM_CLKDIV1_OUTDIV4( 3 );
610 #else
611 #error "Error, F_CPU must be 96000000, 72000000, 48000000, or 24000000"
612 #endif
613         // switch to PLL as clock source, FLL input = 16 MHz / 512
614         MCG_C1 = MCG_C1_CLKS( 0 ) | MCG_C1_FRDIV( 4 );
615
616         // wait for PLL clock to be used
617         while ( (MCG_S & MCG_S_CLKST_MASK) != MCG_S_CLKST( 3 ) );
618
619         // now we're in PEE mode
620 #if F_CPU == 72000000
621         // configure USB for 48 MHz clock
622         SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV( 2 ) | SIM_CLKDIV2_USBFRAC; // USB = 72 MHz PLL / 1.5
623 #else
624         // configure USB for 48 MHz clock
625         SIM_CLKDIV2 = SIM_CLKDIV2_USBDIV( 1 ); // USB = 96 MHz PLL / 2
626 #endif
627
628         // USB uses PLL clock, trace is CPU clock, CLKOUT=OSCERCLK0
629         SIM_SOPT2 = SIM_SOPT2_USBSRC | SIM_SOPT2_PLLFLLSEL | SIM_SOPT2_TRACECLKSEL | SIM_SOPT2_CLKOUTSEL( 6 );
630
631 #endif
632
633 #if !defined(_bootloader_)
634         // Initialize the SysTick counter
635         SYST_RVR = (F_CPU / 1000) - 1;
636         SYST_CSR = SYST_CSR_CLKSOURCE | SYST_CSR_TICKINT | SYST_CSR_ENABLE;
637
638         __enable_irq();
639 #else
640         // Disable Watchdog for bootloader
641         WDOG_STCTRLH &= ~WDOG_STCTRLH_WDOGEN;
642 #endif
643
644         main();
645         while ( 1 ); // Shouldn't get here...
646 }
647
648
649
650 // ----- RAM Setup -----
651
652 char *__brkval = (char *)&_ebss;
653
654 void * _sbrk( int incr )
655 {
656         char *prev = __brkval;
657         __brkval += incr;
658         return prev;
659 }
660
661
662
663 // ----- Interrupt Execution Priority -----
664
665 int nvic_execution_priority()
666 {
667         int priority = 256;
668         uint32_t primask, faultmask, basepri, ipsr;
669
670         // full algorithm in ARM DDI0403D, page B1-639
671         // this isn't quite complete, but hopefully good enough
672         asm volatile( "mrs %0, faultmask\n" : "=r" (faultmask):: );
673         if ( faultmask )
674         {
675                 return -1;
676         }
677
678         asm volatile( "mrs %0, primask\n" : "=r" (primask):: );
679         if ( primask )
680         {
681                 return 0;
682         }
683
684         asm volatile( "mrs %0, ipsr\n" : "=r" (ipsr):: );
685         if ( ipsr )
686         {
687                 if ( ipsr < 16)
688                 {
689                         priority = 0; // could be non-zero
690                 }
691                 else
692                 {
693                         priority = NVIC_GET_PRIORITY( ipsr - 16 );
694                 }
695         }
696
697         asm volatile( "mrs %0, basepri\n" : "=r" (basepri):: );
698         if ( basepri > 0 && basepri < priority )
699         {
700                 priority = basepri;
701         }
702
703         return priority;
704 }
705