SdFile.cpp 11 KB

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