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