My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SdVolume.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * sd/SdVolume.cpp
  24. *
  25. * Arduino SdFat Library
  26. * Copyright (c) 2009 by William Greiman
  27. *
  28. * This file is part of the Arduino Sd2Card Library
  29. */
  30. #include "../inc/MarlinConfig.h"
  31. #if ENABLED(SDSUPPORT)
  32. #include "SdVolume.h"
  33. #include "../MarlinCore.h"
  34. #if !USE_MULTIPLE_CARDS
  35. // raw block cache
  36. uint32_t SdVolume::cacheBlockNumber_; // current block number
  37. cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card
  38. Sd2Card* SdVolume::sdCard_; // pointer to SD card object
  39. bool SdVolume::cacheDirty_; // cacheFlush() will write block if true
  40. uint32_t SdVolume::cacheMirrorBlock_; // mirror block for second FAT
  41. #endif // USE_MULTIPLE_CARDS
  42. // find a contiguous group of clusters
  43. bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) {
  44. if (ENABLED(SDCARD_READONLY)) return false;
  45. // start of group
  46. uint32_t bgnCluster;
  47. // end of group
  48. uint32_t endCluster;
  49. // last cluster of FAT
  50. uint32_t fatEnd = clusterCount_ + 1;
  51. // flag to save place to start next search
  52. bool setStart;
  53. // set search start cluster
  54. if (*curCluster) {
  55. // try to make file contiguous
  56. bgnCluster = *curCluster + 1;
  57. // don't save new start location
  58. setStart = false;
  59. }
  60. else {
  61. // start at likely place for free cluster
  62. bgnCluster = allocSearchStart_;
  63. // save next search start if one cluster
  64. setStart = count == 1;
  65. }
  66. // end of group
  67. endCluster = bgnCluster;
  68. // search the FAT for free clusters
  69. for (uint32_t n = 0;; n++, endCluster++) {
  70. // can't find space checked all clusters
  71. if (n >= clusterCount_) return false;
  72. // past end - start from beginning of FAT
  73. if (endCluster > fatEnd) {
  74. bgnCluster = endCluster = 2;
  75. }
  76. uint32_t f;
  77. if (!fatGet(endCluster, &f)) return false;
  78. if (f != 0) {
  79. // cluster in use try next cluster as bgnCluster
  80. bgnCluster = endCluster + 1;
  81. }
  82. else if ((endCluster - bgnCluster + 1) == count) {
  83. // done - found space
  84. break;
  85. }
  86. }
  87. // mark end of chain
  88. if (!fatPutEOC(endCluster)) return false;
  89. // link clusters
  90. while (endCluster > bgnCluster) {
  91. if (!fatPut(endCluster - 1, endCluster)) return false;
  92. endCluster--;
  93. }
  94. if (*curCluster != 0) {
  95. // connect chains
  96. if (!fatPut(*curCluster, bgnCluster)) return false;
  97. }
  98. // return first cluster number to caller
  99. *curCluster = bgnCluster;
  100. // remember possible next free cluster
  101. if (setStart) allocSearchStart_ = bgnCluster + 1;
  102. return true;
  103. }
  104. bool SdVolume::cacheFlush() {
  105. #if DISABLED(SDCARD_READONLY)
  106. if (cacheDirty_) {
  107. if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data))
  108. return false;
  109. // mirror FAT tables
  110. if (cacheMirrorBlock_) {
  111. if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data))
  112. return false;
  113. cacheMirrorBlock_ = 0;
  114. }
  115. cacheDirty_ = 0;
  116. }
  117. #endif
  118. return true;
  119. }
  120. bool SdVolume::cacheRawBlock(uint32_t blockNumber, bool dirty) {
  121. if (cacheBlockNumber_ != blockNumber) {
  122. if (!cacheFlush()) return false;
  123. if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) return false;
  124. cacheBlockNumber_ = blockNumber;
  125. }
  126. if (dirty) cacheDirty_ = true;
  127. return true;
  128. }
  129. // return the size in bytes of a cluster chain
  130. bool SdVolume::chainSize(uint32_t cluster, uint32_t* size) {
  131. uint32_t s = 0;
  132. do {
  133. if (!fatGet(cluster, &cluster)) return false;
  134. s += 512UL << clusterSizeShift_;
  135. } while (!isEOC(cluster));
  136. *size = s;
  137. return true;
  138. }
  139. // Fetch a FAT entry
  140. bool SdVolume::fatGet(uint32_t cluster, uint32_t* value) {
  141. uint32_t lba;
  142. if (cluster > (clusterCount_ + 1)) return false;
  143. if (FAT12_SUPPORT && fatType_ == 12) {
  144. uint16_t index = cluster;
  145. index += index >> 1;
  146. lba = fatStartBlock_ + (index >> 9);
  147. if (!cacheRawBlock(lba, CACHE_FOR_READ)) return false;
  148. index &= 0x1FF;
  149. uint16_t tmp = cacheBuffer_.data[index];
  150. index++;
  151. if (index == 512) {
  152. if (!cacheRawBlock(lba + 1, CACHE_FOR_READ)) return false;
  153. index = 0;
  154. }
  155. tmp |= cacheBuffer_.data[index] << 8;
  156. *value = cluster & 1 ? tmp >> 4 : tmp & 0xFFF;
  157. return true;
  158. }
  159. if (fatType_ == 16)
  160. lba = fatStartBlock_ + (cluster >> 8);
  161. else if (fatType_ == 32)
  162. lba = fatStartBlock_ + (cluster >> 7);
  163. else
  164. return false;
  165. if (lba != cacheBlockNumber_ && !cacheRawBlock(lba, CACHE_FOR_READ))
  166. return false;
  167. *value = (fatType_ == 16) ? cacheBuffer_.fat16[cluster & 0xFF] : (cacheBuffer_.fat32[cluster & 0x7F] & FAT32MASK);
  168. return true;
  169. }
  170. // Store a FAT entry
  171. bool SdVolume::fatPut(uint32_t cluster, uint32_t value) {
  172. if (ENABLED(SDCARD_READONLY)) return false;
  173. uint32_t lba;
  174. // error if reserved cluster
  175. if (cluster < 2) return false;
  176. // error if not in FAT
  177. if (cluster > (clusterCount_ + 1)) return false;
  178. if (FAT12_SUPPORT && fatType_ == 12) {
  179. uint16_t index = cluster;
  180. index += index >> 1;
  181. lba = fatStartBlock_ + (index >> 9);
  182. if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false;
  183. // mirror second FAT
  184. if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
  185. index &= 0x1FF;
  186. uint8_t tmp = value;
  187. if (cluster & 1) {
  188. tmp = (cacheBuffer_.data[index] & 0xF) | tmp << 4;
  189. }
  190. cacheBuffer_.data[index] = tmp;
  191. index++;
  192. if (index == 512) {
  193. lba++;
  194. index = 0;
  195. if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false;
  196. // mirror second FAT
  197. if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
  198. }
  199. tmp = value >> 4;
  200. if (!(cluster & 1)) {
  201. tmp = ((cacheBuffer_.data[index] & 0xF0)) | tmp >> 4;
  202. }
  203. cacheBuffer_.data[index] = tmp;
  204. return true;
  205. }
  206. if (fatType_ == 16)
  207. lba = fatStartBlock_ + (cluster >> 8);
  208. else if (fatType_ == 32)
  209. lba = fatStartBlock_ + (cluster >> 7);
  210. else
  211. return false;
  212. if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) return false;
  213. // store entry
  214. if (fatType_ == 16)
  215. cacheBuffer_.fat16[cluster & 0xFF] = value;
  216. else
  217. cacheBuffer_.fat32[cluster & 0x7F] = value;
  218. // mirror second FAT
  219. if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_;
  220. return true;
  221. }
  222. // free a cluster chain
  223. bool SdVolume::freeChain(uint32_t cluster) {
  224. // clear free cluster location
  225. allocSearchStart_ = 2;
  226. do {
  227. uint32_t next;
  228. if (!fatGet(cluster, &next)) return false;
  229. // free cluster
  230. if (!fatPut(cluster, 0)) return false;
  231. cluster = next;
  232. } while (!isEOC(cluster));
  233. return true;
  234. }
  235. /** Volume free space in clusters.
  236. *
  237. * \return Count of free clusters for success or -1 if an error occurs.
  238. */
  239. int32_t SdVolume::freeClusterCount() {
  240. uint32_t free = 0;
  241. uint16_t n;
  242. uint32_t todo = clusterCount_ + 2;
  243. if (fatType_ == 16)
  244. n = 256;
  245. else if (fatType_ == 32)
  246. n = 128;
  247. else // put FAT12 here
  248. return -1;
  249. for (uint32_t lba = fatStartBlock_; todo; todo -= n, lba++) {
  250. if (!cacheRawBlock(lba, CACHE_FOR_READ)) return -1;
  251. NOMORE(n, todo);
  252. if (fatType_ == 16) {
  253. for (uint16_t i = 0; i < n; i++)
  254. if (cacheBuffer_.fat16[i] == 0) free++;
  255. }
  256. else {
  257. for (uint16_t i = 0; i < n; i++)
  258. if (cacheBuffer_.fat32[i] == 0) free++;
  259. }
  260. #ifdef ESP32
  261. // Needed to reset the idle task watchdog timer on ESP32 as reading the complete FAT may easily
  262. // block for 10+ seconds. yield() is insufficient since it blocks lower prio tasks (e.g., idle).
  263. static millis_t nextTaskTime = 0;
  264. const millis_t ms = millis();
  265. if (ELAPSED(ms, nextTaskTime)) {
  266. vTaskDelay(1); // delay 1 tick (Minimum. Usually 10 or 1 ms depending on skdconfig.h)
  267. nextTaskTime = ms + 1000; // tickle the task manager again in 1 second
  268. }
  269. #endif // ESP32
  270. }
  271. return free;
  272. }
  273. /** Initialize a FAT volume.
  274. *
  275. * \param[in] dev The SD card where the volume is located.
  276. *
  277. * \param[in] part The partition to be used. Legal values for \a part are
  278. * 1-4 to use the corresponding partition on a device formatted with
  279. * a MBR, Master Boot Record, or zero if the device is formatted as
  280. * a super floppy with the FAT boot sector in block zero.
  281. *
  282. * \return true for success, false for failure.
  283. * Reasons for failure include not finding a valid partition, not finding a valid
  284. * FAT file system in the specified partition or an I/O error.
  285. */
  286. bool SdVolume::init(Sd2Card* dev, uint8_t part) {
  287. uint32_t totalBlocks, volumeStartBlock = 0;
  288. fat32_boot_t* fbs;
  289. sdCard_ = dev;
  290. fatType_ = 0;
  291. allocSearchStart_ = 2;
  292. cacheDirty_ = 0; // cacheFlush() will write block if true
  293. cacheMirrorBlock_ = 0;
  294. cacheBlockNumber_ = 0xFFFFFFFF;
  295. // if part == 0 assume super floppy with FAT boot sector in block zero
  296. // if part > 0 assume mbr volume with partition table
  297. if (part) {
  298. if (part > 4) return false;
  299. if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false;
  300. part_t* p = &cacheBuffer_.mbr.part[part - 1];
  301. if ((p->boot & 0x7F) != 0 || p->totalSectors < 100 || p->firstSector == 0)
  302. return false; // not a valid partition
  303. volumeStartBlock = p->firstSector;
  304. }
  305. if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) return false;
  306. fbs = &cacheBuffer_.fbs32;
  307. if (fbs->bytesPerSector != 512 ||
  308. fbs->fatCount == 0 ||
  309. fbs->reservedSectorCount == 0 ||
  310. fbs->sectorsPerCluster == 0) {
  311. // not valid FAT volume
  312. return false;
  313. }
  314. fatCount_ = fbs->fatCount;
  315. blocksPerCluster_ = fbs->sectorsPerCluster;
  316. // determine shift that is same as multiply by blocksPerCluster_
  317. clusterSizeShift_ = 0;
  318. while (blocksPerCluster_ != _BV(clusterSizeShift_)) {
  319. // error if not power of 2
  320. if (clusterSizeShift_++ > 7) return false;
  321. }
  322. blocksPerFat_ = fbs->sectorsPerFat16 ?
  323. fbs->sectorsPerFat16 : fbs->sectorsPerFat32;
  324. fatStartBlock_ = volumeStartBlock + fbs->reservedSectorCount;
  325. // count for FAT16 zero for FAT32
  326. rootDirEntryCount_ = fbs->rootDirEntryCount;
  327. // directory start for FAT16 dataStart for FAT32
  328. rootDirStart_ = fatStartBlock_ + fbs->fatCount * blocksPerFat_;
  329. // data start for FAT16 and FAT32
  330. dataStartBlock_ = rootDirStart_ + ((32 * fbs->rootDirEntryCount + 511) / 512);
  331. // total blocks for FAT16 or FAT32
  332. totalBlocks = fbs->totalSectors16 ?
  333. fbs->totalSectors16 : fbs->totalSectors32;
  334. // total data blocks
  335. clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock);
  336. // divide by cluster size to get cluster count
  337. clusterCount_ >>= clusterSizeShift_;
  338. // FAT type is determined by cluster count
  339. if (clusterCount_ < 4085) {
  340. fatType_ = 12;
  341. if (!FAT12_SUPPORT) return false;
  342. }
  343. else if (clusterCount_ < 65525)
  344. fatType_ = 16;
  345. else {
  346. rootDirStart_ = fbs->fat32RootCluster;
  347. fatType_ = 32;
  348. }
  349. return true;
  350. }
  351. #endif // SDSUPPORT