SdFile.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. const uint8_t *SdFile::gfBlockBuffBegin() const {
  54. return vol_->cache()->data; // this is constant for the whole time, so it should be fast and sleek
  55. }
  56. void SdFile::gfReset(){
  57. // reset cache read ptr to its begin
  58. gfReadPtr = gfBlockBuffBegin() + gfOffset;
  59. }
  60. //FORCE_INLINE const uint8_t * find_endl(const uint8_t *p){
  61. // while( *(++p) != '\n' ); // skip until a newline is found
  62. // return p;
  63. //}
  64. // think twice before allowing this to inline - manipulating 4B longs is costly
  65. // moreover - this function has its parameters in registers only, so no heavy stack usage besides the call/ret
  66. void __attribute__((noinline)) SdFile::gfUpdateCurrentPosition(uint16_t inc){
  67. curPosition_ += inc;
  68. }
  69. #define find_endl(resultP, startP) \
  70. __asm__ __volatile__ ( \
  71. "cycle: \n" \
  72. "ld r22, Z+ \n" \
  73. "cpi r22, 0x0A \n" \
  74. "brne cycle \n" \
  75. : "=z" (resultP) /* result of the ASM code - in our case the Z register (R30:R31) */ \
  76. : "z" (startP) /* input of the ASM code - in our case the Z register as well (R30:R31) */ \
  77. : "r22" /* modifying register R22 - so that the compiler knows */ \
  78. )
  79. //size=400B
  80. // avoid calling the default heavy-weight read() for just one byte
  81. int16_t SdFile::readFilteredGcode(){
  82. if( ! gfEnsureBlock() ){
  83. goto eof_or_fail; // this is unfortunate :( ... other calls are using the cache and we can loose the data block of our gcode file
  84. }
  85. // assume, we have the 512B block cache filled and terminated with a '\n'
  86. // SERIAL_PROTOCOLPGM("Read:");
  87. // SERIAL_PROTOCOL(curPosition_);
  88. // SERIAL_PROTOCOL(':');
  89. // for(uint8_t i = 0; i < 16; ++i){
  90. // SERIAL_PROTOCOL( gfReadPtr[i] );
  91. // }
  92. // SERIAL_PROTOCOLLN();
  93. // SERIAL_PROTOCOLLN(curPosition_);
  94. {
  95. const uint8_t *start = gfReadPtr;
  96. // It may seem unreasonable to copy the variable into a local one and copy it back at the end of this method,
  97. // but there is an important point of view: the compiler is unsure whether it can optimize the reads/writes
  98. // to gfReadPtr within this method, because it is a class member variable.
  99. // The compiler cannot see, if omitting read/write won't have any incorrect side-effects to the rest of the whole FW.
  100. // So this trick explicitly states, that rdPtr is a local variable limited to the scope of this method,
  101. // therefore the compiler can omit read/write to it (keep it in registers!) as it sees fit.
  102. // And it does! Codesize dropped by 68B!
  103. const uint8_t *rdPtr = gfReadPtr;
  104. // the same applies to gfXBegin, codesize dropped another 100B!
  105. const uint8_t *blockBuffBegin = gfBlockBuffBegin();
  106. uint8_t consecutiveCommentLines = 0;
  107. while( *rdPtr == ';' ){
  108. for(;;){
  109. //while( *(++gfReadPtr) != '\n' ); // skip until a newline is found - suboptimal code!
  110. // Wondering, why this "nice while cycle" is done in such a weird way using a separate find_endl() function?
  111. // Have a look at the ASM code GCC produced!
  112. // At first - a separate find_endl() makes the compiler understand,
  113. // that I don't need to store gfReadPtr every time, I'm only interested in the final address where the '\n' was found
  114. // - the cycle can run on CPU registers only without touching memory besides reading the character being compared.
  115. // Not only makes the code run considerably faster, but is also 40B shorter!
  116. // This was the generated code:
  117. //FORCE_INLINE const uint8_t * find_endl(const uint8_t *p){
  118. // while( *(++p) != '\n' ); // skip until a newline is found
  119. // return p; }
  120. // 11c5e: movw r30, r18
  121. // 11c60: subi r18, 0xFF ; 255
  122. // 11c62: sbci r19, 0xFF ; 255
  123. // 11c64: ld r22, Z
  124. // 11c66: cpi r22, 0x0A ; 10
  125. // 11c68: brne .-12 ; 0x11c5e <get_command()+0x524>
  126. // Still, even that was suboptimal as the compiler seems not to understand the usage of ld r22, Z+ (the plus is important)
  127. // aka automatic increment of the Z register (R30:R31 pair)
  128. // There is no other way than pure ASM!
  129. find_endl(rdPtr, rdPtr);
  130. // found a newline, prepare the next block if block cache end reached
  131. if( rdPtr - blockBuffBegin > 512 ){
  132. // at the end of block cache, fill new data in
  133. gfUpdateCurrentPosition( rdPtr - start - 1 );
  134. if( ! gfComputeNextFileBlock() )goto eof_or_fail;
  135. if( ! gfEnsureBlock() )goto eof_or_fail; // fetch it into RAM
  136. rdPtr = start = blockBuffBegin;
  137. } else {
  138. if(++consecutiveCommentLines == 255){
  139. // SERIAL_PROTOCOLLN(sd->curPosition_);
  140. --rdPtr; // unget the already consumed newline
  141. goto emit_char;
  142. }
  143. // peek the next byte - we are inside the block at least at 511th index - still safe
  144. if( *rdPtr == ';' ){
  145. // consecutive comment
  146. ++consecutiveCommentLines;
  147. } else {
  148. --rdPtr; // unget the already consumed newline
  149. goto emit_char;
  150. }
  151. break; // found the real end of the line even across many blocks
  152. }
  153. }
  154. }
  155. emit_char:
  156. {
  157. gfUpdateCurrentPosition( rdPtr - start + 1 );
  158. int16_t rv = *rdPtr++;
  159. if( curPosition_ >= fileSize_ ){
  160. // past the end of file
  161. goto eof_or_fail;
  162. } else if( rdPtr - blockBuffBegin >= 512 ){
  163. // past the end of current bufferred block - prepare the next one...
  164. if( ! gfComputeNextFileBlock() )goto eof_or_fail;
  165. // don't need to force fetch the block here, it will get loaded on the next call
  166. rdPtr = blockBuffBegin;
  167. }
  168. // SERIAL_PROTOCOLPGM("c=");
  169. // SERIAL_ECHO((char)rv);
  170. // SERIAL_ECHO('|');
  171. // SERIAL_ECHO((int)rv);
  172. // SERIAL_PROTOCOL('|');
  173. // SERIAL_PROTOCOLLN(curPosition_);
  174. // save the current read ptr for the next run
  175. gfReadPtr = rdPtr;
  176. return rv;
  177. }
  178. }
  179. eof_or_fail:
  180. // SERIAL_PROTOCOLPGM("CacheFAIL:");
  181. // make the rdptr point to a safe location - end of file
  182. gfReadPtr = gfBlockBuffBegin() + 512;
  183. return -1;
  184. }
  185. //size=70B
  186. bool SdFile::gfEnsureBlock(){
  187. // SERIAL_PROTOCOLPGM("EB:");
  188. // SERIAL_PROTOCOLLN(gfBlock);
  189. if ( vol_->cacheRawBlock(gfBlock, SdVolume::CACHE_FOR_READ)){
  190. // terminate with a '\n'
  191. const uint16_t terminateOfs = fileSize_ - gfOffset;
  192. vol_->cache()->data[ terminateOfs < 512 ? terminateOfs : 512 ] = '\n';
  193. return true;
  194. } else {
  195. return false;
  196. }
  197. }
  198. //#define shr9(resultCurPos, curPos) \
  199. //__asm__ __volatile__ ( \
  200. //"asr r23 \n" \
  201. //"asr r22 \n" \
  202. //"asr r21 \n" \
  203. //"asr r20 \n" \
  204. //"ldi r20, r21 \n" \
  205. //"ldi r21, r22 \n" \
  206. //"ldi r22, r23 \n" \
  207. //"ldi r23, 0 \n" \
  208. //: "=a" (resultCurPos) \
  209. //: "a" (curPos) \
  210. //)
  211. //size=350B
  212. bool SdFile::gfComputeNextFileBlock() {
  213. // error if not open or write only
  214. if (!isOpen() || !(flags_ & O_READ)) return false;
  215. gfOffset = curPosition_ & 0X1FF; // offset in block
  216. if (type_ == FAT_FILE_TYPE_ROOT_FIXED) {
  217. // SHR by 9 means skip the last byte and shift just 3 bytes by 1
  218. // -> should be 8 instructions... and not the horrible loop shifting 4 bytes at once
  219. // still need to get some work on this
  220. gfBlock = vol_->rootDirStart() + (curPosition_ >> 9);
  221. } else {
  222. uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_);
  223. if (gfOffset == 0 && blockOfCluster == 0) {
  224. // start of new cluster
  225. if (curPosition_ == 0) {
  226. // use first cluster in file
  227. curCluster_ = firstCluster_;
  228. } else {
  229. // get next cluster from FAT
  230. if (!vol_->fatGet(curCluster_, &curCluster_)) return false;
  231. }
  232. }
  233. gfBlock = vol_->clusterStartBlock(curCluster_) + blockOfCluster;
  234. }
  235. return true;
  236. }
  237. //------------------------------------------------------------------------------
  238. /** Write data to an open file.
  239. *
  240. * \note Data is moved to the cache but may not be written to the
  241. * storage device until sync() is called.
  242. *
  243. * \param[in] buf Pointer to the location of the data to be written.
  244. *
  245. * \param[in] nbyte Number of bytes to write.
  246. *
  247. * \return For success write() returns the number of bytes written, always
  248. * \a nbyte. If an error occurs, write() returns -1. Possible errors
  249. * include write() is called before a file has been opened, write is called
  250. * for a read-only file, device is full, a corrupt file system or an I/O error.
  251. *
  252. */
  253. int16_t SdFile::write(const void* buf, uint16_t nbyte) {
  254. return SdBaseFile::write(buf, nbyte);
  255. }
  256. //------------------------------------------------------------------------------
  257. /** Write a byte to a file. Required by the Arduino Print class.
  258. * \param[in] b the byte to be written.
  259. * Use writeError to check for errors.
  260. */
  261. #if ARDUINO >= 100
  262. size_t SdFile::write(uint8_t b)
  263. {
  264. return SdBaseFile::write(&b, 1);
  265. }
  266. #else
  267. void SdFile::write(uint8_t b)
  268. {
  269. SdBaseFile::write(&b, 1);
  270. }
  271. #endif
  272. //------------------------------------------------------------------------------
  273. /** Write a string to a file. Used by the Arduino Print class.
  274. * \param[in] str Pointer to the string.
  275. * Use writeError to check for errors.
  276. */
  277. void SdFile::write(const char* str) {
  278. SdBaseFile::write(str, strlen(str));
  279. }
  280. //------------------------------------------------------------------------------
  281. /** Write a PROGMEM string to a file.
  282. * \param[in] str Pointer to the PROGMEM string.
  283. * Use writeError to check for errors.
  284. */
  285. void SdFile::write_P(PGM_P str) {
  286. for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
  287. }
  288. //------------------------------------------------------------------------------
  289. /** Write a PROGMEM string followed by CR/LF to a file.
  290. * \param[in] str Pointer to the PROGMEM string.
  291. * Use writeError to check for errors.
  292. */
  293. void SdFile::writeln_P(PGM_P str) {
  294. write_P(str);
  295. write_P(PSTR("\r\n"));
  296. }
  297. #endif