SdFile.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /* Arduino SdFat Library
  2. * Copyright (C) 2009 by William Greiman
  3. *
  4. * This file is part of the Arduino SdFat Library
  5. *
  6. * This Library is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This Library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with the Arduino SdFat Library. If not, see
  18. * <http://www.gnu.org/licenses/>.
  19. */
  20. #include "Marlin.h"
  21. #ifdef SDSUPPORT
  22. #include "SdFile.h"
  23. /** Create a file object and open it in the current working directory.
  24. *
  25. * \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
  26. *
  27. * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
  28. * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
  29. */
  30. SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) {
  31. }
  32. //size=100B
  33. bool SdFile::openFilteredGcode(SdBaseFile* dirFile, const char* path){
  34. if( open(dirFile, path, O_READ) ){
  35. // compute the block to start with
  36. if( ! gfComputeNextFileBlock() )
  37. return false;
  38. gfReset();
  39. return true;
  40. } else {
  41. return false;
  42. }
  43. }
  44. //size=90B
  45. bool SdFile::seekSetFilteredGcode(uint32_t pos){
  46. // SERIAL_PROTOCOLPGM("Seek:");
  47. // SERIAL_PROTOCOLLN(pos);
  48. if(! seekSet(pos) )return false;
  49. if(! gfComputeNextFileBlock() )return false;
  50. gfReset();
  51. return true;
  52. }
  53. //size=50B
  54. void SdFile::gfReset(){
  55. gfCachePBegin = vol_->cache()->data;
  56. // reset cache read ptr to its begin
  57. gfCacheP = gfCachePBegin + gfOffset;
  58. }
  59. //FORCE_INLINE const uint8_t * find_endl(const uint8_t *p){
  60. // while( *(++p) != '\n' ); // skip until a newline is found
  61. // return p;
  62. //}
  63. // think twice before allowing this to inline - manipulating 4B longs is costly
  64. // moreover - this function has its parameters in registers only, so no heavy stack usage besides the call/ret
  65. void __attribute__((noinline)) SdFile::gfUpdateCurrentPosition(uint16_t inc){
  66. curPosition_ += inc;
  67. }
  68. #define find_endl(resultP, startP) \
  69. __asm__ __volatile__ ( \
  70. "cycle: \n" \
  71. "ld r22, Z+ \n" \
  72. "cpi r22, 0x0A \n" \
  73. "brne cycle \n" \
  74. : "=z" (resultP) /* result of the ASM code - in our case the Z register (R30:R31) */ \
  75. : "z" (startP) /* input of the ASM code - in our case the Z register as well (R30:R31) */ \
  76. : "r22" /* modifying register R22 - so that the compiler knows */ \
  77. )
  78. //size=400B
  79. // avoid calling the default heavy-weight read() for just one byte
  80. int16_t SdFile::readFilteredGcode(){
  81. gfEnsureBlock(); // this is unfortunate :( ... other calls are using the cache and we can loose the data block of our gcode file
  82. // assume, we have the 512B block cache filled and terminated with a '\n'
  83. // SERIAL_PROTOCOLPGM("Read:");
  84. // SERIAL_PROTOCOL(curPosition_);
  85. // SERIAL_PROTOCOL(':');
  86. // for(uint8_t i = 0; i < 16; ++i){
  87. // SERIAL_PROTOCOL( gfCacheP[i] );
  88. // }
  89. // SERIAL_PROTOCOLLN();
  90. const uint8_t *start = gfCacheP;
  91. uint8_t consecutiveCommentLines = 0;
  92. while( *gfCacheP == ';' ){
  93. for(;;){
  94. //while( *(++gfCacheP) != '\n' ); // skip until a newline is found - suboptimal code!
  95. // Wondering, why this "nice while cycle" is done in such a weird way using a separate find_endl() function?
  96. // Have a look at the ASM code GCC produced!
  97. // At first - a separate find_endl() makes the compiler understand,
  98. // that I don't need to store gfCacheP every time, I'm only interested in the final address where the '\n' was found
  99. // - the cycle can run on CPU registers only without touching memory besides reading the character being compared.
  100. // Not only makes the code run considerably faster, but is also 40B shorter!
  101. // This was the generated code:
  102. //FORCE_INLINE const uint8_t * find_endl(const uint8_t *p){
  103. // while( *(++p) != '\n' ); // skip until a newline is found
  104. // return p; }
  105. // 11c5e: movw r30, r18
  106. // 11c60: subi r18, 0xFF ; 255
  107. // 11c62: sbci r19, 0xFF ; 255
  108. // 11c64: ld r22, Z
  109. // 11c66: cpi r22, 0x0A ; 10
  110. // 11c68: brne .-12 ; 0x11c5e <get_command()+0x524>
  111. // Still, even that was suboptimal as the compiler seems not to understand the usage of ld r22, Z+ (the plus is important)
  112. // aka automatic increment of the Z register (R30:R31 pair)
  113. // There is no other way than pure ASM!
  114. find_endl(gfCacheP, gfCacheP);
  115. // found a newline, prepare the next block if block cache end reached
  116. if( gfCacheP - gfCachePBegin > 512 ){
  117. // at the end of block cache, fill new data in
  118. gfUpdateCurrentPosition( gfCacheP - start - 1 );
  119. if( ! gfComputeNextFileBlock() )goto fail;
  120. gfEnsureBlock(); // fetch it into RAM
  121. gfCacheP = start = gfCachePBegin;
  122. } else {
  123. if(++consecutiveCommentLines == 255){
  124. // SERIAL_PROTOCOLLN(sd->curPosition_);
  125. --gfCacheP; // unget the already consumed newline
  126. goto forceExit;
  127. }
  128. // peek the next byte - we are inside the block at least at 511th index - still safe
  129. if( *gfCacheP == ';' ){
  130. // consecutive comment
  131. ++consecutiveCommentLines;
  132. } else {
  133. --gfCacheP; // unget the already consumed newline
  134. goto forceExit;
  135. }
  136. break; // found the real end of the line even across many blocks
  137. }
  138. }
  139. }
  140. forceExit:
  141. {
  142. gfUpdateCurrentPosition( gfCacheP - start + 1 );
  143. int16_t rv = *gfCacheP++;
  144. // prepare next block if needed
  145. if( gfCacheP - gfCachePBegin >= 512 ){
  146. // speed checking - now at roughly 170KB/s which is much closer to raw read speed of SD card blocks at ~250KB/s
  147. // SERIAL_PROTOCOL(millis2());
  148. // SERIAL_PROTOCOL(':');
  149. // SERIAL_PROTOCOLLN(curPosition_);
  150. if( ! gfComputeNextFileBlock() )goto fail;
  151. // don't need to force fetch the block here, it will get loaded on the next call
  152. gfCacheP = gfCachePBegin;
  153. }
  154. return rv;
  155. }
  156. fail:
  157. // SERIAL_PROTOCOLLNPGM("CacheFAIL");
  158. return -1;
  159. }
  160. //size=70B
  161. bool SdFile::gfEnsureBlock(){
  162. // SERIAL_PROTOCOLPGM("EB:");
  163. // SERIAL_PROTOCOLLN(gfBlock);
  164. if ( vol_->cacheRawBlock(gfBlock, SdVolume::CACHE_FOR_READ)){
  165. // terminate with a '\n'
  166. const uint16_t terminateOfs = fileSize_ - gfOffset;
  167. vol_->cache()->data[ terminateOfs < 512 ? terminateOfs : 512 ] = '\n';
  168. return true;
  169. } else {
  170. return false;
  171. }
  172. }
  173. //#define shr9(resultCurPos, curPos) \
  174. //__asm__ __volatile__ ( \
  175. //"asr r23 \n" \
  176. //"asr r22 \n" \
  177. //"asr r21 \n" \
  178. //"asr r20 \n" \
  179. //"ldi r20, r21 \n" \
  180. //"ldi r21, r22 \n" \
  181. //"ldi r22, r23 \n" \
  182. //"ldi r23, 0 \n" \
  183. //: "=a" (resultCurPos) \
  184. //: "a" (curPos) \
  185. //)
  186. //size=350B
  187. bool SdFile::gfComputeNextFileBlock() {
  188. // error if not open or write only
  189. if (!isOpen() || !(flags_ & O_READ)) return false;
  190. gfOffset = curPosition_ & 0X1FF; // offset in block
  191. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  192. // SHR by 9 means skip the last byte and shift just 3 bytes by 1
  193. // -> should be 8 instructions... and not the horrible loop shifting 4 bytes at once
  194. // still need to get some work on this
  195. gfBlock = vol_->rootDirStart() + (curPosition_ >> 9);
  196. } else {
  197. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  198. if (gfOffset == 0 && blockOfCluster == 0) {
  199. // start of new cluster
  200. if (curPosition_ == 0) {
  201. // use first cluster in file
  202. curCluster_ = firstCluster_;
  203. } else {
  204. // get next cluster from FAT
  205. if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
  206. }
  207. }
  208. gfBlock = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  209. }
  210. return true;
  211. }
  212. //------------------------------------------------------------------------------
  213. /** Write data to an open file.
  214. *
  215. * \note Data is moved to the cache but may not be written to the
  216. * storage device until sync() is called.
  217. *
  218. * \param[in] buf Pointer to the location of the data to be written.
  219. *
  220. * \param[in] nbyte Number of bytes to write.
  221. *
  222. * \return For success write() returns the number of bytes written, always
  223. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  224. * include write() is called before a file has been opened, write is called
  225. * for a read-only file, device is full, a corrupt file system or an I/O error.
  226. *
  227. */
  228. int16_t SdFile::write(const void* buf, uint16_t nbyte) {
  229. return SdBaseFile::write(buf, nbyte);
  230. }
  231. //------------------------------------------------------------------------------
  232. /** Write a byte to a file. Required by the Arduino Print class.
  233. * \param[in] b the byte to be written.
  234. * Use writeError to check for errors.
  235. */
  236. #if ARDUINO >= 100
  237. size_t SdFile::write(uint8_t b)
  238. {
  239. return SdBaseFile::write(&b, 1);
  240. }
  241. #else
  242. void SdFile::write(uint8_t b)
  243. {
  244. SdBaseFile::write(&b, 1);
  245. }
  246. #endif
  247. //------------------------------------------------------------------------------
  248. /** Write a string to a file. Used by the Arduino Print class.
  249. * \param[in] str Pointer to the string.
  250. * Use writeError to check for errors.
  251. */
  252. void SdFile::write(const char* str) {
  253. SdBaseFile::write(str, strlen(str));
  254. }
  255. //------------------------------------------------------------------------------
  256. /** Write a PROGMEM string to a file.
  257. * \param[in] str Pointer to the PROGMEM string.
  258. * Use writeError to check for errors.
  259. */
  260. void SdFile::write_P(PGM_P str) {
  261. for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
  262. }
  263. //------------------------------------------------------------------------------
  264. /** Write a PROGMEM string followed by CR/LF to a file.
  265. * \param[in] str Pointer to the PROGMEM string.
  266. * Use writeError to check for errors.
  267. */
  268. void SdFile::writeln_P(PGM_P str) {
  269. write_P(str);
  270. write_P(PSTR("\r\n"));
  271. }
  272. #endif