nrf_bootloader.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /**
  2. * Copyright (c) 2016 - 2019, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. #include "nrf_bootloader.h"
  41. #include "compiler_abstraction.h"
  42. #include "nrf.h"
  43. #include "boards.h"
  44. #include "sdk_config.h"
  45. #include "nrf_power.h"
  46. #include "nrf_delay.h"
  47. #include "nrf_log.h"
  48. #include "nrf_log_ctrl.h"
  49. #include "nrf_dfu.h"
  50. #include "nrf_error.h"
  51. #include "nrf_dfu_settings.h"
  52. #include "nrf_dfu_utils.h"
  53. #include "nrf_bootloader_wdt.h"
  54. #include "nrf_bootloader_info.h"
  55. #include "nrf_bootloader_app_start.h"
  56. #include "nrf_bootloader_fw_activation.h"
  57. #include "nrf_bootloader_dfu_timers.h"
  58. #include "app_scheduler.h"
  59. #include "nrf_dfu_validation.h"
  60. static nrf_dfu_observer_t m_user_observer; //<! Observer callback set by the user.
  61. static volatile bool m_flash_write_done;
  62. #define SCHED_QUEUE_SIZE 32 /**< Maximum number of events in the scheduler queue. */
  63. #define SCHED_EVENT_DATA_SIZE NRF_DFU_SCHED_EVENT_DATA_SIZE /**< Maximum app_scheduler event size. */
  64. #if !(defined(NRF_BL_DFU_ENTER_METHOD_BUTTON) && \
  65. defined(NRF_BL_DFU_ENTER_METHOD_PINRESET) && \
  66. defined(NRF_BL_DFU_ENTER_METHOD_GPREGRET) && \
  67. defined(NRF_BL_DFU_ENTER_METHOD_BUTTONLESS))
  68. #error Configuration file is missing flags. Update sdk_config.h.
  69. #endif
  70. STATIC_ASSERT((NRF_BL_DFU_INACTIVITY_TIMEOUT_MS >= 100) || (NRF_BL_DFU_INACTIVITY_TIMEOUT_MS == 0),
  71. "NRF_BL_DFU_INACTIVITY_TIMEOUT_MS must be 100 ms or more, or 0 to indicate that it is disabled.");
  72. #if defined(NRF_LOG_BACKEND_FLASH_START_PAGE)
  73. STATIC_ASSERT(NRF_LOG_BACKEND_FLASH_START_PAGE != 0,
  74. "If nrf_log flash backend is used it cannot use space after code because it would collide with settings page.");
  75. #endif
  76. /**@brief Weak implemenation of nrf_dfu_init
  77. *
  78. * @note This function will be overridden if nrf_dfu.c is
  79. * compiled and linked with the project
  80. */
  81. #if (__LINT__ != 1)
  82. __WEAK uint32_t nrf_dfu_init(nrf_dfu_observer_t observer)
  83. {
  84. NRF_LOG_DEBUG("in weak nrf_dfu_init");
  85. return NRF_SUCCESS;
  86. }
  87. #endif
  88. /**@brief Weak implementation of nrf_dfu_init
  89. *
  90. * @note This function must be overridden in application if
  91. * user-specific initialization is needed.
  92. */
  93. __WEAK uint32_t nrf_dfu_init_user(void)
  94. {
  95. NRF_LOG_DEBUG("in weak nrf_dfu_init_user");
  96. return NRF_SUCCESS;
  97. }
  98. static void flash_write_callback(void * p_context)
  99. {
  100. UNUSED_PARAMETER(p_context);
  101. m_flash_write_done = true;
  102. }
  103. static void do_reset(void * p_context)
  104. {
  105. UNUSED_PARAMETER(p_context);
  106. NRF_LOG_FINAL_FLUSH();
  107. #if NRF_MODULE_ENABLED(NRF_LOG_BACKEND_RTT)
  108. // To allow the buffer to be flushed by the host.
  109. nrf_delay_ms(100);
  110. #endif
  111. NVIC_SystemReset();
  112. }
  113. static void bootloader_reset(bool do_backup)
  114. {
  115. NRF_LOG_DEBUG("Resetting bootloader.");
  116. if (do_backup)
  117. {
  118. m_flash_write_done = false;
  119. nrf_dfu_settings_backup(do_reset);
  120. }
  121. else
  122. {
  123. do_reset(NULL);
  124. }
  125. }
  126. static void inactivity_timeout(void)
  127. {
  128. NRF_LOG_INFO("Inactivity timeout.");
  129. bootloader_reset(true);
  130. }
  131. /**@brief Function for handling DFU events.
  132. */
  133. static void dfu_observer(nrf_dfu_evt_type_t evt_type)
  134. {
  135. switch (evt_type)
  136. {
  137. case NRF_DFU_EVT_DFU_STARTED:
  138. case NRF_DFU_EVT_OBJECT_RECEIVED:
  139. nrf_bootloader_dfu_inactivity_timer_restart(
  140. NRF_BOOTLOADER_MS_TO_TICKS(NRF_BL_DFU_INACTIVITY_TIMEOUT_MS),
  141. inactivity_timeout);
  142. break;
  143. case NRF_DFU_EVT_DFU_COMPLETED:
  144. case NRF_DFU_EVT_DFU_ABORTED:
  145. bootloader_reset(true);
  146. break;
  147. default:
  148. break;
  149. }
  150. if (m_user_observer)
  151. {
  152. m_user_observer(evt_type);
  153. }
  154. }
  155. /**@brief Function for initializing the event scheduler.
  156. */
  157. static void scheduler_init(void)
  158. {
  159. APP_SCHED_INIT(SCHED_EVENT_DATA_SIZE, SCHED_QUEUE_SIZE);
  160. }
  161. /**@brief Suspend the CPU until an interrupt occurs.
  162. */
  163. static void wait_for_event(void)
  164. {
  165. #if defined(BLE_STACK_SUPPORT_REQD) || defined(ANT_STACK_SUPPORT_REQD)
  166. (void)sd_app_evt_wait();
  167. #else
  168. // Wait for an event.
  169. __WFE();
  170. // Clear the internal event register.
  171. __SEV();
  172. __WFE();
  173. #endif
  174. }
  175. /**@brief Continually sleep and process tasks whenever woken.
  176. */
  177. static void loop_forever(void)
  178. {
  179. while (true)
  180. {
  181. //feed the watchdog if enabled.
  182. nrf_bootloader_wdt_feed();
  183. app_sched_execute();
  184. if (!NRF_LOG_PROCESS())
  185. {
  186. wait_for_event();
  187. }
  188. }
  189. }
  190. /**@brief Function for initializing button used to enter DFU mode.
  191. */
  192. static void dfu_enter_button_init(void)
  193. {
  194. nrf_gpio_cfg_sense_input(NRF_BL_DFU_ENTER_METHOD_BUTTON_PIN,
  195. BUTTON_PULL,
  196. NRF_GPIO_PIN_SENSE_LOW);
  197. }
  198. static bool crc_on_valid_app_required(void)
  199. {
  200. bool ret = true;
  201. if (NRF_BL_APP_CRC_CHECK_SKIPPED_ON_SYSTEMOFF_RESET &&
  202. (nrf_power_resetreas_get() & NRF_POWER_RESETREAS_OFF_MASK))
  203. {
  204. nrf_power_resetreas_clear(NRF_POWER_RESETREAS_OFF_MASK);
  205. ret = false;
  206. }
  207. else if (NRF_BL_APP_CRC_CHECK_SKIPPED_ON_GPREGRET2 &&
  208. ((nrf_power_gpregret2_get() & BOOTLOADER_DFU_GPREGRET2_MASK) == BOOTLOADER_DFU_GPREGRET2)
  209. && (nrf_power_gpregret2_get() & BOOTLOADER_DFU_SKIP_CRC_BIT_MASK))
  210. {
  211. nrf_power_gpregret2_set(nrf_power_gpregret2_get() & ~BOOTLOADER_DFU_SKIP_CRC);
  212. ret = false;
  213. }
  214. else
  215. {
  216. }
  217. return ret;
  218. }
  219. static bool boot_validate(boot_validation_t const * p_validation, uint32_t data_addr, uint32_t data_len, bool do_crc)
  220. {
  221. if (!do_crc && (p_validation->type == VALIDATE_CRC))
  222. {
  223. return true;
  224. }
  225. return nrf_dfu_validation_boot_validate(p_validation, data_addr, data_len);
  226. }
  227. /** @brief Function for checking if the main application is valid.
  228. *
  229. * @details This function checks if there is a valid application
  230. * located at Bank 0.
  231. *
  232. * @param[in] do_crc Perform CRC check on application. Only CRC checks
  233. can be skipped. For other boot validation types,
  234. this parameter is ignored.
  235. *
  236. * @retval true If a valid application has been detected.
  237. * @retval false If there is no valid application.
  238. */
  239. static bool app_is_valid(bool do_crc)
  240. {
  241. if (s_dfu_settings.bank_0.bank_code != NRF_DFU_BANK_VALID_APP)
  242. {
  243. NRF_LOG_INFO("Boot validation failed. No valid app to boot.");
  244. return false;
  245. }
  246. else if (NRF_BL_APP_SIGNATURE_CHECK_REQUIRED &&
  247. (s_dfu_settings.boot_validation_app.type != VALIDATE_ECDSA_P256_SHA256))
  248. {
  249. NRF_LOG_WARNING("Boot validation failed. The boot validation of the app must be a signature check.");
  250. return false;
  251. }
  252. else if (SD_PRESENT && !boot_validate(&s_dfu_settings.boot_validation_softdevice, MBR_SIZE, s_dfu_settings.sd_size, do_crc))
  253. {
  254. NRF_LOG_WARNING("Boot validation failed. SoftDevice is present but invalid.");
  255. return false;
  256. }
  257. else if (!boot_validate(&s_dfu_settings.boot_validation_app, nrf_dfu_bank0_start_addr(), s_dfu_settings.bank_0.image_size, do_crc))
  258. {
  259. NRF_LOG_WARNING("Boot validation failed. App is invalid.");
  260. return false;
  261. }
  262. // The bootloader itself is not checked, since a self-check of this kind gives little to no benefit
  263. // compared to the cost incurred on each bootup.
  264. NRF_LOG_DEBUG("App is valid");
  265. return true;
  266. }
  267. /**@brief Function for clearing all DFU enter flags that
  268. * preserve state during reset.
  269. *
  270. * @details This is used to make sure that each of these flags
  271. * is checked only once after reset.
  272. */
  273. static void dfu_enter_flags_clear(void)
  274. {
  275. if (NRF_BL_DFU_ENTER_METHOD_PINRESET &&
  276. (NRF_POWER->RESETREAS & POWER_RESETREAS_RESETPIN_Msk))
  277. {
  278. // Clear RESETPIN flag.
  279. NRF_POWER->RESETREAS |= POWER_RESETREAS_RESETPIN_Msk;
  280. }
  281. if (NRF_BL_DFU_ENTER_METHOD_GPREGRET &&
  282. ((nrf_power_gpregret_get() & BOOTLOADER_DFU_GPREGRET_MASK) == BOOTLOADER_DFU_GPREGRET)
  283. && (nrf_power_gpregret_get() & BOOTLOADER_DFU_START_BIT_MASK))
  284. {
  285. // Clear DFU mark in GPREGRET register.
  286. nrf_power_gpregret_set(nrf_power_gpregret_get() & ~BOOTLOADER_DFU_START);
  287. }
  288. if (NRF_BL_DFU_ENTER_METHOD_BUTTONLESS &&
  289. (s_dfu_settings.enter_buttonless_dfu == 1))
  290. {
  291. // Clear DFU flag in flash settings.
  292. s_dfu_settings.enter_buttonless_dfu = 0;
  293. APP_ERROR_CHECK(nrf_dfu_settings_write(NULL));
  294. }
  295. }
  296. /**@brief Function for checking whether to enter DFU mode or not.
  297. */
  298. static bool dfu_enter_check(void)
  299. {
  300. if (!app_is_valid(crc_on_valid_app_required()))
  301. {
  302. NRF_LOG_DEBUG("DFU mode because app is not valid.");
  303. return true;
  304. }
  305. if (NRF_BL_DFU_ENTER_METHOD_BUTTON &&
  306. (nrf_gpio_pin_read(NRF_BL_DFU_ENTER_METHOD_BUTTON_PIN) == 0))
  307. {
  308. NRF_LOG_DEBUG("DFU mode requested via button.");
  309. return true;
  310. }
  311. if (NRF_BL_DFU_ENTER_METHOD_PINRESET &&
  312. (NRF_POWER->RESETREAS & POWER_RESETREAS_RESETPIN_Msk))
  313. {
  314. NRF_LOG_DEBUG("DFU mode requested via pin-reset.");
  315. return true;
  316. }
  317. if (NRF_BL_DFU_ENTER_METHOD_GPREGRET &&
  318. (nrf_power_gpregret_get() & BOOTLOADER_DFU_START))
  319. {
  320. NRF_LOG_DEBUG("DFU mode requested via GPREGRET.");
  321. return true;
  322. }
  323. if (NRF_BL_DFU_ENTER_METHOD_BUTTONLESS &&
  324. (s_dfu_settings.enter_buttonless_dfu == 1))
  325. {
  326. NRF_LOG_DEBUG("DFU mode requested via bootloader settings.");
  327. return true;
  328. }
  329. return false;
  330. }
  331. #if NRF_BL_DFU_ALLOW_UPDATE_FROM_APP
  332. static void postvalidate(void)
  333. {
  334. NRF_LOG_INFO("Postvalidating update after reset.");
  335. nrf_dfu_validation_init();
  336. if (nrf_dfu_validation_init_cmd_present())
  337. {
  338. uint32_t firmware_start_addr;
  339. uint32_t firmware_size;
  340. // Execute a previously received init packed. Subsequent executes will have no effect.
  341. if (nrf_dfu_validation_init_cmd_execute(&firmware_start_addr, &firmware_size) == NRF_DFU_RES_CODE_SUCCESS)
  342. {
  343. if (nrf_dfu_validation_prevalidate() == NRF_DFU_RES_CODE_SUCCESS)
  344. {
  345. if (nrf_dfu_validation_activation_prepare(firmware_start_addr, firmware_size) == NRF_DFU_RES_CODE_SUCCESS)
  346. {
  347. NRF_LOG_INFO("Postvalidation successful.");
  348. }
  349. }
  350. }
  351. }
  352. s_dfu_settings.bank_current = NRF_DFU_CURRENT_BANK_0;
  353. UNUSED_RETURN_VALUE(nrf_dfu_settings_write_and_backup(flash_write_callback));
  354. }
  355. #endif
  356. ret_code_t nrf_bootloader_init(nrf_dfu_observer_t observer)
  357. {
  358. NRF_LOG_DEBUG("In nrf_bootloader_init");
  359. ret_code_t ret_val;
  360. nrf_bootloader_fw_activation_result_t activation_result;
  361. uint32_t initial_timeout;
  362. bool dfu_enter = false;
  363. m_user_observer = observer;
  364. if (NRF_BL_DFU_ENTER_METHOD_BUTTON)
  365. {
  366. dfu_enter_button_init();
  367. }
  368. ret_val = nrf_dfu_settings_init(false);
  369. if (ret_val != NRF_SUCCESS)
  370. {
  371. return NRF_ERROR_INTERNAL;
  372. }
  373. #if NRF_BL_DFU_ALLOW_UPDATE_FROM_APP
  374. // Postvalidate if DFU has signaled that update is ready.
  375. if (s_dfu_settings.bank_current == NRF_DFU_CURRENT_BANK_1)
  376. {
  377. postvalidate();
  378. }
  379. #endif
  380. // Check if an update needs to be activated and activate it.
  381. activation_result = nrf_bootloader_fw_activate();
  382. switch (activation_result)
  383. {
  384. case ACTIVATION_NONE:
  385. initial_timeout = NRF_BOOTLOADER_MS_TO_TICKS(NRF_BL_DFU_INACTIVITY_TIMEOUT_MS);
  386. dfu_enter = dfu_enter_check();
  387. break;
  388. case ACTIVATION_SUCCESS_EXPECT_ADDITIONAL_UPDATE:
  389. initial_timeout = NRF_BOOTLOADER_MS_TO_TICKS(NRF_BL_DFU_CONTINUATION_TIMEOUT_MS);
  390. dfu_enter = true;
  391. break;
  392. case ACTIVATION_SUCCESS:
  393. bootloader_reset(true);
  394. NRF_LOG_ERROR("Unreachable");
  395. return NRF_ERROR_INTERNAL; // Should not reach this.
  396. case ACTIVATION_ERROR:
  397. default:
  398. return NRF_ERROR_INTERNAL;
  399. }
  400. if (dfu_enter)
  401. {
  402. nrf_bootloader_wdt_init();
  403. scheduler_init();
  404. dfu_enter_flags_clear();
  405. // Call user-defined init function if implemented
  406. ret_val = nrf_dfu_init_user();
  407. if (ret_val != NRF_SUCCESS)
  408. {
  409. return NRF_ERROR_INTERNAL;
  410. }
  411. nrf_bootloader_dfu_inactivity_timer_restart(initial_timeout, inactivity_timeout);
  412. ret_val = nrf_dfu_init(dfu_observer);
  413. if (ret_val != NRF_SUCCESS)
  414. {
  415. return NRF_ERROR_INTERNAL;
  416. }
  417. NRF_LOG_DEBUG("Enter main loop");
  418. loop_forever(); // This function will never return.
  419. NRF_LOG_ERROR("Unreachable");
  420. }
  421. else
  422. {
  423. // Erase additional data like peer data or advertisement name
  424. ret_val = nrf_dfu_settings_additional_erase();
  425. if (ret_val != NRF_SUCCESS)
  426. {
  427. return NRF_ERROR_INTERNAL;
  428. }
  429. m_flash_write_done = false;
  430. nrf_dfu_settings_backup(flash_write_callback);
  431. ASSERT(m_flash_write_done);
  432. nrf_bootloader_app_start();
  433. NRF_LOG_ERROR("Unreachable");
  434. }
  435. // Should not be reached.
  436. return NRF_ERROR_INTERNAL;
  437. }