1 /*
2  * Copyright (c) 2012-2014 Wind River Systems, Inc.
3  * Copyright (c) 2020 Arm Limited
4  * Copyright (c) 2021 Nordic Semiconductor ASA
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include <assert.h>
20 #include <zephyr.h>
21 #include <drivers/gpio.h>
22 #include <sys/__assert.h>
23 #include <drivers/flash.h>
24 #include <drivers/timer/system_timer.h>
25 #include <usb/usb_device.h>
26 #include <soc.h>
27 #include <linker/linker-defs.h>
28 
29 #include "target.h"
30 
31 #include "bootutil/bootutil_log.h"
32 #include "bootutil/image.h"
33 #include "bootutil/bootutil.h"
34 #include "bootutil/fault_injection_hardening.h"
35 #include "flash_map_backend/flash_map_backend.h"
36 
37 #ifdef CONFIG_MCUBOOT_SERIAL
38 #include "boot_serial/boot_serial.h"
39 #include "serial_adapter/serial_adapter.h"
40 
41 const struct boot_uart_funcs boot_funcs = {
42     .read = console_read,
43     .write = console_write
44 };
45 #endif
46 
47 #if defined(CONFIG_BOOT_USB_DFU_WAIT) || defined(CONFIG_BOOT_USB_DFU_GPIO)
48 #include <usb/class/usb_dfu.h>
49 #endif
50 
51 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
52 #include <arm_cleanup.h>
53 #endif
54 
55 /* CONFIG_LOG_MINIMAL is the legacy Kconfig property,
56  * replaced by CONFIG_LOG_MODE_MINIMAL.
57  */
58 #if (defined(CONFIG_LOG_MODE_MINIMAL) || defined(CONFIG_LOG_MINIMAL))
59 #define ZEPHYR_LOG_MODE_MINIMAL 1
60 #endif
61 
62 #if defined(CONFIG_LOG) && !defined(CONFIG_LOG_IMMEDIATE) && \
63     !defined(ZEPHYR_LOG_MODE_MINIMAL)
64 #ifdef CONFIG_LOG_PROCESS_THREAD
65 #warning "The log internal thread for log processing can't transfer the log"\
66          "well for MCUBoot."
67 #else
68 #include <logging/log_ctrl.h>
69 
70 #define BOOT_LOG_PROCESSING_INTERVAL K_MSEC(30) /* [ms] */
71 
72 /* log are processing in custom routine */
73 K_THREAD_STACK_DEFINE(boot_log_stack, CONFIG_MCUBOOT_LOG_THREAD_STACK_SIZE);
74 struct k_thread boot_log_thread;
75 volatile bool boot_log_stop = false;
76 K_SEM_DEFINE(boot_log_sem, 1, 1);
77 
78 /* log processing need to be initalized by the application */
79 #define ZEPHYR_BOOT_LOG_START() zephyr_boot_log_start()
80 #define ZEPHYR_BOOT_LOG_STOP() zephyr_boot_log_stop()
81 #endif /* CONFIG_LOG_PROCESS_THREAD */
82 #else
83 /* synchronous log mode doesn't need to be initalized by the application */
84 #define ZEPHYR_BOOT_LOG_START() do { } while (false)
85 #define ZEPHYR_BOOT_LOG_STOP() do { } while (false)
86 #endif /* defined(CONFIG_LOG) && !defined(CONFIG_LOG_IMMEDIATE) */
87 
88 #ifdef CONFIG_SOC_FAMILY_NRF
89 #include <hal/nrf_power.h>
90 
boot_skip_serial_recovery()91 static inline bool boot_skip_serial_recovery()
92 {
93 #if NRF_POWER_HAS_RESETREAS
94     uint32_t rr = nrf_power_resetreas_get(NRF_POWER);
95 
96     return !(rr == 0 || (rr & NRF_POWER_RESETREAS_RESETPIN_MASK));
97 #else
98     return false;
99 #endif
100 }
101 #else
boot_skip_serial_recovery()102 static inline bool boot_skip_serial_recovery()
103 {
104     return false;
105 }
106 #endif
107 
108 MCUBOOT_LOG_MODULE_REGISTER(mcuboot);
109 
110 #ifdef CONFIG_MCUBOOT_INDICATION_LED
111 /*
112  * Devicetree helper macro which gets the 'flags' cell from a 'gpios'
113  * property, or returns 0 if the property has no 'flags' cell.
114  */
115 #define FLAGS_OR_ZERO(node)                        \
116   COND_CODE_1(DT_PHA_HAS_CELL(node, gpios, flags), \
117               (DT_GPIO_FLAGS(node, gpios)),        \
118               (0))
119 
120 /*
121  * The led0 devicetree alias is optional. If present, we'll use it
122  * to turn on the LED whenever the button is pressed.
123  */
124 
125 #define LED0_NODE DT_ALIAS(bootloader_led0)
126 
127 #if DT_NODE_HAS_STATUS(LED0_NODE, okay) && DT_NODE_HAS_PROP(LED0_NODE, gpios)
128 #define LED0_GPIO_LABEL DT_GPIO_LABEL(LED0_NODE, gpios)
129 #define LED0_GPIO_PIN DT_GPIO_PIN(LED0_NODE, gpios)
130 #define LED0_GPIO_FLAGS (GPIO_OUTPUT | FLAGS_OR_ZERO(LED0_NODE))
131 #else
132 /* A build error here means your board isn't set up to drive an LED. */
133 #error "Unsupported board: led0 devicetree alias is not defined"
134 #endif
135 
136 const static struct device *led;
137 
led_init(void)138 void led_init(void)
139 {
140 
141   led = device_get_binding(LED0_GPIO_LABEL);
142   if (led == NULL) {
143     BOOT_LOG_ERR("Didn't find LED device %s\n", LED0_GPIO_LABEL);
144     return;
145   }
146 
147   gpio_pin_configure(led, LED0_GPIO_PIN, LED0_GPIO_FLAGS);
148   gpio_pin_set(led, LED0_GPIO_PIN, 0);
149 
150 }
151 #endif
152 
153 void os_heap_init(void);
154 
155 #if defined(CONFIG_ARM)
156 
157 #ifdef CONFIG_SW_VECTOR_RELAY
158 extern void *_vector_table_pointer;
159 #endif
160 
161 struct arm_vector_table {
162     uint32_t msp;
163     uint32_t reset;
164 };
165 
166 extern void sys_clock_disable(void);
167 
do_boot(struct boot_rsp * rsp)168 static void do_boot(struct boot_rsp *rsp)
169 {
170     struct arm_vector_table *vt;
171     uintptr_t flash_base;
172     int rc;
173 
174     /* The beginning of the image is the ARM vector table, containing
175      * the initial stack pointer address and the reset vector
176      * consecutively. Manually set the stack pointer and jump into the
177      * reset vector
178      */
179     rc = flash_device_base(rsp->br_flash_dev_id, &flash_base);
180     assert(rc == 0);
181 
182     vt = (struct arm_vector_table *)(flash_base +
183                                      rsp->br_image_off +
184                                      rsp->br_hdr->ih_hdr_size);
185 
186 #ifdef CONFIG_SYS_CLOCK_EXISTS
187     sys_clock_disable();
188 #endif
189 #ifdef CONFIG_USB
190     /* Disable the USB to prevent it from firing interrupts */
191     usb_disable();
192 #endif
193 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
194     cleanup_arm_nvic(); /* cleanup NVIC registers */
195 
196 #ifdef CONFIG_CPU_CORTEX_M7
197     /* Disable instruction cache and data cache before chain-load the application */
198     SCB_DisableDCache();
199     SCB_DisableICache();
200 #endif
201 
202 #if CONFIG_CPU_HAS_ARM_MPU || CONFIG_CPU_HAS_NXP_MPU
203     z_arm_clear_arm_mpu_config();
204 #endif
205 
206 #if defined(CONFIG_BUILTIN_STACK_GUARD) && \
207     defined(CONFIG_CPU_CORTEX_M_HAS_SPLIM)
208     /* Reset limit registers to avoid inflicting stack overflow on image
209      * being booted.
210      */
211     __set_PSPLIM(0);
212     __set_MSPLIM(0);
213 #endif
214 
215 #else
216     irq_lock();
217 #endif /* CONFIG_MCUBOOT_CLEANUP_ARM_CORE */
218 
219 #ifdef CONFIG_BOOT_INTR_VEC_RELOC
220 #if defined(CONFIG_SW_VECTOR_RELAY)
221     _vector_table_pointer = vt;
222 #ifdef CONFIG_CPU_CORTEX_M_HAS_VTOR
223     SCB->VTOR = (uint32_t)__vector_relay_table;
224 #endif
225 #elif defined(CONFIG_CPU_CORTEX_M_HAS_VTOR)
226     SCB->VTOR = (uint32_t)vt;
227 #endif /* CONFIG_SW_VECTOR_RELAY */
228 #else /* CONFIG_BOOT_INTR_VEC_RELOC */
229 #if defined(CONFIG_CPU_CORTEX_M_HAS_VTOR) && defined(CONFIG_SW_VECTOR_RELAY)
230     _vector_table_pointer = _vector_start;
231     SCB->VTOR = (uint32_t)__vector_relay_table;
232 #endif
233 #endif /* CONFIG_BOOT_INTR_VEC_RELOC */
234 
235     __set_MSP(vt->msp);
236 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
237     __set_CONTROL(0x00); /* application will configures core on its own */
238     __ISB();
239 #endif
240     ((void (*)(void))vt->reset)();
241 }
242 
243 #elif defined(CONFIG_XTENSA)
244 #define SRAM_BASE_ADDRESS	0xBE030000
245 
copy_img_to_SRAM(int slot,unsigned int hdr_offset)246 static void copy_img_to_SRAM(int slot, unsigned int hdr_offset)
247 {
248     const struct flash_area *fap;
249     int area_id;
250     int rc;
251     unsigned char *dst = (unsigned char *)(SRAM_BASE_ADDRESS + hdr_offset);
252 
253     BOOT_LOG_INF("Copying image to SRAM");
254 
255     area_id = flash_area_id_from_image_slot(slot);
256     rc = flash_area_open(area_id, &fap);
257     if (rc != 0) {
258         BOOT_LOG_ERR("flash_area_open failed with %d\n", rc);
259         goto done;
260     }
261 
262     rc = flash_area_read(fap, hdr_offset, dst, fap->fa_size - hdr_offset);
263     if (rc != 0) {
264         BOOT_LOG_ERR("flash_area_read failed with %d\n", rc);
265         goto done;
266     }
267 
268 done:
269     flash_area_close(fap);
270 }
271 
272 /* Entry point (.ResetVector) is at the very beginning of the image.
273  * Simply copy the image to a suitable location and jump there.
274  */
do_boot(struct boot_rsp * rsp)275 static void do_boot(struct boot_rsp *rsp)
276 {
277     void *start;
278 
279     BOOT_LOG_INF("br_image_off = 0x%x\n", rsp->br_image_off);
280     BOOT_LOG_INF("ih_hdr_size = 0x%x\n", rsp->br_hdr->ih_hdr_size);
281 
282     /* Copy from the flash to HP SRAM */
283     copy_img_to_SRAM(0, rsp->br_hdr->ih_hdr_size);
284 
285     /* Jump to entry point */
286     start = (void *)(SRAM_BASE_ADDRESS + rsp->br_hdr->ih_hdr_size);
287     ((void (*)(void))start)();
288 }
289 
290 #else
291 /* Default: Assume entry point is at the very beginning of the image. Simply
292  * lock interrupts and jump there. This is the right thing to do for X86 and
293  * possibly other platforms.
294  */
do_boot(struct boot_rsp * rsp)295 static void do_boot(struct boot_rsp *rsp)
296 {
297     uintptr_t flash_base;
298     void *start;
299     int rc;
300 
301     rc = flash_device_base(rsp->br_flash_dev_id, &flash_base);
302     assert(rc == 0);
303 
304     start = (void *)(flash_base + rsp->br_image_off +
305                      rsp->br_hdr->ih_hdr_size);
306 
307     /* Lock interrupts and dive into the entry point */
308     irq_lock();
309     ((void (*)(void))start)();
310 }
311 #endif
312 
313 #if defined(CONFIG_LOG) && !defined(CONFIG_LOG_IMMEDIATE) &&\
314     !defined(CONFIG_LOG_PROCESS_THREAD) && !defined(ZEPHYR_LOG_MODE_MINIMAL)
315 /* The log internal thread for log processing can't transfer log well as has too
316  * low priority.
317  * Dedicated thread for log processing below uses highest application
318  * priority. This allows to transmit all logs without adding k_sleep/k_yield
319  * anywhere else int the code.
320  */
321 
322 /* most simple log processing theread */
boot_log_thread_func(void * dummy1,void * dummy2,void * dummy3)323 void boot_log_thread_func(void *dummy1, void *dummy2, void *dummy3)
324 {
325     (void)dummy1;
326     (void)dummy2;
327     (void)dummy3;
328 
329      log_init();
330 
331      while (1) {
332              if (log_process(false) == false) {
333                     if (boot_log_stop) {
334                         break;
335                     }
336                     k_sleep(BOOT_LOG_PROCESSING_INTERVAL);
337              }
338      }
339 
340      k_sem_give(&boot_log_sem);
341 }
342 
zephyr_boot_log_start(void)343 void zephyr_boot_log_start(void)
344 {
345         /* start logging thread */
346         k_thread_create(&boot_log_thread, boot_log_stack,
347                 K_THREAD_STACK_SIZEOF(boot_log_stack),
348                 boot_log_thread_func, NULL, NULL, NULL,
349                 K_HIGHEST_APPLICATION_THREAD_PRIO, 0,
350                 BOOT_LOG_PROCESSING_INTERVAL);
351 
352         k_thread_name_set(&boot_log_thread, "logging");
353 }
354 
zephyr_boot_log_stop(void)355 void zephyr_boot_log_stop(void)
356 {
357     boot_log_stop = true;
358 
359     /* wait until log procesing thread expired
360      * This can be reworked using a thread_join() API once a such will be
361      * available in zephyr.
362      * see https://github.com/zephyrproject-rtos/zephyr/issues/21500
363      */
364     (void)k_sem_take(&boot_log_sem, K_FOREVER);
365 }
366 #endif/* defined(CONFIG_LOG) && !defined(CONFIG_LOG_IMMEDIATE) &&\
367         !defined(CONFIG_LOG_PROCESS_THREAD) */
368 
369 #if defined(CONFIG_MCUBOOT_SERIAL) || defined(CONFIG_BOOT_USB_DFU_GPIO)
detect_pin(const char * port,int pin,uint32_t expected,int delay)370 static bool detect_pin(const char* port, int pin, uint32_t expected, int delay)
371 {
372     int rc;
373     int detect_value;
374     struct device const *detect_port;
375 
376     detect_port = device_get_binding(port);
377     __ASSERT(detect_port, "Error: Bad port for boot detection.\n");
378 
379     /* The default presence value is 0 which would normally be
380      * active-low, but historically the raw value was checked so we'll
381      * use the raw interface.
382      */
383     rc = gpio_pin_configure(detect_port, pin,
384                             GPIO_INPUT | GPIO_PULL_UP);
385     __ASSERT(rc == 0, "Failed to initialize boot detect pin.\n");
386 
387     rc = gpio_pin_get_raw(detect_port, pin);
388     detect_value = rc;
389 
390     __ASSERT(rc >= 0, "Failed to read boot detect pin.\n");
391 
392     if (detect_value == expected) {
393         if (delay > 0) {
394 #ifdef CONFIG_MULTITHREADING
395             k_sleep(K_MSEC(50));
396 #else
397             k_busy_wait(50000);
398 #endif
399 
400             /* Get the uptime for debounce purposes. */
401             int64_t timestamp = k_uptime_get();
402 
403             for(;;) {
404                 rc = gpio_pin_get_raw(detect_port, pin);
405                 detect_value = rc;
406                 __ASSERT(rc >= 0, "Failed to read boot detect pin.\n");
407 
408                 /* Get delta from when this started */
409                 uint32_t delta = k_uptime_get() -  timestamp;
410 
411                 /* If not pressed OR if pressed > debounce period, stop. */
412                 if (delta >= delay || detect_value != expected) {
413                     break;
414                 }
415 
416                 /* Delay 1 ms */
417 #ifdef CONFIG_MULTITHREADING
418                 k_sleep(K_MSEC(1));
419 #else
420                 k_busy_wait(1000);
421 #endif
422             }
423         }
424     }
425 
426     return detect_value == expected;
427 }
428 #endif
429 
main(void)430 void main(void)
431 {
432     struct boot_rsp rsp;
433     int rc;
434     fih_int fih_rc = FIH_FAILURE;
435 
436     MCUBOOT_WATCHDOG_FEED();
437 
438 #if !defined(MCUBOOT_DIRECT_XIP)
439     BOOT_LOG_INF("Starting bootloader");
440 #else
441     BOOT_LOG_INF("Starting Direct-XIP bootloader");
442 #endif
443 
444 #ifdef CONFIG_MCUBOOT_INDICATION_LED
445     /* LED init */
446     led_init();
447 #endif
448 
449     os_heap_init();
450 
451     ZEPHYR_BOOT_LOG_START();
452 
453     (void)rc;
454 
455 #if (!defined(CONFIG_XTENSA) && defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL))
456     if (!flash_device_get_binding(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) {
457         BOOT_LOG_ERR("Flash device %s not found",
458 		     DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL);
459         while (1)
460             ;
461     }
462 #elif (defined(CONFIG_XTENSA) && defined(JEDEC_SPI_NOR_0_LABEL))
463     if (!flash_device_get_binding(JEDEC_SPI_NOR_0_LABEL)) {
464         BOOT_LOG_ERR("Flash device %s not found", JEDEC_SPI_NOR_0_LABEL);
465         while (1)
466             ;
467     }
468 #endif
469 
470 #ifdef CONFIG_MCUBOOT_SERIAL
471     if (detect_pin(CONFIG_BOOT_SERIAL_DETECT_PORT,
472                    CONFIG_BOOT_SERIAL_DETECT_PIN,
473                    CONFIG_BOOT_SERIAL_DETECT_PIN_VAL,
474                    CONFIG_BOOT_SERIAL_DETECT_DELAY) &&
475             !boot_skip_serial_recovery()) {
476 #ifdef CONFIG_MCUBOOT_INDICATION_LED
477         gpio_pin_set(led, LED0_GPIO_PIN, 1);
478 #endif
479 
480         BOOT_LOG_INF("Enter the serial recovery mode");
481         rc = boot_console_init();
482         __ASSERT(rc == 0, "Error initializing boot console.\n");
483         boot_serial_start(&boot_funcs);
484         __ASSERT(0, "Bootloader serial process was terminated unexpectedly.\n");
485     }
486 #endif
487 
488 #if defined(CONFIG_BOOT_USB_DFU_GPIO)
489     if (detect_pin(CONFIG_BOOT_USB_DFU_DETECT_PORT,
490                    CONFIG_BOOT_USB_DFU_DETECT_PIN,
491                    CONFIG_BOOT_USB_DFU_DETECT_PIN_VAL,
492                    CONFIG_BOOT_USB_DFU_DETECT_DELAY)) {
493 #ifdef CONFIG_MCUBOOT_INDICATION_LED
494         gpio_pin_set(led, LED0_GPIO_PIN, 1);
495 #endif
496         rc = usb_enable(NULL);
497         if (rc) {
498             BOOT_LOG_ERR("Cannot enable USB");
499         } else {
500             BOOT_LOG_INF("Waiting for USB DFU");
501             wait_for_usb_dfu(K_FOREVER);
502             BOOT_LOG_INF("USB DFU wait time elapsed");
503         }
504     }
505 #elif defined(CONFIG_BOOT_USB_DFU_WAIT)
506     rc = usb_enable(NULL);
507     if (rc) {
508         BOOT_LOG_ERR("Cannot enable USB");
509     } else {
510         BOOT_LOG_INF("Waiting for USB DFU");
511         wait_for_usb_dfu(K_MSEC(CONFIG_BOOT_USB_DFU_WAIT_DELAY_MS));
512         BOOT_LOG_INF("USB DFU wait time elapsed");
513     }
514 #endif
515 
516     FIH_CALL(boot_go, fih_rc, &rsp);
517     if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
518         BOOT_LOG_ERR("Unable to find bootable image");
519         FIH_PANIC;
520     }
521 
522     BOOT_LOG_INF("Bootloader chainload address offset: 0x%x",
523                  rsp.br_image_off);
524 
525 #if defined(MCUBOOT_DIRECT_XIP)
526     BOOT_LOG_INF("Jumping to the image slot");
527 #else
528     BOOT_LOG_INF("Jumping to the first image slot");
529 #endif
530     ZEPHYR_BOOT_LOG_STOP();
531     do_boot(&rsp);
532 
533     BOOT_LOG_ERR("Never should get here");
534     while (1)
535         ;
536 }
537