nrf_fstorage_sd.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /**
  2. * Copyright (c) 2016 - 2020, 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 "sdk_common.h"
  41. #if NRF_MODULE_ENABLED(NRF_FSTORAGE)
  42. #include "nrf_fstorage_sd.h"
  43. #include <stdint.h>
  44. #include <string.h>
  45. #include <stdbool.h>
  46. #include "nordic_common.h"
  47. #include "nrf_soc.h"
  48. #include "nrf_sdh.h"
  49. #include "nrf_sdh_soc.h"
  50. #include "nrf_atomic.h"
  51. #include "nrf_atfifo.h"
  52. #include "app_util_platform.h"
  53. #if (NRF_FSTORAGE_SD_MAX_WRITE_SIZE % 4)
  54. #error NRF_FSTORAGE_SD_MAX_WRITE_SIZE must be a multiple of the word size.
  55. #endif
  56. /**@brief fstorage operation codes. */
  57. typedef enum
  58. {
  59. NRF_FSTORAGE_OP_WRITE, //!< Write bytes to flash.
  60. NRF_FSTORAGE_OP_ERASE //!< Erase flash pages.
  61. } nrf_fstorage_sd_opcode_t;
  62. ANON_UNIONS_ENABLE;
  63. /**@brief fstorage operation queue element. */
  64. typedef struct
  65. {
  66. nrf_fstorage_t const * p_fs; //!< The fstorage instance that requested the operation.
  67. nrf_fstorage_sd_opcode_t op_code; //!< Requested operation.
  68. void * p_param; //!< User-defined parameter passed to the event handler.
  69. union
  70. {
  71. struct
  72. {
  73. void const * p_src; //!< Data to be written to flash.
  74. uint32_t dest; //!< Destination of the data in flash.
  75. uint32_t len; //!< Length of the data to be written (in bytes).
  76. uint32_t offset; //!< Write offset.
  77. } write;
  78. struct
  79. {
  80. uint32_t page; //!< Physical page number.
  81. uint32_t progress; //!< Number of pages erased.
  82. uint32_t pages_to_erase; //!< Total number of pages to erase.
  83. } erase;
  84. };
  85. } nrf_fstorage_sd_op_t;
  86. ANON_UNIONS_DISABLE;
  87. typedef enum
  88. {
  89. NRF_FSTORAGE_STATE_IDLE, //!< No operations requested to the SoftDevice.
  90. NRF_FSTORAGE_STATE_OP_PENDING, //!< A non-fstorage operation is pending.
  91. NRF_FSTORAGE_STATE_OP_EXECUTING, //!< An fstorage operation is executing.
  92. } nrf_fstorage_sd_state_t;
  93. /**@brief Internal state. */
  94. typedef struct
  95. {
  96. nrf_atomic_flag_t initialized; //!< fstorage is initalized.
  97. nrf_atomic_flag_t queue_running; //!< The queue is running.
  98. /** Prevent API calls from entering queue_process(). */
  99. nrf_fstorage_sd_state_t state; //!< Internal fstorage state.
  100. uint32_t retries; //!< Number of times an operation has been retried on timeout.
  101. bool sd_enabled; //!< The SoftDevice is enabled.
  102. bool paused; //!< A SoftDevice state change is impending.
  103. /** Do not load a new operation when the last one completes. */
  104. } nrf_fstorage_sd_work_t;
  105. void nrf_fstorage_sys_evt_handler(uint32_t, void *);
  106. bool nrf_fstorage_sdh_req_handler(nrf_sdh_req_evt_t, void *);
  107. void nrf_fstorage_sdh_state_handler(nrf_sdh_state_evt_t, void *);
  108. /* Flash device information. */
  109. static nrf_fstorage_info_t m_flash_info =
  110. {
  111. #if defined(NRF51)
  112. .erase_unit = 1024,
  113. #elif defined(NRF52_SERIES)
  114. .erase_unit = 4096,
  115. #endif
  116. .program_unit = 4,
  117. .rmap = true,
  118. .wmap = false,
  119. };
  120. /* Queue of fstorage operations. */
  121. NRF_ATFIFO_DEF(m_fifo, nrf_fstorage_sd_op_t, NRF_FSTORAGE_SD_QUEUE_SIZE);
  122. /* Define a nrf_sdh_soc event observer to receive SoftDevice system events. */
  123. NRF_SDH_SOC_OBSERVER(m_sys_obs, 0, nrf_fstorage_sys_evt_handler, NULL);
  124. /* nrf_sdh request observer. */
  125. NRF_SDH_REQUEST_OBSERVER(m_req_obs, 0) =
  126. {
  127. .handler = nrf_fstorage_sdh_req_handler,
  128. };
  129. /* nrf_sdh state observer. */
  130. NRF_SDH_STATE_OBSERVER(m_state_obs, 0) =
  131. {
  132. .handler = nrf_fstorage_sdh_state_handler,
  133. };
  134. static nrf_fstorage_sd_work_t m_flags; /* Internal status. */
  135. static nrf_fstorage_sd_op_t * m_p_cur_op; /* The current operation being executed. */
  136. static nrf_atfifo_item_get_t m_iget_ctx; /* Context for nrf_atfifo_item_get() and nrf_atfifo_item_free(). */
  137. /* Send events to the application. */
  138. static void event_send(nrf_fstorage_sd_op_t const * p_op, ret_code_t result)
  139. {
  140. if (p_op->p_fs->evt_handler == NULL)
  141. {
  142. /* Nothing to do. */
  143. return;
  144. }
  145. nrf_fstorage_evt_t evt =
  146. {
  147. .result = result,
  148. .p_param = p_op->p_param,
  149. };
  150. switch (p_op->op_code)
  151. {
  152. case NRF_FSTORAGE_OP_WRITE:
  153. evt.id = NRF_FSTORAGE_EVT_WRITE_RESULT;
  154. evt.addr = p_op->write.dest;
  155. evt.p_src = p_op->write.p_src;
  156. evt.len = p_op->write.len;
  157. break;
  158. case NRF_FSTORAGE_OP_ERASE:
  159. evt.id = NRF_FSTORAGE_EVT_ERASE_RESULT;
  160. evt.addr = (p_op->erase.page * m_flash_info.erase_unit);
  161. evt.len = p_op->erase.pages_to_erase;
  162. break;
  163. default:
  164. /* Should not happen. */
  165. break;
  166. }
  167. p_op->p_fs->evt_handler(&evt);
  168. }
  169. /* Write to flash. */
  170. static uint32_t write_execute(nrf_fstorage_sd_op_t const * p_op)
  171. {
  172. uint32_t chunk_len;
  173. chunk_len = MIN(p_op->write.len - p_op->write.offset, NRF_FSTORAGE_SD_MAX_WRITE_SIZE);
  174. chunk_len = MAX(1, chunk_len / m_flash_info.program_unit);
  175. /* Cast to p_src to uint32_t to perform arithmetic. */
  176. uint32_t * p_dest = (uint32_t*)(p_op->write.dest + p_op->write.offset);
  177. uint32_t const * p_src = (uint32_t*)((uint32_t)p_op->write.p_src + p_op->write.offset);
  178. return sd_flash_write(p_dest, p_src, chunk_len);
  179. }
  180. /* Erase flash page(s). */
  181. static uint32_t erase_execute(nrf_fstorage_sd_op_t const * p_op)
  182. {
  183. return sd_flash_page_erase(p_op->erase.page + p_op->erase.progress);
  184. }
  185. /* Free the current queue element. */
  186. static void queue_free(void)
  187. {
  188. (void) nrf_atfifo_item_free(m_fifo, &m_iget_ctx);
  189. }
  190. /* Load a new operation from the queue. */
  191. static bool queue_load_next(void)
  192. {
  193. m_p_cur_op = nrf_atfifo_item_get(m_fifo, &m_iget_ctx);
  194. return (m_p_cur_op != NULL);
  195. }
  196. /* Execute an operation in the queue. */
  197. static void queue_process(void)
  198. {
  199. uint32_t rc;
  200. if (m_flags.state == NRF_FSTORAGE_STATE_IDLE)
  201. {
  202. if (!queue_load_next())
  203. {
  204. /* No more operations, nothing to do. */
  205. m_flags.queue_running = false;
  206. return;
  207. }
  208. }
  209. m_flags.state = NRF_FSTORAGE_STATE_OP_EXECUTING;
  210. switch (m_p_cur_op->op_code)
  211. {
  212. case NRF_FSTORAGE_OP_WRITE:
  213. rc = write_execute(m_p_cur_op);
  214. break;
  215. case NRF_FSTORAGE_OP_ERASE:
  216. rc = erase_execute(m_p_cur_op);
  217. break;
  218. default:
  219. rc = NRF_ERROR_INTERNAL;
  220. break;
  221. }
  222. switch (rc)
  223. {
  224. case NRF_SUCCESS:
  225. {
  226. /* The operation was accepted by the SoftDevice.
  227. * If the SoftDevice is enabled, wait for a system event. Otherwise,
  228. * the SoftDevice call is synchronous and will not send an event so we simulate it. */
  229. if (!m_flags.sd_enabled)
  230. {
  231. nrf_fstorage_sys_evt_handler(NRF_EVT_FLASH_OPERATION_SUCCESS, NULL);
  232. }
  233. } break;
  234. case NRF_ERROR_BUSY:
  235. {
  236. /* The SoftDevice is executing a flash operation that was not requested by fstorage.
  237. * Stop processing the queue until a system event is received. */
  238. m_flags.state = NRF_FSTORAGE_STATE_OP_PENDING;
  239. } break;
  240. default:
  241. {
  242. /* An error has occurred. We cannot proceed further with this operation. */
  243. event_send(m_p_cur_op, NRF_ERROR_INTERNAL);
  244. /* Reset the internal state so we can accept other operations. */
  245. m_flags.state = NRF_FSTORAGE_STATE_IDLE;
  246. m_flags.queue_running = false;
  247. /* Free the current queue element. */
  248. queue_free();
  249. } break;
  250. }
  251. }
  252. /* Start processing the queue if it is not running and fstorage is not paused. */
  253. static void queue_start(void)
  254. {
  255. if ( (!nrf_atomic_flag_set_fetch(&m_flags.queue_running))
  256. && (!m_flags.paused))
  257. {
  258. queue_process();
  259. }
  260. }
  261. /* Flash operation success callback. Keeps track of the progress of an operation. */
  262. static bool on_operation_success(nrf_fstorage_sd_op_t * const p_op)
  263. {
  264. /* Reset the retry counter on success. */
  265. m_flags.retries = 0;
  266. switch (p_op->op_code)
  267. {
  268. case NRF_FSTORAGE_OP_WRITE:
  269. {
  270. /* Update the offset only if the operation is successful
  271. * so that it can be retried in case it times out. */
  272. uint32_t const chunk_len = MIN(p_op->write.len - p_op->write.offset,
  273. NRF_FSTORAGE_SD_MAX_WRITE_SIZE);
  274. p_op->write.offset += chunk_len;
  275. if (p_op->write.offset == p_op->write.len)
  276. {
  277. return true;
  278. }
  279. } break;
  280. case NRF_FSTORAGE_OP_ERASE:
  281. {
  282. p_op->erase.progress++;
  283. if (p_op->erase.progress == p_op->erase.pages_to_erase)
  284. {
  285. return true;
  286. }
  287. } break;
  288. default:
  289. /* Should not happen. */
  290. break;
  291. }
  292. return false;
  293. }
  294. /* Flash operation failure callback. */
  295. static bool on_operation_failure(nrf_fstorage_sd_op_t const * p_op)
  296. {
  297. UNUSED_PARAMETER(p_op);
  298. m_flags.retries++;
  299. if (m_flags.retries > NRF_FSTORAGE_SD_MAX_RETRIES)
  300. {
  301. /* Maximum amount of retries reached. Give up. */
  302. m_flags.retries = 0;
  303. return true;
  304. }
  305. return false;
  306. }
  307. static ret_code_t init(nrf_fstorage_t * p_fs, void * p_param)
  308. {
  309. UNUSED_PARAMETER(p_param);
  310. p_fs->p_flash_info = &m_flash_info;
  311. if (!nrf_atomic_flag_set_fetch(&m_flags.initialized))
  312. {
  313. #if NRF_SDH_ENABLED
  314. m_flags.sd_enabled = nrf_sdh_is_enabled();
  315. #endif
  316. (void) NRF_ATFIFO_INIT(m_fifo);
  317. }
  318. return NRF_SUCCESS;
  319. }
  320. static ret_code_t uninit(nrf_fstorage_t * p_fs, void * p_param)
  321. {
  322. UNUSED_PARAMETER(p_fs);
  323. UNUSED_PARAMETER(p_param);
  324. /* The state is re-initialized upon init().
  325. * The common uninitialization code is run by the caller. */
  326. memset(&m_flags, 0x00, sizeof(m_flags));
  327. (void) nrf_atfifo_clear(m_fifo);
  328. return NRF_SUCCESS;
  329. }
  330. static ret_code_t write(nrf_fstorage_t const * p_fs,
  331. uint32_t dest,
  332. void const * p_src,
  333. uint32_t len,
  334. void * p_param)
  335. {
  336. nrf_fstorage_sd_op_t * p_op;
  337. nrf_atfifo_item_put_t iput_ctx;
  338. /* Get a free queue element. */
  339. p_op = nrf_atfifo_item_alloc(m_fifo, &iput_ctx);
  340. if (p_op == NULL)
  341. {
  342. return NRF_ERROR_NO_MEM;
  343. }
  344. /* Initialize the operation. */
  345. memset(p_op, 0x00, sizeof(nrf_fstorage_sd_op_t));
  346. p_op->op_code = NRF_FSTORAGE_OP_WRITE;
  347. p_op->p_fs = p_fs;
  348. p_op->p_param = p_param;
  349. p_op->write.dest = dest;
  350. p_op->write.p_src = p_src;
  351. p_op->write.len = len;
  352. /* Put the operation on the queue. */
  353. (void) nrf_atfifo_item_put(m_fifo, &iput_ctx);
  354. queue_start();
  355. return NRF_SUCCESS;
  356. }
  357. static ret_code_t read(nrf_fstorage_t const * p_fs, uint32_t src, void * p_dest, uint32_t len)
  358. {
  359. memcpy(p_dest, (uint32_t*)src, len);
  360. return NRF_SUCCESS;
  361. }
  362. static ret_code_t erase(nrf_fstorage_t const * p_fs,
  363. uint32_t page_addr,
  364. uint32_t len,
  365. void * p_param)
  366. {
  367. nrf_fstorage_sd_op_t * p_op;
  368. nrf_atfifo_item_put_t iput_ctx;
  369. /* Get a free queue element. */
  370. p_op = nrf_atfifo_item_alloc(m_fifo, &iput_ctx);
  371. if (p_op == NULL)
  372. {
  373. return NRF_ERROR_NO_MEM;
  374. }
  375. /* Initialize the operation. */
  376. memset(p_op, 0x00, sizeof(nrf_fstorage_sd_op_t));
  377. p_op->op_code = NRF_FSTORAGE_OP_ERASE;
  378. p_op->p_fs = p_fs;
  379. p_op->p_param = p_param;
  380. p_op->erase.page = (page_addr / m_flash_info.erase_unit);
  381. p_op->erase.pages_to_erase = len;
  382. /* Put the operation on the queue. */
  383. (void) nrf_atfifo_item_put(m_fifo, &iput_ctx);
  384. queue_start();
  385. return NRF_SUCCESS;
  386. }
  387. static uint8_t const * rmap(nrf_fstorage_t const * p_fs, uint32_t addr)
  388. {
  389. UNUSED_PARAMETER(p_fs);
  390. return (uint8_t*)addr;
  391. }
  392. static uint8_t * wmap(nrf_fstorage_t const * p_fs, uint32_t addr)
  393. {
  394. UNUSED_PARAMETER(p_fs);
  395. UNUSED_PARAMETER(addr);
  396. /* Not supported. */
  397. return NULL;
  398. }
  399. static bool is_busy(nrf_fstorage_t const * p_fs)
  400. {
  401. UNUSED_PARAMETER(p_fs);
  402. return (m_flags.state != NRF_FSTORAGE_STATE_IDLE);
  403. }
  404. void nrf_fstorage_sys_evt_handler(uint32_t sys_evt, void * p_context)
  405. {
  406. UNUSED_PARAMETER(p_context);
  407. if ( (sys_evt != NRF_EVT_FLASH_OPERATION_SUCCESS)
  408. && (sys_evt != NRF_EVT_FLASH_OPERATION_ERROR))
  409. {
  410. /* Ignore any non-flash events. */
  411. return;
  412. }
  413. switch (m_flags.state)
  414. {
  415. case NRF_FSTORAGE_STATE_IDLE:
  416. /* Ignore flash events if no flash operation was requested. */
  417. return;
  418. case NRF_FSTORAGE_STATE_OP_PENDING:
  419. /* The SoftDevice has completed a flash operation that was not requested by fstorage.
  420. * It should be possible to request an operation now.
  421. * Process the queue at the end of this function. */
  422. break;
  423. case NRF_FSTORAGE_STATE_OP_EXECUTING:
  424. {
  425. /* Handle the result of a flash operation initiated by this module. */
  426. bool operation_finished = false;
  427. switch (sys_evt)
  428. {
  429. case NRF_EVT_FLASH_OPERATION_SUCCESS:
  430. operation_finished = on_operation_success(m_p_cur_op);
  431. break;
  432. case NRF_EVT_FLASH_OPERATION_ERROR:
  433. operation_finished = on_operation_failure(m_p_cur_op);
  434. break;
  435. default:
  436. break;
  437. }
  438. if (operation_finished)
  439. {
  440. /* The operation has finished. Change state to NRF_FSTORAGE_STATE_IDLE
  441. * so that queue_process() will fetch a new operation from the queue. */
  442. m_flags.state = NRF_FSTORAGE_STATE_IDLE;
  443. event_send(m_p_cur_op, (sys_evt == NRF_EVT_FLASH_OPERATION_SUCCESS) ?
  444. NRF_SUCCESS : NRF_ERROR_TIMEOUT);
  445. /* Free the queue element after sending out the event to prevent API calls made
  446. * in the event context to queue elements indefinitely, without this function
  447. * ever returning in case the SoftDevice calls are synchronous. */
  448. queue_free();
  449. }
  450. } break;
  451. }
  452. if (!m_flags.paused)
  453. {
  454. queue_process();
  455. }
  456. else
  457. {
  458. /* A flash operation has completed. Let the SoftDevice change state. */
  459. (void) nrf_sdh_request_continue();
  460. }
  461. }
  462. bool nrf_fstorage_sdh_req_handler(nrf_sdh_req_evt_t req, void * p_context)
  463. {
  464. UNUSED_PARAMETER(req);
  465. UNUSED_PARAMETER(p_context);
  466. m_flags.paused = true;
  467. /* If there are any operations ongoing, pause the SoftDevice state change. */
  468. return (m_flags.state == NRF_FSTORAGE_STATE_IDLE);
  469. }
  470. void nrf_fstorage_sdh_state_handler(nrf_sdh_state_evt_t state, void * p_context)
  471. {
  472. UNUSED_PARAMETER(p_context);
  473. if ( (state == NRF_SDH_EVT_STATE_ENABLED)
  474. || (state == NRF_SDH_EVT_STATE_DISABLED))
  475. {
  476. m_flags.paused = false;
  477. m_flags.sd_enabled = (state == NRF_SDH_EVT_STATE_ENABLED);
  478. /* Execute any operations still in the queue. */
  479. queue_process();
  480. }
  481. }
  482. /* Exported API implementation. */
  483. nrf_fstorage_api_t nrf_fstorage_sd =
  484. {
  485. .init = init,
  486. .uninit = uninit,
  487. .read = read,
  488. .write = write,
  489. .erase = erase,
  490. .rmap = rmap,
  491. .wmap = wmap,
  492. .is_busy = is_busy
  493. };
  494. #endif // NRF_FSTORAGE_ENABLED