fcb_elem_info.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2017 Nordic Semiconductor ASA
  3. * Copyright (c) 2015 Runtime Inc
  4. *
  5. * SPDX-License-Identifier: Apache-2.0
  6. */
  7. #include <sys/crc.h>
  8. #include <fs/fcb.h>
  9. #include "fcb_priv.h"
  10. /*
  11. * Given offset in flash sector, fill in rest of the fcb_entry, and crc8 over
  12. * the data.
  13. */
  14. int
  15. fcb_elem_crc8(struct fcb *fcb, struct fcb_entry *loc, uint8_t *c8p)
  16. {
  17. uint8_t tmp_str[FCB_TMP_BUF_SZ];
  18. int cnt;
  19. int blk_sz;
  20. uint8_t crc8;
  21. uint16_t len;
  22. uint32_t off;
  23. uint32_t end;
  24. int rc;
  25. if (loc->fe_elem_off + 2 > loc->fe_sector->fs_size) {
  26. return -ENOTSUP;
  27. }
  28. rc = fcb_flash_read(fcb, loc->fe_sector, loc->fe_elem_off, tmp_str, 2);
  29. if (rc) {
  30. return -EIO;
  31. }
  32. cnt = fcb_get_len(fcb, tmp_str, &len);
  33. if (cnt < 0) {
  34. return cnt;
  35. }
  36. loc->fe_data_off = loc->fe_elem_off + fcb_len_in_flash(fcb, cnt);
  37. loc->fe_data_len = len;
  38. crc8 = CRC8_CCITT_INITIAL_VALUE;
  39. crc8 = crc8_ccitt(crc8, tmp_str, cnt);
  40. off = loc->fe_data_off;
  41. end = loc->fe_data_off + len;
  42. for (; off < end; off += blk_sz) {
  43. blk_sz = end - off;
  44. if (blk_sz > sizeof(tmp_str)) {
  45. blk_sz = sizeof(tmp_str);
  46. }
  47. rc = fcb_flash_read(fcb, loc->fe_sector, off, tmp_str, blk_sz);
  48. if (rc) {
  49. return -EIO;
  50. }
  51. crc8 = crc8_ccitt(crc8, tmp_str, blk_sz);
  52. }
  53. *c8p = crc8;
  54. return 0;
  55. }
  56. int fcb_elem_info(struct fcb *fcb, struct fcb_entry *loc)
  57. {
  58. int rc;
  59. uint8_t crc8;
  60. uint8_t fl_crc8;
  61. off_t off;
  62. rc = fcb_elem_crc8(fcb, loc, &crc8);
  63. if (rc) {
  64. return rc;
  65. }
  66. off = loc->fe_data_off + fcb_len_in_flash(fcb, loc->fe_data_len);
  67. rc = fcb_flash_read(fcb, loc->fe_sector, off, &fl_crc8, sizeof(fl_crc8));
  68. if (rc) {
  69. return -EIO;
  70. }
  71. if (fl_crc8 != crc8) {
  72. return -EBADMSG;
  73. }
  74. return 0;
  75. }