FsCache.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2011-2022 Bill Greiman
  3. * This file is part of the SdFat library for SD memory cards.
  4. *
  5. * MIT License
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a
  8. * copy of this software and associated documentation files (the "Software"),
  9. * to deal in the Software without restriction, including without limitation
  10. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  11. * and/or sell copies of the Software, and to permit persons to whom the
  12. * Software is furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included
  15. * in all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  18. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #define DBG_FILE "FsCache.cpp"
  26. #include "DebugMacros.h"
  27. #include "FsCache.h"
  28. //------------------------------------------------------------------------------
  29. uint8_t* FsCache::prepare(uint32_t sector, uint8_t option) {
  30. if (!m_blockDev) {
  31. DBG_FAIL_MACRO;
  32. goto fail;
  33. }
  34. if (m_sector != sector) {
  35. if (!sync()) {
  36. DBG_FAIL_MACRO;
  37. goto fail;
  38. }
  39. if (!(option & CACHE_OPTION_NO_READ)) {
  40. if (!m_blockDev->readSector(sector, m_buffer)) {
  41. DBG_FAIL_MACRO;
  42. goto fail;
  43. }
  44. }
  45. m_status = 0;
  46. m_sector = sector;
  47. }
  48. m_status |= option & CACHE_STATUS_MASK;
  49. return m_buffer;
  50. fail:
  51. return nullptr;
  52. }
  53. //------------------------------------------------------------------------------
  54. bool FsCache::sync() {
  55. if (m_status & CACHE_STATUS_DIRTY) {
  56. if (!m_blockDev->writeSector(m_sector, m_buffer)) {
  57. DBG_FAIL_MACRO;
  58. goto fail;
  59. }
  60. // mirror second FAT
  61. if (m_status & CACHE_STATUS_MIRROR_FAT) {
  62. uint32_t sector = m_sector + m_mirrorOffset;
  63. if (!m_blockDev->writeSector(sector, m_buffer)) {
  64. DBG_FAIL_MACRO;
  65. goto fail;
  66. }
  67. }
  68. m_status &= ~CACHE_STATUS_DIRTY;
  69. }
  70. return true;
  71. fail:
  72. return false;
  73. }