fal_flash.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (c) 2006-2024 RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-05-17 armink the first version
  9. */
  10. #include <fal.h>
  11. #include <string.h>
  12. /* flash device table, must defined by user */
  13. #if !defined(FAL_FLASH_DEV_TABLE)
  14. #error "You must defined flash device table (FAL_FLASH_DEV_TABLE) on 'fal_cfg.h'"
  15. #endif
  16. static const struct fal_flash_dev * const device_table[] = FAL_FLASH_DEV_TABLE;
  17. static const size_t device_table_len = sizeof(device_table) / sizeof(device_table[0]);
  18. static uint8_t init_ok = 0;
  19. /**
  20. * Initialize all flash device on FAL flash table
  21. *
  22. * @return result
  23. */
  24. int fal_flash_init(void)
  25. {
  26. size_t i, j, offset;
  27. if (init_ok)
  28. {
  29. return 0;
  30. }
  31. for (i = 0; i < device_table_len; i++)
  32. {
  33. assert(device_table[i]->ops.read);
  34. assert(device_table[i]->ops.write);
  35. assert(device_table[i]->ops.erase);
  36. /* init flash device on flash table */
  37. if (device_table[i]->ops.init)
  38. {
  39. device_table[i]->ops.init();
  40. }
  41. log_d("Flash device | %*.*s | addr: 0x%08lx | len: 0x%08x | blk_size: 0x%08x |initialized finish.",
  42. FAL_DEV_NAME_MAX, FAL_DEV_NAME_MAX, device_table[i]->name, device_table[i]->addr, device_table[i]->len,
  43. device_table[i]->blk_size);
  44. offset = 0;
  45. for (j = 0; j < FAL_DEV_BLK_MAX; j ++)
  46. {
  47. const struct flash_blk *blk = &device_table[i]->blocks[j];
  48. size_t blk_len = blk->count * blk->size;
  49. if (blk->count == 0 || blk->size == 0)
  50. break;
  51. if(offset > device_table[i]->len)
  52. {
  53. log_i("Flash device %*.*s: add block failed, offset %d > len %d.",
  54. FAL_DEV_NAME_MAX, FAL_DEV_NAME_MAX, device_table[i]->name, device_table[i]->addr, offset, device_table[i]->len);
  55. break;
  56. }
  57. log_d(" blk%2d | addr: 0x%08lx | len: 0x%08x | blk_size: 0x%08x |initialized finish.",
  58. j, device_table[i]->addr + offset, blk_len, blk->size);
  59. offset += blk_len;
  60. }
  61. }
  62. init_ok = 1;
  63. return 0;
  64. }
  65. /**
  66. * find flash device by name
  67. *
  68. * @param name flash device name
  69. *
  70. * @return != NULL: flash device
  71. * NULL: not found
  72. */
  73. const struct fal_flash_dev *fal_flash_device_find(const char *name)
  74. {
  75. assert(init_ok);
  76. assert(name);
  77. size_t i;
  78. for (i = 0; i < device_table_len; i++)
  79. {
  80. if (!strncmp(name, device_table[i]->name, FAL_DEV_NAME_MAX)) {
  81. return device_table[i];
  82. }
  83. }
  84. return NULL;
  85. }