drv_flash.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (c) 2006-2023, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-10-19 ChuShicheng first version
  9. */
  10. #include "drv_flash.h"
  11. #include "board.h"
  12. #include "hardware/flash.h"
  13. #ifdef BSP_USING_ON_CHIP_FLASH
  14. #define DBG_LEVEL DBG_LOG
  15. #define LOG_TAG "DRV.FLASH"
  16. #include <rtdbg.h>
  17. #define FLASH_SIZE 2 * 1024 * 1024
  18. #define FLASH_START_ADRESS 0x0000000
  19. int _flash_read(rt_uint32_t addr, rt_uint8_t *buf, size_t size)
  20. {
  21. rt_memcpy(buf, (const void *)(XIP_BASE + addr), size);
  22. return size;
  23. }
  24. int _flash_write(rt_uint32_t addr, const rt_uint8_t *buf, size_t size)
  25. {
  26. if (addr % FLASH_PAGE_SIZE != 0)
  27. {
  28. LOG_E("write addr must be %d-byte alignment", FLASH_PAGE_SIZE);
  29. return -RT_EINVAL;
  30. }
  31. if (size % FLASH_PAGE_SIZE != 0)
  32. {
  33. LOG_E("write size must be %d-byte alignment", FLASH_PAGE_SIZE);
  34. return -RT_EINVAL;
  35. }
  36. flash_range_program(addr, buf, size);
  37. return size;
  38. }
  39. int _flash_erase(rt_uint32_t addr, size_t size)
  40. {
  41. if(size % FLASH_SECTOR_SIZE)
  42. {
  43. LOG_E("erase size must be %d-byte alignment", FLASH_SECTOR_SIZE);
  44. }
  45. flash_range_erase(addr, size);
  46. return size;
  47. }
  48. #ifdef RT_USING_FAL
  49. #include "fal.h"
  50. static int fal_flash_read(long offset, rt_uint8_t *buf, size_t size);
  51. static int fal_flash_write(long offset, const rt_uint8_t *buf, size_t size);
  52. static int fal_flash_erase(long offset, size_t size);
  53. const struct fal_flash_dev _onchip_flash =
  54. {
  55. "onchip_flash",
  56. FLASH_START_ADRESS,
  57. FLASH_SIZE,
  58. FLASH_PAGE_SIZE,
  59. {
  60. NULL,
  61. fal_flash_read,
  62. fal_flash_write,
  63. fal_flash_erase
  64. }
  65. };
  66. static int fal_flash_read(long offset, rt_uint8_t *buf, size_t size)
  67. {
  68. return _flash_read(_onchip_flash.addr + offset, buf, size);
  69. }
  70. static int fal_flash_write(long offset, const rt_uint8_t *buf, size_t size)
  71. {
  72. return _flash_write(_onchip_flash.addr + offset, buf, size);
  73. }
  74. static int fal_flash_erase(long offset, size_t size)
  75. {
  76. return _flash_erase(_onchip_flash.addr + offset, size);
  77. }
  78. static int rt_hw_on_chip_flash_init(void)
  79. {
  80. fal_init();
  81. return RT_EOK;
  82. }
  83. INIT_COMPONENT_EXPORT(rt_hw_on_chip_flash_init);
  84. #endif /* RT_USING_FAL */
  85. #endif /* BSP_USING_ON_CHIP_FLASH */