sector_cache.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "sector_cache.h"
  2. #include <stddef.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <furi.h>
  6. #include <furi_hal_memory.h>
  7. #define SECTOR_SIZE 512
  8. #define N_SECTORS 8
  9. #define TAG "SDCache"
  10. typedef struct {
  11. uint32_t itr;
  12. uint32_t sectors[N_SECTORS];
  13. uint8_t sector_data[N_SECTORS][SECTOR_SIZE];
  14. } SectorCache;
  15. static SectorCache* cache = NULL;
  16. void sector_cache_init() {
  17. if(cache == NULL) {
  18. // TODO: tuneup allocation order, to place cache in mem pool (MEM2)
  19. cache = memmgr_alloc_from_pool(sizeof(SectorCache));
  20. }
  21. if(cache != NULL) {
  22. FURI_LOG_I(TAG, "Init");
  23. memset(cache, 0, sizeof(SectorCache));
  24. } else {
  25. FURI_LOG_E(TAG, "Init failed");
  26. }
  27. }
  28. uint8_t* sector_cache_get(uint32_t n_sector) {
  29. if(cache != NULL && n_sector != 0) {
  30. for(int sector_i = 0; sector_i < N_SECTORS; ++sector_i) {
  31. if(cache->sectors[sector_i] == n_sector) {
  32. return cache->sector_data[sector_i];
  33. }
  34. }
  35. }
  36. return NULL;
  37. }
  38. void sector_cache_put(uint32_t n_sector, uint8_t* data) {
  39. if(cache == NULL) return;
  40. cache->sectors[cache->itr % N_SECTORS] = n_sector;
  41. memcpy(cache->sector_data[cache->itr % N_SECTORS], data, SECTOR_SIZE);
  42. cache->itr++;
  43. }
  44. void sector_cache_invalidate_range(uint32_t start_sector, uint32_t end_sector) {
  45. if(cache == NULL) return;
  46. for(int sector_i = 0; sector_i < N_SECTORS; ++sector_i) {
  47. if((cache->sectors[sector_i] >= start_sector) &&
  48. (cache->sectors[sector_i] <= end_sector)) {
  49. cache->sectors[sector_i] = 0;
  50. }
  51. }
  52. }