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

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