ff.c 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - FAT file system module R0.06 (C)ChaN, 2008
  3. /-----------------------------------------------------------------------------/
  4. / The FatFs module is an experimenal project to implement FAT file system to
  5. / cheap microcontrollers. This is a free software and is opened for education,
  6. / research and development under license policy of following trems.
  7. /
  8. / Copyright (C) 2008, ChaN, all right reserved.
  9. /
  10. / * The FatFs module is a free software and there is no warranty.
  11. / * You can use, modify and/or redistribute it for personal, non-profit or
  12. / * commercial use without restriction under your responsibility.
  13. / * Redistributions of source code must retain the above copyright notice.
  14. /
  15. /---------------------------------------------------------------------------/
  16. / Feb 26, 2006 R0.00 Prototype.
  17. /
  18. / Apr 29, 2006 R0.01 First stable version.
  19. /
  20. / Jun 01, 2006 R0.02 Added FAT12 support.
  21. / Removed unbuffered mode.
  22. / Fixed a problem on small (<32M) patition.
  23. / Jun 10, 2006 R0.02a Added a configuration option (_FS_MINIMUM).
  24. /
  25. / Sep 22, 2006 R0.03 Added f_rename().
  26. / Changed option _FS_MINIMUM to _FS_MINIMIZE.
  27. / Dec 11, 2006 R0.03a Improved cluster scan algolithm to write files fast.
  28. / Fixed f_mkdir() creates incorrect directory on FAT32.
  29. /
  30. / Feb 04, 2007 R0.04 Supported multiple drive system.
  31. / Changed some interfaces for multiple drive system.
  32. / Changed f_mountdrv() to f_mount().
  33. / Added f_mkfs().
  34. / Apr 01, 2007 R0.04a Supported multiple partitions on a plysical drive.
  35. / Added a capability of extending file size to f_lseek().
  36. / Added minimization level 3.
  37. / Fixed an endian sensitive code in f_mkfs().
  38. / May 05, 2007 R0.04b Added a configuration option _USE_NTFLAG.
  39. / Added FSInfo support.
  40. / Fixed DBCS name can result FR_INVALID_NAME.
  41. / Fixed short seek (<= csize) collapses the file object.
  42. /
  43. / Aug 25, 2007 R0.05 Changed arguments of f_read(), f_write() and f_mkfs().
  44. / Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
  45. / Fixed f_mkdir() on FAT32 creates incorrect directory.
  46. / Feb 03, 2008 R0.05a Added f_truncate() and f_utime().
  47. / Fixed off by one error at FAT sub-type determination.
  48. / Fixed btr in f_read() can be mistruncated.
  49. / Fixed cached sector is not flushed when create and close
  50. / without write.
  51. /
  52. / Apr 01, 2008 R0.06 Added fputc(), fputs(), fprintf() and fgets().
  53. / Improved performance of f_lseek() on moving to the same
  54. / or following cluster.
  55. /---------------------------------------------------------------------------*/
  56. #include <avr/pgmspace.h>
  57. #include <string.h>
  58. #include "config.h"
  59. #include "ff.h" /* FatFs declarations */
  60. #include "diskio.h" /* Include file for user provided disk functions */
  61. #include "uart.h"
  62. #include "fpga.h"
  63. /*--------------------------------------------------------------------------
  64. Module Private Functions
  65. ---------------------------------------------------------------------------*/
  66. #if _USE_DRIVE_PREFIX != 0
  67. static
  68. FATFS *FatFs[_LOGICAL_DRIVES]; /* Pointer to the file system objects (logical drives) */
  69. #endif
  70. //static
  71. //WORD fsid; /* File system mount ID */
  72. #if _USE_LFN!=0
  73. static const PROGMEM
  74. BYTE LFN_pos[13]={1,3,5,7,9,14,16,18,20,22,24,28,30};
  75. #endif
  76. #if _USE_1_BUF != 0
  77. # define FSBUF static_buf
  78. static
  79. BUF static_buf;
  80. #else
  81. # define FSBUF (fs->buf)
  82. #endif
  83. #if _USE_FS_BUF != 0
  84. # define FPBUF FSBUF
  85. #else
  86. # define FPBUF (fp->buf)
  87. #endif
  88. /*-----------------------------------------------------------------------*/
  89. /* Change window offset */
  90. /*-----------------------------------------------------------------------*/
  91. static
  92. BOOL move_window ( /* TRUE: successful, FALSE: failed */
  93. FATFS *fs, /* File system object */
  94. BUF *buf,
  95. DWORD sector /* Sector number to make apperance in the fs->buf.data[] */
  96. ) /* Move to zero only writes back dirty window */
  97. {
  98. DWORD wsect;
  99. #if _USE_1_BUF != 0
  100. FATFS* ofs = buf->fs;
  101. #else
  102. #define ofs fs
  103. #endif
  104. wsect = buf->sect;
  105. #if _USE_1_BUF != 0
  106. if (wsect != sector || fs != ofs) { /* Changed current window */
  107. #else
  108. if (wsect != sector) { /* Changed current window */
  109. #endif
  110. #if !_FS_READONLY
  111. BYTE n;
  112. if (buf->dirty) { /* Write back dirty window if needed */
  113. if (disk_write(ofs->drive, buf->data, wsect, 1) != RES_OK)
  114. return FALSE;
  115. buf->dirty = FALSE;
  116. if (wsect < (ofs->fatbase + ofs->sects_fat)) { /* In FAT area */
  117. for (n = ofs->n_fats; n >= 2; n--) { /* Reflect the change to FAT copy */
  118. wsect += ofs->sects_fat;
  119. disk_write(ofs->drive, buf->data, wsect, 1);
  120. }
  121. }
  122. }
  123. #endif
  124. if (sector) {
  125. if (disk_read(fs->drive, buf->data, sector, 1) != RES_OK)
  126. return FALSE;
  127. buf->sect = sector;
  128. #if _USE_1_BUF != 0
  129. buf->fs=fs;
  130. #endif
  131. }
  132. }
  133. return TRUE;
  134. }
  135. static
  136. BOOL move_fs_window(
  137. FATFS* fs,
  138. DWORD sector
  139. )
  140. {
  141. return move_window(fs,&FSBUF,sector);
  142. }
  143. static
  144. BOOL move_fp_window(
  145. FIL* fp,
  146. DWORD sector
  147. )
  148. {
  149. return move_window(fp->fs,&FPBUF,sector);
  150. }
  151. /*-----------------------------------------------------------------------*/
  152. /* Clean-up cached data */
  153. /*-----------------------------------------------------------------------*/
  154. #if !_FS_READONLY
  155. static
  156. FRESULT sync ( /* FR_OK: successful, FR_RW_ERROR: failed */
  157. FATFS *fs /* File system object */
  158. )
  159. {
  160. FSBUF.dirty = TRUE;
  161. if (!move_fs_window(fs, 0)) return FR_RW_ERROR;
  162. #if _USE_FSINFO
  163. /* Update FSInfo sector if needed */
  164. if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
  165. FSBUF.sect = 0;
  166. memset(FSBUF.data, 0, 512);
  167. ST_WORD(&FSBUF.data[BS_55AA], 0xAA55);
  168. ST_DWORD(&FSBUF.data[FSI_LeadSig], 0x41615252);
  169. ST_DWORD(&FSBUF.data[FSI_StrucSig], 0x61417272);
  170. ST_DWORD(&FSBUF.data[FSI_Free_Count], fs->free_clust);
  171. ST_DWORD(&FSBUF.data[FSI_Nxt_Free], fs->last_clust);
  172. disk_write(fs->drive, FSBUF.data, fs->fsi_sector, 1);
  173. fs->fsi_flag = 0;
  174. }
  175. #endif
  176. /* Make sure that no pending write process in the physical drive */
  177. if (disk_ioctl(fs->drive, CTRL_SYNC, NULL) != RES_OK)
  178. return FR_RW_ERROR;
  179. return FR_OK;
  180. }
  181. #endif
  182. /*-----------------------------------------------------------------------*/
  183. /* Get a cluster status */
  184. /*-----------------------------------------------------------------------*/
  185. static
  186. DWORD get_cluster ( /* 0,>=2: successful, 1: failed */
  187. FATFS *fs, /* File system object */
  188. DWORD clust /* Cluster# to get the link information */
  189. )
  190. {
  191. WORD wc, bc;
  192. DWORD fatsect;
  193. if (clust >= 2 && clust < fs->max_clust) { /* Is it a valid cluster#? */
  194. fatsect = fs->fatbase;
  195. switch (fs->fs_type) {
  196. case FS_FAT12 :
  197. bc = (WORD)clust * 3 / 2;
  198. if (!move_fs_window(fs, fatsect + (bc / SS(fs)))) break;
  199. wc = FSBUF.data[bc & (SS(fs) - 1)]; bc++;
  200. if (!move_fs_window(fs, fatsect + (bc / SS(fs)))) break;
  201. wc |= (WORD)FSBUF.data[bc & (SS(fs) - 1)] << 8;
  202. return (clust & 1) ? (wc >> 4) : (wc & 0xFFF);
  203. case FS_FAT16 :
  204. if (!move_fs_window(fs, fatsect + (clust / (SS(fs) / 2)))) break;
  205. return LD_WORD(&FSBUF.data[((WORD)clust * 2) & (SS(fs) - 1)]);
  206. case FS_FAT32 :
  207. if (!move_fs_window(fs, fatsect + (clust / (SS(fs) / 4)))) break;
  208. return LD_DWORD(&FSBUF.data[((WORD)clust * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF;
  209. }
  210. }
  211. return 1; /* Out of cluster range, or an error occured */
  212. }
  213. /*-----------------------------------------------------------------------*/
  214. /* Change a cluster status */
  215. /*-----------------------------------------------------------------------*/
  216. #if !_FS_READONLY
  217. static
  218. BOOL put_cluster ( /* TRUE: successful, FALSE: failed */
  219. FATFS *fs, /* File system object */
  220. DWORD clust, /* Cluster# to change (must be 2 to fs->max_clust-1) */
  221. DWORD val /* New value to mark the cluster */
  222. )
  223. {
  224. WORD bc;
  225. BYTE *p;
  226. DWORD fatsect;
  227. fatsect = fs->fatbase;
  228. switch (fs->fs_type) {
  229. case FS_FAT12 :
  230. bc = (WORD)clust * 3 / 2;
  231. if (!move_fs_window(fs, fatsect + (bc / SS(fs)))) return FALSE;
  232. p = &FSBUF.data[bc & (SS(fs) - 1)];
  233. *p = (clust & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  234. bc++;
  235. FSBUF.dirty = TRUE;
  236. if (!move_fs_window(fs, fatsect + (bc / SS(fs)))) return FALSE;
  237. p = &FSBUF.data[bc & (SS(fs) - 1)];
  238. *p = (clust & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  239. break;
  240. case FS_FAT16 :
  241. if (!move_fs_window(fs, fatsect + (clust / (SS(fs) / 2)))) return FALSE;
  242. ST_WORD(&FSBUF.data[((WORD)clust * 2) & (SS(fs) - 1)], (WORD)val);
  243. break;
  244. case FS_FAT32 :
  245. if (!move_fs_window(fs, fatsect + (clust / (SS(fs) / 4)))) return FALSE;
  246. ST_DWORD(&FSBUF.data[((WORD)clust * 4) & (SS(fs) - 1)], val);
  247. break;
  248. default :
  249. return FALSE;
  250. }
  251. FSBUF.dirty = TRUE;
  252. return TRUE;
  253. }
  254. #endif /* !_FS_READONLY */
  255. /*-----------------------------------------------------------------------*/
  256. /* Remove a cluster chain */
  257. /*-----------------------------------------------------------------------*/
  258. #if !_FS_READONLY
  259. static
  260. BOOL remove_chain ( /* TRUE: successful, FALSE: failed */
  261. FATFS *fs, /* File system object */
  262. DWORD clust /* Cluster# to remove chain from */
  263. )
  264. {
  265. DWORD nxt;
  266. while (clust >= 2 && clust < fs->max_clust) {
  267. nxt = get_cluster(fs, clust);
  268. if (nxt == 1) return FALSE;
  269. if (!put_cluster(fs, clust, 0)) return FALSE;
  270. if (fs->free_clust != 0xFFFFFFFF) {
  271. fs->free_clust++;
  272. #if _USE_FSINFO
  273. fs->fsi_flag = 1;
  274. #endif
  275. }
  276. clust = nxt;
  277. }
  278. return TRUE;
  279. }
  280. #endif
  281. /*-----------------------------------------------------------------------*/
  282. /* Stretch or create a cluster chain */
  283. /*-----------------------------------------------------------------------*/
  284. #if !_FS_READONLY
  285. static
  286. DWORD create_chain ( /* 0: No free cluster, 1: Error, >=2: New cluster number */
  287. FATFS *fs, /* File system object */
  288. DWORD clust /* Cluster# to stretch, 0 means create new */
  289. )
  290. {
  291. DWORD cstat, ncl, scl, mcl = fs->max_clust;
  292. if (clust == 0) { /* Create new chain */
  293. scl = fs->last_clust; /* Get suggested start point */
  294. if (scl == 0 || scl >= mcl) scl = 1;
  295. }
  296. else { /* Stretch existing chain */
  297. cstat = get_cluster(fs, clust); /* Check the cluster status */
  298. if (cstat < 2) return 1; /* It is an invalid cluster */
  299. if (cstat < mcl) return cstat; /* It is already followed by next cluster */
  300. scl = clust;
  301. }
  302. ncl = scl; /* Start cluster */
  303. for (;;) {
  304. ncl++; /* Next cluster */
  305. if (ncl >= mcl) { /* Wrap around */
  306. ncl = 2;
  307. if (ncl > scl) return 0; /* No free custer */
  308. }
  309. cstat = get_cluster(fs, ncl); /* Get the cluster status */
  310. if (cstat == 0) break; /* Found a free cluster */
  311. if (cstat == 1) return 1; /* Any error occured */
  312. if (ncl == scl) return 0; /* No free custer */
  313. }
  314. if (!put_cluster(fs, ncl, 0x0FFFFFFF)) return 1; /* Mark the new cluster "in use" */
  315. if (clust && !put_cluster(fs, clust, ncl)) return 1; /* Link it to previous one if needed */
  316. fs->last_clust = ncl; /* Update fsinfo */
  317. if (fs->free_clust != 0xFFFFFFFF) {
  318. fs->free_clust--;
  319. #if _USE_FSINFO
  320. fs->fsi_flag = 1;
  321. #endif
  322. }
  323. return ncl; /* Return new cluster number */
  324. }
  325. #endif /* !_FS_READONLY */
  326. /*-----------------------------------------------------------------------*/
  327. /* Get sector# from cluster# */
  328. /*-----------------------------------------------------------------------*/
  329. static
  330. DWORD clust2sect ( /* !=0: sector number, 0: failed - invalid cluster# */
  331. FATFS *fs, /* File system object */
  332. DWORD clust /* Cluster# to be converted */
  333. )
  334. {
  335. clust -= 2;
  336. if (clust >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */
  337. return clust * fs->csize + fs->database;
  338. }
  339. /*-----------------------------------------------------------------------*/
  340. /* Move directory pointer to next */
  341. /*-----------------------------------------------------------------------*/
  342. static
  343. BOOL next_dir_entry ( /* TRUE: successful, FALSE: could not move next */
  344. DIR *dj /* Pointer to directory object */
  345. )
  346. {
  347. DWORD clust;
  348. WORD idx;
  349. idx = dj->index + 1;
  350. if ((idx & ((SS(dj->fs) - 1) / 32)) == 0) { /* Table sector changed? */
  351. dj->sect++; /* Next sector */
  352. if (dj->clust == 0) { /* In static table */
  353. if (idx >= dj->fs->n_rootdir) return FALSE; /* Reached to end of table */
  354. } else { /* In dynamic table */
  355. if (((idx / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
  356. clust = get_cluster(dj->fs, dj->clust); /* Get next cluster */
  357. if (clust < 2 || clust >= dj->fs->max_clust) /* Reached to end of table */
  358. return FALSE;
  359. dj->clust = clust; /* Initialize for new cluster */
  360. dj->sect = clust2sect(dj->fs, clust);
  361. }
  362. }
  363. }
  364. dj->index = idx; /* Lower several bits of dj->index indicates offset in dj->sect */
  365. return TRUE;
  366. }
  367. /*-----------------------------------------------------------------------*/
  368. /* Get file status from directory entry */
  369. /*-----------------------------------------------------------------------*/
  370. #if _FS_MINIMIZE <= 1
  371. static
  372. void get_fileinfo ( /* No return code */
  373. FILINFO *finfo, /* Ptr to store the file information */
  374. const BYTE *dir /* Ptr to the directory entry */
  375. )
  376. {
  377. BYTE n, c, a;
  378. UCHAR *p;
  379. p = &finfo->fname[0];
  380. a = _USE_NTFLAG ? dir[DIR_NTres] : 0; /* NT flag */
  381. for (n = 0; n < 8; n++) { /* Convert file name (body) */
  382. c = dir[n];
  383. if (c == ' ') break;
  384. if (c == 0x05) c = 0xE5;
  385. if (a & 0x08 && c >= 'A' && c <= 'Z') c += 0x20;
  386. *p++ = c;
  387. }
  388. if (dir[8] != ' ') { /* Convert file name (extension) */
  389. *p++ = '.';
  390. for (n = 8; n < 11; n++) {
  391. c = dir[n];
  392. if (c == ' ') break;
  393. if (a & 0x10 && c >= 'A' && c <= 'Z') c += 0x20;
  394. *p++ = c;
  395. }
  396. }
  397. *p = '\0';
  398. finfo->fattrib = dir[DIR_Attr]; /* Attribute */
  399. finfo->fsize = LD_DWORD(&dir[DIR_FileSize]); /* Size */
  400. finfo->fdate = LD_WORD(&dir[DIR_WrtDate]); /* Date */
  401. finfo->ftime = LD_WORD(&dir[DIR_WrtTime]); /* Time */
  402. finfo->clust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16)
  403. | LD_WORD(&dir[DIR_FstClusLO]); /* Get cluster# */
  404. }
  405. #endif /* _FS_MINIMIZE <= 1 */
  406. /*-----------------------------------------------------------------------*/
  407. /* Pick a paragraph and create the name in format of directory entry */
  408. /*-----------------------------------------------------------------------*/
  409. static
  410. UCHAR make_dirfile ( /* 1: error - detected an invalid format, '\0'or'/': next character */
  411. const UCHAR **path, /* Pointer to the file path pointer */
  412. UCHAR *dirname, /* Pointer to directory name buffer {Name(8), Ext(3), NT flag(1)} */
  413. BOOL* lfn /* is this an LFN name? */
  414. )
  415. {
  416. BYTE n, t, c, a, b;
  417. *lfn=FALSE;
  418. memset(dirname, ' ', 8+3); /* Fill buffer with spaces */
  419. a = 0; b = 0x18; /* NT flag */
  420. n = 0; t = 8;
  421. for (;;) {
  422. c = *(*path)++;
  423. if (c == '\0' || c == '/') { /* Reached to end of str or directory separator */
  424. if (n == 0) break;
  425. dirname[11] = _USE_NTFLAG ? (a & b) : 0;
  426. return c;
  427. }
  428. if (c < ' ' || c == 0x7F) break; /* Reject invisible chars */
  429. if (c == ' ') goto md_l3;
  430. if (c == '.') {
  431. #if _USE_CHDIR != 0 || _USE_CURR_DIR != 0
  432. if (n == 0 || (n == 1 && *dirname == '.'))
  433. goto md_l2;
  434. #endif
  435. if (!(a & 1) && n >= 1 && n <= 8) { /* Enter extension part */
  436. n = 8; t = 11; continue;
  437. }
  438. goto md_l3;
  439. }
  440. if (_USE_SJIS &&
  441. ((c >= 0x81 && c <= 0x9F) || /* Accept S-JIS code */
  442. (c >= 0xE0 && c <= 0xFC))) {
  443. if (n == 0 && c == 0xE5) /* Change heading \xE5 to \x05 */
  444. c = 0x05;
  445. a ^= 0x01; goto md_l2;
  446. }
  447. if (c == '"') break; /* Reject " */
  448. if (c <= ')') goto md_l1; /* Accept ! # $ % & ' ( ) */
  449. if (c <= ',') goto md_l3; /* Reject * + , */
  450. if (c <= '9') goto md_l1; /* Accept - 0-9 */
  451. if (c <= '?') goto md_l3; /* Reject : ; < = > ? */
  452. if (!(a & 1)) { /* These checks are not applied to S-JIS 2nd byte */
  453. if (c == '|') goto md_l3; /* Reject | */
  454. if (c >= '[' && c <= ']') goto md_l3;/* Reject [ \ ] */
  455. if (_USE_NTFLAG && c >= 'A' && c <= 'Z')
  456. (t == 8) ? (b &= (BYTE)~0x08) : (b &= (BYTE)~0x10);
  457. if (c >= 'a' && c <= 'z') { /* Convert to upper case */
  458. c -= 0x20;
  459. if (_USE_NTFLAG) (t == 8) ? (a |= 0x08) : (a |= 0x10);
  460. }
  461. }
  462. md_l1:
  463. a &= (BYTE)~0x01;
  464. md_l2:
  465. if (n >= t) goto md_l3;
  466. dirname[n++] = c;
  467. }
  468. return 1;
  469. md_l3:
  470. #if _USE_LFN != 0
  471. do {
  472. if(c== '\\' || c==':' || c=='*' || c=='?' || c == '"' || c == '<' || c == '>' || c=='|')
  473. return 1;
  474. c = *(*path)++;
  475. } while (c != '\0' && c != '/'); /* Reached to end of str or directory separator */
  476. *lfn=TRUE;
  477. return c;
  478. #else
  479. return 1;
  480. #endif
  481. }
  482. /*-----------------------------------------------------------------------*/
  483. /* Trace a file path */
  484. /*-----------------------------------------------------------------------*/
  485. static
  486. FRESULT trace_path ( /* FR_OK(0): successful, !=0: error code */
  487. DIR *dj, /* Pointer to directory object to return last directory */
  488. UCHAR *fn, /* Pointer to last segment name to return {file(8),ext(3),attr(1)} */
  489. const UCHAR *path, /* Full-path string to trace a file or directory */
  490. BYTE **dir /* Pointer to pointer to found entry to return */
  491. #if _USE_LFN != 0
  492. ,DIR *fileobj, /* Pointer DIR holding the beginning of the LFN, identical to dj if none */
  493. const UCHAR** spath, /* path to start of last item's name */
  494. UINT *len /* length of LFN entry, 0=non-LFN */
  495. #endif
  496. )
  497. {
  498. DWORD clust;
  499. UCHAR ds;
  500. BYTE *dptr = NULL;
  501. FATFS *fs = dj->fs;
  502. BOOL lfn;
  503. #if _USE_LFN != 0
  504. BYTE a,b,i,j;
  505. BOOL match;
  506. UINT l;
  507. BOOL store=TRUE;
  508. #endif
  509. /* Initialize directory object */
  510. #if _USE_CHDIR != 0 || _USE_CURR_DIR != 0
  511. if(fs->curr_dir==0 || (*path!=0 && path[0]=='/')) {
  512. #endif
  513. clust = fs->dirbase;
  514. if (fs->fs_type == FS_FAT32) {
  515. dj->clust = dj->sclust = clust;
  516. dj->sect = clust2sect(fs, clust);
  517. } else {
  518. dj->clust = dj->sclust = 0;
  519. dj->sect = clust;
  520. }
  521. #if _USE_CHDIR != 0 || _USE_CURR_DIR !=0
  522. } else {
  523. clust=fs->curr_dir;
  524. dj->clust = dj->sclust = clust;
  525. dj->sect = clust2sect(fs, clust);
  526. }
  527. #endif
  528. dj->index = 0;
  529. #if _USE_LFN != 0
  530. //fileobj->id=dj->id;
  531. fileobj->fs=dj->fs;
  532. #endif
  533. #if _USE_CHDIR != 0
  534. while (path[0] == '/') path++;
  535. #endif
  536. if (*path == '\0') { /* Null path means the root directory */
  537. *dir = NULL; return FR_OK;
  538. }
  539. for (;;) {
  540. #if _USE_LFN != 0
  541. *spath=path; // save this off, as we may need it for the LFN
  542. match=TRUE;
  543. l=0;
  544. #endif
  545. ds = make_dirfile(&path, fn, &lfn); /* Get a paragraph into fn[] */
  546. #if _USE_LFN != 0
  547. if(lfn)
  548. *len=path-*spath-1; /* this might not be ANSI-compatible, not sure */
  549. else
  550. *len=0;
  551. #endif
  552. if (ds == 1) return FR_INVALID_NAME;
  553. for (;;) {
  554. if (!move_fs_window(fs, dj->sect)) return FR_RW_ERROR;
  555. #if _USE_LFN != 0
  556. if (store) {
  557. fileobj->clust = dj->clust;
  558. fileobj->sect = dj->sect;
  559. fileobj->index = dj->index;
  560. store = FALSE;
  561. if (!lfn)
  562. /* We don't know the length of the LFN, estimate it */
  563. *len = 0;
  564. }
  565. #endif
  566. dptr = &FSBUF.data[(dj->index & ((SS(fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */
  567. if (dptr[DIR_Name] == 0) /* Has it reached to end of dir? */
  568. return !ds ? FR_NO_FILE : FR_NO_PATH;
  569. #if _USE_LFN != 0
  570. if (dptr[DIR_Name] != 0xE5) { /* Matched? */
  571. if((dptr[DIR_Attr] & AM_LFN) == AM_LFN) {
  572. if (lfn) {
  573. i=((dptr[0]&0x1f)-1)*13;
  574. j=0;
  575. while(j<13 && match) {
  576. a=dptr[pgm_read_byte(LFN_pos+j)];
  577. b=dptr[pgm_read_byte(LFN_pos+j++)+1];
  578. if(!a && !b) {
  579. j--;
  580. break;
  581. }
  582. b=(*spath)[i++];
  583. if (b >= 'a' && b <= 'z') { /* Convert to upper case */
  584. b -= 0x20;
  585. }
  586. if (a >= 'a' && a <= 'z') { /* Convert to upper case */
  587. a -= 0x20;
  588. }
  589. if(a!= b) {
  590. match=FALSE;
  591. }
  592. }
  593. l+=j;
  594. } else {
  595. /* Track the length of the LFN entry in case it belongs to our file */
  596. *len = *len + 13;
  597. }
  598. } else if ((dptr[DIR_Attr] & AM_LFN) != AM_LFN) { /* we're a normal entry */
  599. if (lfn) {
  600. if(lfn && (match && l == *len)) { /* match */
  601. memcpy(fn,&dptr[DIR_Name], 8+3);
  602. fn[11] = dptr[DIR_NTres];
  603. break;
  604. }
  605. l=0;
  606. match=TRUE;
  607. } else {
  608. /* No LFN to match against */
  609. if (dptr[DIR_Name] != 0xE5 /* Matched? */
  610. && !(dptr[DIR_Attr] & AM_VOL)
  611. && !memcmp(&dptr[DIR_Name], fn, 8+3) ) {
  612. break;
  613. }
  614. }
  615. store = TRUE;
  616. }
  617. } else
  618. /* This is a deleted entry, move fileobj forward */
  619. store = TRUE;
  620. #else
  621. if (dptr[DIR_Name] != 0xE5 /* Matched? */
  622. && !(dptr[DIR_Attr] & AM_VOL)
  623. && !memcmp(&dptr[DIR_Name], fn, 8+3) ) {
  624. break;
  625. }
  626. #endif
  627. if (!next_dir_entry(dj)) { /* Next directory pointer */
  628. #if _USE_LFN != 0
  629. if (!lfn)
  630. *len = 0;
  631. #endif
  632. return !ds ? FR_NO_FILE : FR_NO_PATH;
  633. }
  634. }
  635. if (!ds) { *dir = dptr; return FR_OK; } /* Matched with end of path */
  636. if (!(dptr[DIR_Attr] & AM_DIR)) return FR_NO_PATH; /* Cannot trace because it is a file */
  637. clust = ((DWORD)LD_WORD(&dptr[DIR_FstClusHI]) << 16)
  638. | LD_WORD(&dptr[DIR_FstClusLO]); /* Get cluster# of the directory */
  639. dj->clust = dj->sclust = clust; /* Restart scanning at the new directory */
  640. dj->sect = clust2sect(fs, clust);
  641. dj->index = 2;
  642. }
  643. }
  644. /*-----------------------------------------------------------------------*/
  645. /* Reserve a directory entry */
  646. /*-----------------------------------------------------------------------*/
  647. #if !_FS_READONLY
  648. static
  649. FRESULT reserve_direntry ( /* FR_OK: successful, FR_DENIED: no free entry, FR_RW_ERROR: a disk error occured */
  650. DIR *dj, /* Target directory to create new entry */
  651. BYTE **dir /* Pointer to pointer to created entry to retutn */
  652. #if _USE_LFN != 0
  653. ,UINT len
  654. #endif
  655. )
  656. {
  657. DWORD clust, sector;
  658. BYTE c, n, *dptr;
  659. FATFS *fs = dj->fs;
  660. #if _USE_LFN != 0
  661. BYTE entries=0;
  662. WORD isave=0;
  663. DWORD csave=0,ssave=0;
  664. len=(len+25)/13;
  665. #endif
  666. /* Re-initialize directory object */
  667. clust = dj->sclust;
  668. if (clust != 0) { /* Dynamic directory table */
  669. dj->clust = clust;
  670. dj->sect = clust2sect(fs, clust);
  671. } else { /* Static directory table */
  672. dj->sect = fs->dirbase;
  673. }
  674. dj->index = 0;
  675. do {
  676. if (!move_fs_window(fs, dj->sect)) return FR_RW_ERROR;
  677. dptr = &FSBUF.data[(dj->index & ((SS(fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */
  678. c = dptr[DIR_Name];
  679. if (c == 0 || c == 0xE5) { /* Found an empty entry */
  680. #if _USE_LFN != 0
  681. /* capture initial entry. */
  682. if((entries++) == 0) {
  683. *dir=dptr;
  684. isave=dj->index;
  685. ssave=dj->sect;
  686. csave=dj->clust;
  687. }
  688. if(entries==len) {
  689. dj->index=isave;
  690. dj->sect=ssave;
  691. dj->clust=csave;
  692. return FR_OK;
  693. }
  694. } else if(entries!=len){
  695. entries=0;
  696. #else
  697. *dir = dptr; return FR_OK;
  698. #endif
  699. }
  700. } while (next_dir_entry(dj)); /* Next directory pointer */
  701. /* Reached to end of the directory table */
  702. /* Abort when it is a static table or could not stretch dynamic table */
  703. if (clust == 0 || !(clust = create_chain(fs, dj->clust))) return FR_DENIED;
  704. if (clust == 1 || !move_fs_window(fs, 0)) return FR_RW_ERROR;
  705. /* Cleanup the expanded table */
  706. FSBUF.sect = sector = clust2sect(fs, clust);
  707. memset(FSBUF.data, 0, SS(fs));
  708. for (n = fs->csize; n; n--) {
  709. if (disk_write(fs->drive, FSBUF.data, sector, 1) != RES_OK)
  710. return FR_RW_ERROR;
  711. sector++;
  712. }
  713. FSBUF.dirty = TRUE;
  714. #if _USE_LFN != 0
  715. if(entries) { // we had to expand the table, but now we need to go back.
  716. if (!move_fs_window(fs, ssave)) return FR_RW_ERROR;
  717. dj->index=isave;
  718. dj->sect=ssave;
  719. dj->clust=csave;
  720. } else {
  721. /* We allocated a new cluster for all entries, point dj there */
  722. dj->index = 0;
  723. dj->sect = FSBUF.sect;
  724. dj->clust = clust;
  725. *dir = FSBUF.data;
  726. }
  727. #else
  728. *dir = FSBUF.data;
  729. #endif
  730. return FR_OK;
  731. }
  732. #endif /* !_FS_READONLY */
  733. /*-----------------------------------------------------------------------*/
  734. /* Load boot record and check if it is a FAT boot record */
  735. /*-----------------------------------------------------------------------*/
  736. static const PROGMEM UCHAR fat32string[] = "FAT32";
  737. static
  738. BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not a FAT, 2:Not a boot record or error */
  739. FATFS *fs, /* File system object */
  740. DWORD sect /* Sector# (lba) to check if it is a FAT boot record or not */
  741. )
  742. {
  743. if (!move_fs_window(fs, sect)) /* Load boot record, save off old data in process */
  744. return 2;
  745. if (!sect) {
  746. if (disk_read(fs->drive, FSBUF.data, sect, 1) != RES_OK) /* Load boot record, if sector 0 */
  747. return 2;
  748. FSBUF.sect = 0;
  749. }
  750. if (LD_WORD(&FSBUF.data[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
  751. return 2;
  752. if (!memcmp_P(&FSBUF.data[BS_FilSysType], fat32string, 3)) /* Check FAT signature */
  753. return 0;
  754. if (!memcmp_P(&FSBUF.data[BS_FilSysType32], fat32string, 5) && !(FSBUF.data[BPB_ExtFlags] & 0x80))
  755. return 0;
  756. return 1;
  757. }
  758. /*-----------------------------------------------------------------------*/
  759. /* Mount a drive */
  760. /*-----------------------------------------------------------------------*/
  761. FRESULT mount_drv(
  762. BYTE drv,
  763. FATFS* fs,
  764. BYTE chk_wp /* !=0: Check media write protection for write access */
  765. )
  766. {
  767. DSTATUS stat;
  768. BYTE fmt, *tbl;
  769. DWORD bootsect, fatsize, totalsect, maxclust;
  770. memset(fs, 0, sizeof(FATFS)); /* Clean-up the file system object */
  771. fs->drive = LD2PD(drv); /* Bind the logical drive and a physical drive */
  772. stat = disk_initialize(fs->drive); /* Initialize low level disk I/O layer */
  773. if (stat & STA_NOINIT) /* Check if the drive is ready */
  774. return FR_NOT_READY;
  775. #if S_MAX_SIZ > 512 /* Get disk sector size if needed */
  776. if (disk_ioctl(fs->drive, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > S_MAX_SIZ)
  777. return FR_NO_FILESYSTEM;
  778. #endif
  779. #if !_FS_READONLY
  780. if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
  781. return FR_WRITE_PROTECTED;
  782. #endif
  783. #if _MULTI_PARTITION == 0
  784. /* Search FAT partition on the drive */
  785. fmt = check_fs(fs, bootsect = 0); /* Check sector 0 as an SFD format */
  786. if (fmt == 1) { /* Not a FAT boot record, it may be patitioned */
  787. /* Check a partition listed in top of the partition table */
  788. tbl = &FSBUF.data[MBR_Table + LD2PT(drv) * 16]; /* Partition table */
  789. if (tbl[4]) { /* Is the partition existing? */
  790. bootsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */
  791. fmt = check_fs(fs, bootsect); /* Check the partition */
  792. }
  793. }
  794. #else
  795. /* Check only the partition that was requested */
  796. if (LD2PT(drv) == 0) {
  797. /* Unpartitioned media */
  798. fmt = check_fs(fs, bootsect = 0);
  799. } else {
  800. /* Read MBR */
  801. fmt = 1;
  802. if (disk_read(fs->drive, FSBUF.data, 0, 1) != RES_OK)
  803. goto failed;
  804. if (LD2PT(drv) < 5) {
  805. /* Primary partition */
  806. tbl = &FSBUF.data[MBR_Table + (LD2PT(drv)-1) * 16];
  807. fmt = 1;
  808. if (tbl[4]) {
  809. bootsect = LD_DWORD(&tbl[8]);
  810. fmt = check_fs(fs, bootsect);
  811. }
  812. } else {
  813. /* Logical drive */
  814. BYTE i,curr;
  815. fmt = 1;
  816. bootsect = 0;
  817. fatsize = 0; // Used to store the offset of the first extended part
  818. curr = LD2PT(drv)-4;
  819. /* Walk the chain of extended partitions */
  820. do {
  821. /* Check for an extended partition */
  822. for (i=0;i<4;i++) {
  823. tbl = &FSBUF.data[MBR_Table + i*16];
  824. if (tbl[4] == 5 || tbl[4] == 0x0f)
  825. break;
  826. }
  827. if (i == 4) {
  828. fmt = 255;
  829. goto failed;
  830. }
  831. bootsect = fatsize + LD_DWORD(&tbl[8]);
  832. if (fatsize == 0)
  833. fatsize = bootsect;
  834. /* Read the next sector in the partition chain */
  835. if (disk_read(fs->drive, FSBUF.data, bootsect, 1) != RES_OK)
  836. goto failed;
  837. } while (--curr);
  838. /* Look for the non-extended, non-empty partition entry */
  839. for (i=0;i<4;i++) {
  840. tbl = &FSBUF.data[MBR_Table + i*16];
  841. if (tbl[4] && tbl[4] != 5 && tbl[4] != 0x0f)
  842. break;
  843. }
  844. if (i == 4) {
  845. /* End of extended partition chain */
  846. fmt = 255;
  847. goto failed;
  848. }
  849. bootsect = bootsect + LD_DWORD(&tbl[8]);
  850. fmt = check_fs(fs, bootsect);
  851. }
  852. }
  853. failed:
  854. #endif
  855. if (fmt || LD_WORD(&FSBUF.data[BPB_BytsPerSec]) != SS(fs)) { /* No valid FAT patition is found */
  856. if (fmt == 255) {
  857. /* At end of extended partition chain */
  858. return FR_INVALID_OBJECT;
  859. } else {
  860. /* No file system found */
  861. return FR_NO_FILESYSTEM;
  862. }
  863. }
  864. /* Initialize the file system object */
  865. fatsize = LD_WORD(&FSBUF.data[BPB_FATSz16]); /* Number of sectors per FAT */
  866. if (!fatsize) fatsize = LD_DWORD(&FSBUF.data[BPB_FATSz32]);
  867. fs->sects_fat = fatsize;
  868. fs->n_fats = FSBUF.data[BPB_NumFATs]; /* Number of FAT copies */
  869. fatsize *= fs->n_fats; /* (Number of sectors in FAT area) */
  870. fs->fatbase = bootsect + LD_WORD(&FSBUF.data[BPB_RsvdSecCnt]); /* FAT start sector (lba) */
  871. fs->csize = FSBUF.data[BPB_SecPerClus]; /* Number of sectors per cluster */
  872. fs->n_rootdir = LD_WORD(&FSBUF.data[BPB_RootEntCnt]); /* Nmuber of root directory entries */
  873. totalsect = LD_WORD(&FSBUF.data[BPB_TotSec16]); /* Number of sectors on the file system */
  874. if (!totalsect) totalsect = LD_DWORD(&FSBUF.data[BPB_TotSec32]);
  875. fs->max_clust = maxclust = (totalsect /* max_clust = Last cluster# + 1 */
  876. - LD_WORD(&FSBUF.data[BPB_RsvdSecCnt]) - fatsize - fs->n_rootdir / (SS(fs)/32)
  877. ) / fs->csize + 2;
  878. fmt = FS_FAT12; /* Determine the FAT sub type */
  879. if (maxclust >= 0xFF7) fmt = FS_FAT16;
  880. if (maxclust >= 0xFFF7) fmt = FS_FAT32;
  881. fs->fs_type = fmt;
  882. if (fmt == FS_FAT32)
  883. fs->dirbase = LD_DWORD(&FSBUF.data[BPB_RootClus]); /* Root directory start cluster */
  884. else
  885. fs->dirbase = fs->fatbase + fatsize; /* Root directory start sector (lba) */
  886. fs->database = fs->fatbase + fatsize + fs->n_rootdir / (SS(fs)/32); /* Data start sector (lba) */
  887. #if !_FS_READONLY
  888. fs->free_clust = 0xFFFFFFFF;
  889. # if _USE_FSINFO
  890. /* Get fsinfo if needed */
  891. if (fmt == FS_FAT32) {
  892. fs->fsi_sector = bootsect + LD_WORD(&FSBUF.data[BPB_FSInfo]);
  893. //if (disk_read(fs->drive, FSBUF.data, fs->fsi_sector, 1) == RES_OK &&
  894. if (move_fs_window(fs,fs->fsi_sector) &&
  895. LD_WORD(&FSBUF.data[BS_55AA]) == 0xAA55 &&
  896. LD_DWORD(&FSBUF.data[FSI_LeadSig]) == 0x41615252 &&
  897. LD_DWORD(&FSBUF.data[FSI_StrucSig]) == 0x61417272) {
  898. fs->last_clust = LD_DWORD(&FSBUF.data[FSI_Nxt_Free]);
  899. fs->free_clust = LD_DWORD(&FSBUF.data[FSI_Free_Count]);
  900. }
  901. }
  902. # endif
  903. #endif
  904. fs->fs_type = fmt; /* FAT syb-type */
  905. //fs->id = ++fsid; /* File system mount ID */
  906. return FR_OK;
  907. }
  908. /*-----------------------------------------------------------------------*/
  909. /* Make sure that the file system is valid */
  910. /*-----------------------------------------------------------------------*/
  911. static
  912. FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */
  913. const UCHAR **path, /* Pointer to pointer to the path name (drive number) */
  914. FATFS **rfs, /* Pointer to pointer to the found file system object */
  915. BYTE chk_wp /* !=0: Check media write protection for write access */
  916. )
  917. {
  918. DSTATUS stat;
  919. const UCHAR *p = *path;
  920. #if _USE_DRIVE_PREFIX != 0
  921. BYTE drv;
  922. /* Get drive number from the path name */
  923. while (*p == ' ') p++; /* Strip leading spaces */
  924. # if _MULTI_PARTITION != 0
  925. *path=p;
  926. drv = 0;
  927. while(*p >= '0' && *p<='9') {
  928. if(drv >= 25 && *p > '5')
  929. return FR_INVALID_DRIVE;
  930. drv = drv*10+((*p++)-'0');
  931. }
  932. if(*p != ':') {
  933. p = *path;
  934. drv = 0;
  935. }
  936. # else
  937. drv = p[0] - '0'; /* Is there a drive number? */
  938. if (drv <= 9 && p[1] == ':')
  939. p += 2; /* Found a drive number, get and strip it */
  940. else
  941. drv = 0; /* No drive number is given, use drive number 0 as default */
  942. # endif
  943. #endif
  944. #if _USE_CHDIR == 0
  945. if (*p == '/') p++; /* Strip heading slash */
  946. #endif
  947. *path = p; /* Return pointer to the path name */
  948. /* Check if the drive number is valid or not */
  949. #if _USE_DRIVE_PREFIX != 0
  950. if (drv >= _LOGICAL_DRIVES) return FR_INVALID_DRIVE; /* Is the drive number valid? */
  951. *rfs = FatFs[drv]; /* Returen pointer to the corresponding file system object */
  952. #endif
  953. if (!*rfs) return FR_NOT_ENABLED; /* Is the file system object registered? */
  954. if ((*rfs)->fs_type) { /* If the logical drive has been mounted */
  955. stat = disk_status((*rfs)->drive);
  956. if (!(stat & STA_NOINIT)) { /* and physical drive is kept initialized (has not been changed), */
  957. #if !_FS_READONLY
  958. if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
  959. return FR_WRITE_PROTECTED;
  960. #endif
  961. return FR_OK; /* The file system object is valid */
  962. }
  963. }
  964. /* The logical drive must be re-mounted. */
  965. #if _USE_DEFERRED_MOUNT != 0
  966. return mount_drv(drv,*rfs, chk_wp);
  967. #else
  968. return FR_NOT_READY;
  969. #endif
  970. }
  971. /*-----------------------------------------------------------------------*/
  972. /* Check if the file/dir object is valid or not */
  973. /*-----------------------------------------------------------------------*/
  974. static
  975. FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
  976. const FATFS *fs /* Pointer to the file system object */
  977. //,WORD id /* Member id of the target object to be checked */
  978. )
  979. {
  980. if (!fs || !fs->fs_type /*|| fs->id != id */)
  981. return FR_INVALID_OBJECT;
  982. if (disk_status(fs->drive) & STA_NOINIT)
  983. return FR_NOT_READY;
  984. return FR_OK;
  985. }
  986. #if _USE_LFN != 0
  987. static
  988. BYTE compute_checksum(UCHAR *buf) {
  989. BYTE i,rc;
  990. rc=buf[0];
  991. for(i=1;i<11;i++) {
  992. rc=(rc&1?(rc>>1)| 0x80:rc>>1);
  993. rc+=buf[i];
  994. }
  995. return rc;
  996. }
  997. static
  998. BYTE dos_char(
  999. BYTE x
  1000. )
  1001. {
  1002. if(x>('a'-1) && x<('z'+1))
  1003. x=x-'a'+'A';
  1004. else if(x>(' '-1) && x<'+') {
  1005. } else if(x>('A'-1) && x<('Z'+1)) {
  1006. } else if(x>('0'-1) && x<('9'+1)) {
  1007. } else if(x&0x80) {
  1008. } else switch(x) {
  1009. case ',':
  1010. case '-':
  1011. case '^':
  1012. case '~':
  1013. case '=':
  1014. case '_':
  1015. case '`':
  1016. case '{':
  1017. case '}':
  1018. break;
  1019. default:
  1020. x='_';
  1021. break;
  1022. }
  1023. return x;
  1024. }
  1025. static
  1026. void create_short_name(
  1027. const UCHAR* name,
  1028. UINT len,
  1029. UCHAR* buf
  1030. )
  1031. {
  1032. BYTE i=0,k,l=0;
  1033. BYTE j=len;
  1034. memset(buf,' ',11);
  1035. buf[11]=0;
  1036. if(name[0]!='.') {
  1037. while(--j) { /* find the last '.' */
  1038. if(name[j]=='.') break;
  1039. }
  1040. k=j+1;
  1041. i=8;
  1042. if(k>1) {
  1043. while(k<len && i<11) {
  1044. if(name[k]!=' ') {
  1045. // build extension
  1046. buf[i++]=dos_char(name[k]);
  1047. }
  1048. k++;
  1049. }
  1050. } else
  1051. j=6;
  1052. }
  1053. i=0; /* now build start */
  1054. while(i<6 && l<j) {
  1055. if(name[l]!=' ' && name[l]!='.') {
  1056. buf[i++]=dos_char(name[l]);
  1057. }
  1058. l++;
  1059. }
  1060. if(i<3) {
  1061. buf[i++]='A'; /* FIXME: replace this with a way to generate a random or hash hex word. */
  1062. buf[i++]='B';
  1063. buf[i++]='C';
  1064. buf[i++]='D';
  1065. }
  1066. buf[i++]='~';
  1067. buf[i++]='1';
  1068. if(((BYTE)buf[0])==0xe5)
  1069. buf[0]=0x05;
  1070. }
  1071. static
  1072. BOOL fix_short_name(
  1073. UCHAR *buf
  1074. )
  1075. {
  1076. BYTE i=8;
  1077. BOOL c=FALSE;
  1078. while(buf[--i]==' ');
  1079. do {
  1080. if(buf[i]=='9') {
  1081. buf[i]='0';
  1082. c=TRUE;
  1083. } else if(c && buf[i]=='~') {
  1084. buf[i]='1';
  1085. break;
  1086. } else {
  1087. buf[i]++;
  1088. c=FALSE;
  1089. break;
  1090. }
  1091. } while (--i);
  1092. if(c) {
  1093. if(!i) return FALSE;
  1094. buf[i-1]='~';
  1095. }
  1096. return TRUE;
  1097. }
  1098. static
  1099. FRESULT chk_filename( /* FR_EXIST means name is taken. */
  1100. DIR *dj, /* Target directory to create new entry */
  1101. UCHAR* fn /* name to check */
  1102. )
  1103. {
  1104. BYTE *dptr;
  1105. FATFS *fs = dj->fs;
  1106. DWORD clust;
  1107. /* Re-initialize directory object */
  1108. clust = dj->sclust;
  1109. if (clust) { /* Dyanmic directory table */
  1110. dj->clust = clust;
  1111. dj->sect = clust2sect(fs, clust);
  1112. } else { /* Static directory table */
  1113. dj->sect = fs->dirbase;
  1114. }
  1115. dj->index = 0;
  1116. do {
  1117. if (!move_fs_window(fs, dj->sect)) return FR_RW_ERROR;
  1118. dptr = &FSBUF.data[(dj->index & ((SS(fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */
  1119. if(dptr[DIR_Name] == 0) { /* if we got here, we have a match */
  1120. return FR_OK;
  1121. } else if(*dptr!=0xe5
  1122. && (dptr[DIR_Attr] & AM_LFN) != AM_LFN
  1123. && !(dptr[DIR_Attr] & AM_VOL)
  1124. && !memcmp(&dptr[DIR_Name], fn, 8+3) ) /* start over. */
  1125. return FR_EXIST;
  1126. } while (next_dir_entry(dj)); /* Next directory pointer */
  1127. /* Reached to end of the directory table */
  1128. return FR_OK;
  1129. }
  1130. FRESULT add_direntry(
  1131. DIR *dj, /* Target directory to create new entry */
  1132. BYTE **dir, /* pointer to created entry */
  1133. const UCHAR* spath,
  1134. UINT len,
  1135. UCHAR* fn
  1136. )
  1137. {
  1138. FATFS *fs = dj->fs;
  1139. DWORD clust,sect;
  1140. WORD index;
  1141. BYTE entries,i,j,k;
  1142. BYTE chk;
  1143. entries=i=(len+12)/13;
  1144. fn[11]=0; /* ALL uppercase */
  1145. clust = dj->clust; /* save off entries needed. */
  1146. index = dj->index;
  1147. sect = dj->sect;
  1148. create_short_name(spath,len,fn);
  1149. for(;;) {
  1150. if(!chk_filename(dj,fn)) break;
  1151. if(!fix_short_name(fn))
  1152. return FR_EXIST;
  1153. }
  1154. chk=compute_checksum(fn);
  1155. dj->clust = clust; /* we now have a good name, use it */
  1156. dj->index = index;
  1157. dj->sect = sect;
  1158. while(move_fs_window(fs, dj->sect)) {
  1159. *dir = &FSBUF.data[(dj->index & ((SS(fs) - 1) / 32)) * 32]; /* Pointer to the directory entry */
  1160. if(!i)
  1161. return FR_OK;
  1162. FSBUF.dirty = TRUE;
  1163. memset(*dir, 0, 32); /* Initialize the new entry with open name */
  1164. (*dir)[DIR_Name]=(i==entries?0x40:0) | (i);
  1165. j=0;
  1166. i--;
  1167. k=(i)*13;
  1168. while(j<13 && k<len) {
  1169. (*dir)[pgm_read_byte(LFN_pos+j++)]=spath[k++];
  1170. }
  1171. j++;
  1172. while(j<13) {
  1173. (*dir)[pgm_read_byte(LFN_pos+j)]=0xff;
  1174. (*dir)[pgm_read_byte(LFN_pos+j++)+1]=0xff;
  1175. }
  1176. (*dir)[DIR_Attr]=AM_LFN;
  1177. (*dir)[DIR_Chksum]=chk;
  1178. if(!next_dir_entry(dj)) break;
  1179. }
  1180. return FR_RW_ERROR;
  1181. }
  1182. #endif
  1183. /*--------------------------------------------------------------------------
  1184. Public Functions
  1185. --------------------------------------------------------------------------*/
  1186. /*-----------------------------------------------------------------------*/
  1187. /* Mount/Unmount a Locical Drive */
  1188. /*-----------------------------------------------------------------------*/
  1189. FRESULT f_mount (
  1190. BYTE drv, /* Logical drive number to be mounted/unmounted */
  1191. FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
  1192. )
  1193. {
  1194. #if _USE_DRIVE_PREFIX != 0
  1195. if (drv >= _LOGICAL_DRIVES) return FR_INVALID_DRIVE;
  1196. if (FatFs[drv]) FatFs[drv]->fs_type = 0; /* Clear old object */
  1197. FatFs[drv] = fs; /* Register and clear new object */
  1198. #endif
  1199. if (fs) fs->fs_type = 0;
  1200. #if _USE_DEFERRED_MOUNT == 0
  1201. return mount_drv(drv,fs,0);
  1202. #else
  1203. return FR_OK;
  1204. #endif
  1205. }
  1206. /*-----------------------------------------------------------------------*/
  1207. /* Open or Create a File */
  1208. /*-----------------------------------------------------------------------*/
  1209. FRESULT f_open (
  1210. #if _USE_DRIVE_PREFIX == 0
  1211. FATFS *fs, /* Pointer to file system object */
  1212. #endif
  1213. FIL *fp, /* Pointer to the blank file object */
  1214. const UCHAR *path, /* Pointer to the file name */
  1215. BYTE mode /* Access mode and file open mode flags */
  1216. )
  1217. {
  1218. FRESULT res;
  1219. DIR dj;
  1220. BYTE *dir = NULL;
  1221. UCHAR fn[8+3+1];
  1222. #if _USE_DRIVE_PREFIX != 0
  1223. FATFS *fs = NULL;
  1224. #endif
  1225. #if _USE_LFN != 0
  1226. UINT len;
  1227. DIR fileobj;
  1228. const UCHAR* spath;
  1229. #endif
  1230. #if _USE_FS_BUF == 0
  1231. FPBUF.dirty=FALSE;
  1232. #endif
  1233. fp->fs = NULL; /* Clear file object */
  1234. #if !_FS_READONLY
  1235. mode &= (FA_READ|FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW);
  1236. res = auto_mount(&path, &fs, (BYTE)(mode & (FA_WRITE|FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)));
  1237. #else
  1238. mode &= FA_READ;
  1239. res = auto_mount(&path, &fs, 0);
  1240. #endif
  1241. if (res != FR_OK) return res;
  1242. dj.fs = fs;
  1243. #if _USE_LFN != 0
  1244. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len); /* Trace the file path */
  1245. #else
  1246. res = trace_path(&dj, fn, path, &dir); /* Trace the file path */
  1247. #endif
  1248. #if !_FS_READONLY
  1249. /* Create or Open a file */
  1250. # if _USE_CHDIR != 0
  1251. if(fn[0]=='.')
  1252. return FR_INVALID_NAME;
  1253. # endif
  1254. if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) {
  1255. DWORD ps, rs;
  1256. if (res != FR_OK) { /* No file, create new */
  1257. if (res != FR_NO_FILE) return res;
  1258. # if _USE_LFN != 0
  1259. res = reserve_direntry(&dj, &dir,len);
  1260. if (res != FR_OK) return res;
  1261. if(len && add_direntry(&dj,&dir,spath,len,fn)) return FR_RW_ERROR;
  1262. # else
  1263. res = reserve_direntry(&dj, &dir);
  1264. if (res != FR_OK) return res;
  1265. # endif
  1266. memset(dir, 0, 32); /* Initialize the new entry with open name */
  1267. memcpy(&dir[DIR_Name], fn, 8+3);
  1268. dir[DIR_NTres] = fn[11];
  1269. mode |= FA_CREATE_ALWAYS;
  1270. }
  1271. else { /* Any object is already existing */
  1272. if (mode & FA_CREATE_NEW) /* Cannot create new */
  1273. return FR_EXIST;
  1274. if (!dir) /* Cannot overwrite it */
  1275. return FR_DENIED;
  1276. if (dir[DIR_Attr] & AM_DIR)
  1277. return FR_IS_DIRECTORY;
  1278. if (dir[DIR_Attr] & AM_RDO)
  1279. return FR_IS_READONLY;
  1280. if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero if needed */
  1281. rs = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]); /* Get start cluster */
  1282. ST_WORD(&dir[DIR_FstClusHI], 0); /* cluster = 0 */
  1283. ST_WORD(&dir[DIR_FstClusLO], 0);
  1284. ST_DWORD(&dir[DIR_FileSize], 0); /* size = 0 */
  1285. FSBUF.dirty = TRUE;
  1286. ps = FSBUF.sect; /* Remove the cluster chain */
  1287. if (!remove_chain(fs, rs) || !move_fs_window(fs, ps))
  1288. return FR_RW_ERROR;
  1289. fs->last_clust = rs - 1; /* Reuse the cluster hole */
  1290. }
  1291. }
  1292. if (mode & FA_CREATE_ALWAYS) {
  1293. dir[DIR_Attr] = 0; /* Reset attribute */
  1294. ps = get_fattime();
  1295. ST_DWORD(&dir[DIR_CrtTime], ps); /* Created time */
  1296. mode |= FA__WRITTEN; /* Set file changed flag */
  1297. }
  1298. }
  1299. /* Open an existing file */
  1300. else {
  1301. #endif /* !_FS_READONLY */
  1302. if (res != FR_OK) return res; /* Trace failed */
  1303. if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */
  1304. return FR_NO_FILE;
  1305. #if !_FS_READONLY
  1306. if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
  1307. return FR_DENIED;
  1308. }
  1309. fp->dir_sect = FSBUF.sect; /* Pointer to the directory entry */
  1310. fp->dir_ptr = dir;
  1311. #endif
  1312. fp->flag = mode; /* File access mode */
  1313. fp->org_clust = /* File start cluster */
  1314. ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
  1315. fp->fsize = LD_DWORD(&dir[DIR_FileSize]); /* File size */
  1316. fp->fptr = 0; /* Initialize file pointer */
  1317. fp->csect = 1; /* Sector counter */
  1318. fp->fs = fs; //fp->id = fs->id; /* Owner file system object of the file */
  1319. #if !_FS_READONLY
  1320. if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW))
  1321. sync(fs); /* sync buffer in case the file was just created */
  1322. /* can't sync earlier, modifies FSBUF.sect */
  1323. #endif
  1324. return FR_OK;
  1325. }
  1326. FRESULT l_opencluster (
  1327. FATFS *fs, /* Pointer to file system object */
  1328. FIL *fp, /* Pointer to the blank file object */
  1329. DWORD clust /* Cluster number to be opened */
  1330. )
  1331. {
  1332. fp->flag = FA_READ;
  1333. fp->org_clust = clust;
  1334. fp->fsize = (DWORD)fs->csize * SS(fs);
  1335. fp->fptr = 0;
  1336. fp->csect = 1;
  1337. fp->fs = fs;
  1338. return FR_OK;
  1339. }
  1340. FRESULT l_openfilebycluster (
  1341. FATFS *fs, /* Pointer to file system object */
  1342. FIL *fp, /* Pointer to the blank file object */
  1343. const UCHAR *path,
  1344. DWORD clust, /* Cluster number to be opened */
  1345. DWORD fsize /* File size to be assumed */
  1346. )
  1347. {
  1348. auto_mount(&path, &fs, 0);
  1349. fp->flag = FA_READ;
  1350. fp->org_clust = clust;
  1351. fp->fsize = fsize;
  1352. fp->fptr = 0;
  1353. fp->csect = 1;
  1354. fp->fs = fs;
  1355. return FR_OK;
  1356. }
  1357. /*-----------------------------------------------------------------------*/
  1358. /* Read File */
  1359. /*-----------------------------------------------------------------------*/
  1360. FRESULT f_read (
  1361. FIL *fp, /* Pointer to the file object */
  1362. void *buff, /* Pointer to data buffer */
  1363. UINT btr, /* Number of bytes to read */
  1364. UINT *br /* Pointer to number of bytes read */
  1365. )
  1366. {
  1367. FRESULT res;
  1368. DWORD clust, sect, remain;
  1369. UINT rcnt, cc;
  1370. BYTE *rbuff = buff;
  1371. FATFS *fs = fp->fs;
  1372. *br = 0;
  1373. res = validate(fs /*, fp->id*/); /* Check validity of the object */
  1374. if (res != FR_OK) return res;
  1375. if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
  1376. if (!(fp->flag & FA_READ)) return FR_DENIED; /* Check access mode */
  1377. remain = fp->fsize - fp->fptr;
  1378. if (btr > remain) btr = (UINT)remain; /* Truncate read count by number of bytes left */
  1379. for ( ; btr; /* Repeat until all data transferred */
  1380. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  1381. if ((fp->fptr & (SS(fs) - 1)) == 0) { /* On the sector boundary */
  1382. if (--fp->csect) { /* Decrement left sector counter */
  1383. sect = fp->curr_sect + 1; /* Get current sector */
  1384. } else { /* On the cluster boundary, get next cluster */
  1385. clust = (fp->fptr == 0) ?
  1386. fp->org_clust : get_cluster(fs, fp->curr_clust);
  1387. if (clust < 2 || clust >= fs->max_clust)
  1388. goto fr_error;
  1389. fp->curr_clust = clust; /* Current cluster */
  1390. sect = clust2sect(fs, clust); /* Get current sector */
  1391. fp->csect = fs->csize; /* Re-initialize the left sector counter */
  1392. }
  1393. #if !_FS_READONLY
  1394. if(!move_fp_window(fp,0)) goto fr_error;
  1395. #endif
  1396. fp->curr_sect = sect; /* Update current sector */
  1397. cc = btr / SS(fs); /* When left bytes >= SS(fs), */
  1398. if (cc) { /* Read maximum contiguous sectors directly */
  1399. if (cc > fp->csect) cc = fp->csect;
  1400. if(SPI_OFFLOAD) {
  1401. SD_SPI_OFFLOAD = 1;
  1402. }
  1403. if (disk_read(fs->drive, rbuff, sect, (BYTE)cc) != RES_OK)
  1404. goto fr_error;
  1405. SD_SPI_OFFLOAD = 0;
  1406. fp->csect -= (BYTE)(cc - 1);
  1407. fp->curr_sect += cc - 1;
  1408. rcnt = cc * SS(fs);
  1409. continue;
  1410. }
  1411. }
  1412. if(btr) { /* if we actually have bytes to read in singles, copy them in */
  1413. rcnt = SS(fs) - ((WORD)fp->fptr & (SS(fs) - 1)); /* Copy fractional bytes from file I/O buffer */
  1414. if (rcnt > btr) rcnt = btr;
  1415. if(!move_fp_window(fp,fp->curr_sect)) goto fr_error; /* are we there or not? */
  1416. memcpy(rbuff, &FPBUF.data[fp->fptr & (SS(fs) - 1)], rcnt);
  1417. }
  1418. }
  1419. SPI_OFFLOAD = 0;
  1420. return FR_OK;
  1421. fr_error: /* Abort this file due to an unrecoverable error */
  1422. fp->flag |= FA__ERROR;
  1423. SPI_OFFLOAD = 0;
  1424. SD_SPI_OFFLOAD = 0;
  1425. return FR_RW_ERROR;
  1426. }
  1427. #if !_FS_READONLY
  1428. /*-----------------------------------------------------------------------*/
  1429. /* Write File */
  1430. /*-----------------------------------------------------------------------*/
  1431. FRESULT f_write (
  1432. FIL *fp, /* Pointer to the file object */
  1433. const void *buff, /* Pointer to the data to be written */
  1434. UINT btw, /* Number of bytes to write */
  1435. UINT *bw /* Pointer to number of bytes written */
  1436. )
  1437. {
  1438. FRESULT res;
  1439. DWORD clust, sect;
  1440. UINT wcnt, cc;
  1441. const BYTE *wbuff = buff;
  1442. FATFS *fs = fp->fs;
  1443. *bw = 0;
  1444. res = validate(fs /*, fp->id*/); /* Check validity of the object */
  1445. if (res != FR_OK) return res;
  1446. if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
  1447. if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
  1448. if (fp->fsize + btw < fp->fsize) return FR_OK; /* File size cannot reach 4GB */
  1449. for ( ; btw; /* Repeat until all data transferred */
  1450. wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
  1451. if ((fp->fptr & (SS(fs) - 1)) == 0) { /* On the sector boundary */
  1452. if (--fp->csect) { /* Decrement left sector counter */
  1453. sect = fp->curr_sect + 1; /* Get current sector */
  1454. } else { /* On the cluster boundary, get next cluster */
  1455. if (fp->fptr == 0) { /* Is top of the file */
  1456. clust = fp->org_clust;
  1457. if (clust == 0) /* No cluster is created yet */
  1458. fp->org_clust = clust = create_chain(fs, 0); /* Create a new cluster chain */
  1459. } else { /* Middle or end of file */
  1460. clust = create_chain(fs, fp->curr_clust); /* Trace or streach cluster chain */
  1461. }
  1462. if (clust == 0) break; /* Disk full */
  1463. if (clust == 1 || clust >= fs->max_clust) goto fw_error;
  1464. fp->curr_clust = clust; /* Current cluster */
  1465. sect = clust2sect(fs, clust); /* Get current sector */
  1466. fp->csect = fs->csize; /* Re-initialize the left sector counter */
  1467. }
  1468. if(!move_fp_window(fp,0)) goto fw_error;
  1469. fp->curr_sect = sect; /* Update current sector */
  1470. cc = btw / SS(fs); /* When left bytes >= SS(fs), */
  1471. if (cc) { /* Write maximum contiguous sectors directly */
  1472. if (cc > fp->csect) cc = fp->csect;
  1473. if (disk_write(fs->drive, wbuff, sect, (BYTE)cc) != RES_OK) goto fw_error;
  1474. fp->csect -= (BYTE)(cc - 1);
  1475. fp->curr_sect += cc - 1;
  1476. wcnt = cc * SS(fs);
  1477. continue;
  1478. }
  1479. }
  1480. if(btw) {
  1481. wcnt = SS(fs) - ((WORD)fp->fptr & (SS(fs) - 1)); /* Copy fractional bytes to file I/O buffer */
  1482. if (wcnt > btw) wcnt = btw;
  1483. if (
  1484. #if _USE_1_BUF == 0
  1485. fp->fptr < fp->fsize && /* Fill sector buffer with file data if needed */
  1486. #endif
  1487. !move_fp_window(fp,fp->curr_sect)) goto fw_error;
  1488. memcpy(&FPBUF.data[fp->fptr & (SS(fs) - 1)], wbuff, wcnt);
  1489. FPBUF.dirty=TRUE;
  1490. }
  1491. }
  1492. if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
  1493. fp->flag |= FA__WRITTEN; /* Set file changed flag */
  1494. return FR_OK;
  1495. fw_error: /* Abort this file due to an unrecoverable error */
  1496. fp->flag |= FA__ERROR;
  1497. return FR_RW_ERROR;
  1498. }
  1499. /*-----------------------------------------------------------------------*/
  1500. /* Synchronize the file object */
  1501. /*-----------------------------------------------------------------------*/
  1502. FRESULT f_sync (
  1503. FIL *fp /* Pointer to the file object */
  1504. )
  1505. {
  1506. FRESULT res;
  1507. DWORD tim;
  1508. BYTE *dir;
  1509. FATFS *fs = fp->fs;
  1510. res = validate(fs /*, fp->id*/); /* Check validity of the object */
  1511. if (res == FR_OK) {
  1512. if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
  1513. /* Write back data buffer if needed */
  1514. if(!move_fp_window(fp,0)) return FR_RW_ERROR;
  1515. /* Update the directory entry */
  1516. if (!move_fs_window(fs, fp->dir_sect))
  1517. return FR_RW_ERROR;
  1518. dir = fp->dir_ptr;
  1519. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  1520. ST_DWORD(&dir[DIR_FileSize], fp->fsize); /* Update file size */
  1521. ST_WORD(&dir[DIR_FstClusLO], fp->org_clust); /* Update start cluster */
  1522. ST_WORD(&dir[DIR_FstClusHI], fp->org_clust >> 16);
  1523. tim = get_fattime(); /* Updated time */
  1524. ST_DWORD(&dir[DIR_WrtTime], tim);
  1525. fp->flag &= (BYTE)~FA__WRITTEN;
  1526. res = sync(fs);
  1527. }
  1528. }
  1529. return res;
  1530. }
  1531. #endif /* !_FS_READONLY */
  1532. /*-----------------------------------------------------------------------*/
  1533. /* Close File */
  1534. /*-----------------------------------------------------------------------*/
  1535. FRESULT f_close (
  1536. FIL *fp /* Pointer to the file object to be closed */
  1537. )
  1538. {
  1539. FRESULT res;
  1540. #if !_FS_READONLY
  1541. res = f_sync(fp);
  1542. #else
  1543. res = validate(fp->fs /*, fp->id*/);
  1544. #endif
  1545. if (res == FR_OK) fp->fs = NULL;
  1546. return res;
  1547. }
  1548. #if _FS_MINIMIZE <= 2
  1549. /*-----------------------------------------------------------------------*/
  1550. /* Seek File R/W Pointer */
  1551. /*-----------------------------------------------------------------------*/
  1552. FRESULT f_lseek (
  1553. FIL *fp, /* Pointer to the file object */
  1554. DWORD ofs /* File pointer from top of file */
  1555. )
  1556. {
  1557. FRESULT res;
  1558. DWORD clust, csize;
  1559. CHAR csect;
  1560. FATFS *fs = fp->fs;
  1561. res = validate(fs /*, fp->id*/); /* Check validity of the object */
  1562. if (res != FR_OK) return res;
  1563. if (fp->flag & FA__ERROR) return FR_RW_ERROR;
  1564. if (fp->fptr == ofs) /* Don't seek if the target is the current position */
  1565. return FR_OK;
  1566. if (!move_fp_window(fp,0)) goto fk_error; /* JLB not sure I need this. */
  1567. if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
  1568. #if !_FS_READONLY
  1569. && !(fp->flag & FA_WRITE)
  1570. #endif
  1571. ) ofs = fp->fsize;
  1572. /* Move file R/W pointer if needed */
  1573. if (ofs) {
  1574. csize = (DWORD)fs->csize * SS(fs); /* Cluster size in unit of byte */
  1575. if(ofs/csize == (fp->fptr-1)/csize) {
  1576. /* Source and Target are in the same cluster. Just reset sector fields */
  1577. fp->fptr = ofs;
  1578. ofs-=(((DWORD)(ofs/csize))*csize); /* subtract off up to current cluster */
  1579. } else {
  1580. fp->csect = 1;
  1581. if(fp->fptr && ofs > fp->fptr) {
  1582. fp->fptr = (((DWORD)((fp->fptr-1)/csize))*csize); /* Set file R/W pointer to start of cluster */
  1583. ofs-=fp->fptr; /* subtract off clusters traversed */
  1584. clust = fp->curr_clust; /* Get current cluster */
  1585. } else {
  1586. fp->fptr = 0; /* Set file R/W pointer to top of the file */
  1587. clust = fp->org_clust; /* Get start cluster */
  1588. }
  1589. #if !_FS_READONLY
  1590. if (clust == 0) { /* If the file does not have a cluster chain, create new cluster chain */
  1591. clust = create_chain(fs, 0);
  1592. if (clust == 1) goto fk_error;
  1593. fp->org_clust = clust;
  1594. }
  1595. #endif
  1596. if (clust) { /* If the file has a cluster chain, it can be followed */
  1597. for (;;) { /* Loop to skip leading clusters */
  1598. fp->curr_clust = clust; /* Update current cluster */
  1599. if (ofs <= csize) break;
  1600. #if !_FS_READONLY
  1601. if (fp->flag & FA_WRITE) /* Check if in write mode or not */
  1602. clust = create_chain(fs, clust); /* Force streached if in write mode */
  1603. else
  1604. #endif
  1605. clust = get_cluster(fs, clust); /* Only follow cluster chain if not in write mode */
  1606. if (clust == 0) { /* Stop if could not follow the cluster chain */
  1607. ofs = csize; break;
  1608. }
  1609. if (clust < 2 || clust >= fs->max_clust) goto fk_error;
  1610. fp->fptr += csize; /* Update R/W pointer */
  1611. ofs -= csize;
  1612. }
  1613. fp->fptr += ofs; /* Update file R/W pointer */
  1614. }
  1615. }
  1616. csect = (CHAR)((ofs - 1) / SS(fs)); /* Sector offset in the cluster */
  1617. fp->curr_sect = clust2sect(fs, fp->curr_clust) + csect; /* Current sector */
  1618. fp->csect = fs->csize - csect; /* Left sector counter in the cluster */
  1619. } else {
  1620. fp->fptr = 0; fp->csect = 1; /* Set file R/W pointer to top of the file */
  1621. }
  1622. #if !_FS_READONLY
  1623. if (fp->fptr > fp->fsize) { /* Set changed flag if the file was extended */
  1624. fp->fsize = fp->fptr;
  1625. fp->flag |= FA__WRITTEN;
  1626. }
  1627. #endif
  1628. return FR_OK;
  1629. fk_error: /* Abort this file due to an unrecoverable error */
  1630. fp->flag |= FA__ERROR;
  1631. return FR_RW_ERROR;
  1632. }
  1633. #if _FS_MINIMIZE <= 1
  1634. /*-----------------------------------------------------------------------*/
  1635. /* Create a directroy object */
  1636. /*-----------------------------------------------------------------------*/
  1637. FRESULT f_opendir (
  1638. #if _USE_DRIVE_PREFIX == 0
  1639. FATFS *fs, /* Pointer to file system object */
  1640. #endif
  1641. DIR *dj, /* Pointer to directory object to create */
  1642. const UCHAR *path /* Pointer to the directory path */
  1643. )
  1644. {
  1645. FRESULT res;
  1646. BYTE *dir;
  1647. UCHAR fn[8+3+1];
  1648. #if _USE_DRIVE_PREFIX != 0
  1649. FATFS *fs;
  1650. #endif
  1651. #if _USE_LFN != 0
  1652. DIR fileobj;
  1653. const UCHAR* spath;
  1654. UINT len;
  1655. #endif
  1656. res = auto_mount(&path, &fs, 0);
  1657. if (res == FR_OK) {
  1658. dj->fs = fs;
  1659. #if _USE_LFN != 0
  1660. res = trace_path(dj, fn, path, &dir, &fileobj, &spath, &len);
  1661. #else
  1662. res = trace_path(dj, fn, path, &dir); /* trace the file path */
  1663. #endif
  1664. if (res == FR_OK) { /* Trace completed */
  1665. if (dir != NULL) { /* It is not the root dir */
  1666. if (dir[DIR_Attr] & AM_DIR) { /* The entry is a directory */
  1667. dj->clust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
  1668. dj->sect = clust2sect(fs, dj->clust);
  1669. #if _USE_CHDIR != 0 || _USE_CURR_DIR != 0
  1670. dj->index = 0;
  1671. #else
  1672. dj->index = 2;
  1673. #endif
  1674. } else { /* The entry is not a directory */
  1675. res = FR_NO_FILE;
  1676. }
  1677. }
  1678. //dj->id = fs->id;
  1679. }
  1680. }
  1681. return res;
  1682. }
  1683. /**
  1684. * l_opendir - open a directory by cluster number
  1685. * @fs : Pointer to the FATFS structure of the target file system
  1686. * @dj : Pointer to the DIR structure to be filled
  1687. * @cluster: Number of the start cluster of the directory (0=root)
  1688. *
  1689. * This functions works like f_opendir, but instead of a path the directory
  1690. * to be opened is specified by the FATFS structure and the starting cluster
  1691. * number. Use 0 for the cluster to open the root directory.
  1692. * Always returns FR_OK.
  1693. */
  1694. FRESULT l_opendir(FATFS* fs, DWORD cluster, DIR *dj) {
  1695. dj->fs = fs;
  1696. //dj->id = fs->id;
  1697. if (cluster == 0) {
  1698. /* Open the root directory */
  1699. cluster = fs->dirbase;
  1700. if (fs->fs_type == FS_FAT32) {
  1701. dj->clust = dj->sclust = cluster;
  1702. dj->sect = clust2sect(fs, cluster);
  1703. } else {
  1704. dj->clust = dj->sclust = 0;
  1705. dj->sect = cluster;
  1706. }
  1707. dj->index = 0;
  1708. } else {
  1709. /* Open a non-root directory */
  1710. dj->clust = dj->sclust = cluster;
  1711. dj->sect = clust2sect(fs, cluster);
  1712. #if _USE_CHDIR != 0 || _USE_CURR_DIR != 0
  1713. dj->index = 0;
  1714. #else
  1715. dj->index = 2;
  1716. #endif
  1717. }
  1718. return FR_OK;
  1719. }
  1720. /*-----------------------------------------------------------------------*/
  1721. /* Read Directory Entry in Sequense */
  1722. /*-----------------------------------------------------------------------*/
  1723. FRESULT f_readdir (
  1724. DIR *dj, /* Pointer to the directory object */
  1725. FILINFO *finfo /* Pointer to file information to return */
  1726. )
  1727. {
  1728. BYTE *dir, c, res;
  1729. FATFS *fs = dj->fs;
  1730. #if _USE_LFN != 0
  1731. WORD len=0;
  1732. BYTE i,pos;
  1733. # ifdef _MAX_LFN_LENGTH
  1734. BOOL skiplfn = FALSE;
  1735. # endif
  1736. if (finfo->lfn) {
  1737. finfo->lfn[0]=0; /* set first char to null */
  1738. # if _USE_LFN_DBCS != 0
  1739. finfo->lfn[1]=0;
  1740. # endif
  1741. }
  1742. #endif
  1743. res = validate(fs /*, dj->id*/); /* Check validity of the object */
  1744. if (res != FR_OK) return res;
  1745. finfo->fname[0] = 0;
  1746. while (dj->sect) {
  1747. if (!move_fs_window(fs, dj->sect))
  1748. return FR_RW_ERROR;
  1749. dir = &FSBUF.data[(dj->index & ((SS(fs) - 1) >> 5)) * 32]; /* pointer to the directory entry */
  1750. c = dir[DIR_Name];
  1751. if (c == 0) break; /* Has it reached to end of dir? */
  1752. #if _USE_LFN != 0
  1753. if (c != 0xE5) { /* Is it a valid entry? */
  1754. if(finfo->lfn && ((dir[DIR_Attr] & AM_LFN) == AM_LFN)) {
  1755. pos=((*dir & 0x1f)-1)*S_LFN_OFFSET; /* get offset */
  1756. # ifdef _MAX_LFN_LENGTH
  1757. if (skiplfn || pos >= _MAX_LFN_LENGTH * S_LFN_INCREMENT) {
  1758. skiplfn = TRUE;
  1759. goto skippedlfn;
  1760. }
  1761. # endif
  1762. i=0;
  1763. while(i<13) {
  1764. if(!dir[pgm_read_byte(LFN_pos+i)] && !dir[pgm_read_byte(LFN_pos+i)+1])
  1765. break;
  1766. if (pos >= _MAX_LFN_LENGTH) {
  1767. len = 0;
  1768. i = 0;
  1769. skiplfn = TRUE;
  1770. break;
  1771. }
  1772. finfo->lfn[pos]=dir[pgm_read_byte(LFN_pos+i)];
  1773. # if _USE_LFN_DBCS != 0
  1774. finfo->lfn[pos+1]=dir[pgm_read_byte(LFN_pos+i)+1];
  1775. # endif
  1776. pos+=S_LFN_INCREMENT;
  1777. i++;
  1778. }
  1779. len+=i;
  1780. } else {
  1781. # ifdef _MAX_LFN_LENGTH
  1782. skiplfn = FALSE;
  1783. # endif
  1784. if (finfo->lfn) {
  1785. finfo->lfn[len*S_LFN_INCREMENT]=0;
  1786. # if _USE_LFN_DBCS != 0
  1787. finfo->lfn[len*S_LFN_INCREMENT+1]=0;
  1788. # endif
  1789. }
  1790. get_fileinfo(finfo, dir);
  1791. }
  1792. }
  1793. # ifdef _MAX_LFN_LENGTH
  1794. skippedlfn:
  1795. #endif
  1796. #else
  1797. if (c != 0xE5 && ((dir[DIR_Attr] & AM_LFN) != AM_LFN)) /* Is it a valid entry? */
  1798. get_fileinfo(finfo, dir);
  1799. #endif
  1800. if (!next_dir_entry(dj)) dj->sect = 0; /* Next entry */
  1801. if (finfo->fname[0]) break; /* Found valid entry */
  1802. }
  1803. return FR_OK;
  1804. }
  1805. #if _FS_MINIMIZE == 0
  1806. /*-----------------------------------------------------------------------*/
  1807. /* Get File Status */
  1808. /*-----------------------------------------------------------------------*/
  1809. FRESULT f_stat (
  1810. #if _USE_DRIVE_PREFIX == 0
  1811. FATFS *fs, /* Pointer to file system object */
  1812. #endif
  1813. const UCHAR *path, /* Pointer to the file path */
  1814. FILINFO *finfo /* Pointer to file information to return */
  1815. )
  1816. {
  1817. FRESULT res;
  1818. DIR dj;
  1819. BYTE *dir;
  1820. UCHAR fn[8+3+1];
  1821. #if _USE_DRIVE_PREFIX != 0
  1822. FATFS *fs;
  1823. #endif
  1824. #if _USE_LFN != 0
  1825. DIR fileobj;
  1826. const UCHAR* spath;
  1827. UINT len;
  1828. #endif
  1829. res = auto_mount(&path, &fs, 0);
  1830. if (res == FR_OK) {
  1831. dj.fs = fs;
  1832. #if _USE_LFN != 0
  1833. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len);
  1834. #else
  1835. res = trace_path(&dj, fn, path, &dir); /* trace the file path */
  1836. #endif
  1837. if (res == FR_OK) { /* Trace completed */
  1838. if (dir) /* Found an object */
  1839. get_fileinfo(finfo, dir);
  1840. else /* It is root dir */
  1841. res = FR_INVALID_NAME;
  1842. }
  1843. }
  1844. return res;
  1845. }
  1846. #if !_FS_READONLY
  1847. /*-----------------------------------------------------------------------*/
  1848. /* Truncate File */
  1849. /*-----------------------------------------------------------------------*/
  1850. # if _USE_TRUNCATE
  1851. FRESULT f_truncate (
  1852. FIL *fp /* Pointer to the file object */
  1853. )
  1854. {
  1855. FRESULT res;
  1856. DWORD ncl;
  1857. FATFS *fs=fp->fs;
  1858. res = validate(fs /*, fp->id */); /* Check validity of the object */
  1859. if (res != FR_OK) return res;
  1860. if (fp->flag & FA__ERROR) return FR_RW_ERROR; /* Check error flag */
  1861. if (!(fp->flag & FA_WRITE)) return FR_DENIED; /* Check access mode */
  1862. if (fp->fsize > fp->fptr) {
  1863. fp->fsize = fp->fptr; /* Set file size to current R/W point */
  1864. fp->flag |= FA__WRITTEN;
  1865. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  1866. if (!remove_chain(fp->fs, fp->org_clust)) goto ft_error;
  1867. fp->org_clust = 0;
  1868. } else { /* When truncate a part of the file, remove remaining clusters */
  1869. ncl = get_cluster(fp->fs, fp->curr_clust);
  1870. if (ncl < 2) goto ft_error;
  1871. if (ncl < fp->fs->max_clust) {
  1872. if (!put_cluster(fp->fs, fp->curr_clust, 0x0FFFFFFF)) goto ft_error;
  1873. if (!remove_chain(fp->fs, ncl)) goto ft_error;
  1874. }
  1875. }
  1876. }
  1877. return FR_OK;
  1878. ft_error: /* Abort this file due to an unrecoverable error */
  1879. fp->flag |= FA__ERROR;
  1880. return FR_RW_ERROR;
  1881. }
  1882. #endif
  1883. /*-----------------------------------------------------------------------*/
  1884. /* Get Number of Free Clusters, stop if maxclust found */
  1885. /*-----------------------------------------------------------------------*/
  1886. FRESULT l_getfree (
  1887. FATFS *fs, /* Pointer to file system object */
  1888. const UCHAR *drv, /* Pointer to the logical drive number (root dir) */
  1889. DWORD *nclust, /* Pointer to the variable to return number of free clusters */
  1890. DWORD maxclust /* Stop after maxclust free clusters were found (0 = no limit) */
  1891. )
  1892. {
  1893. FRESULT res;
  1894. DWORD n, clust, sect;
  1895. BYTE fat, f, *p;
  1896. /* Get drive number */
  1897. res = auto_mount(&drv, &fs, 0);
  1898. if (res != FR_OK) return res;
  1899. /* If number of free cluster is valid, return it without cluster scan. */
  1900. if (fs->free_clust <= fs->max_clust - 2) {
  1901. *nclust = fs->free_clust;
  1902. return FR_OK;
  1903. }
  1904. /* Get number of free clusters */
  1905. fat = fs->fs_type;
  1906. n = 0;
  1907. if (fat == FS_FAT12) {
  1908. clust = 2;
  1909. do {
  1910. if ((WORD)get_cluster(fs, clust) == 0) n++;
  1911. } while (++clust < fs->max_clust);
  1912. } else {
  1913. clust = fs->max_clust;
  1914. sect = fs->fatbase;
  1915. f = 0; p = 0;
  1916. do {
  1917. if (maxclust && n >= maxclust) {
  1918. n = maxclust;
  1919. break;
  1920. }
  1921. if (!f) {
  1922. if (!move_fs_window(fs, sect++)) return FR_RW_ERROR;
  1923. p = FSBUF.data;
  1924. }
  1925. if (fat == FS_FAT16) {
  1926. if (LD_WORD(p) == 0) n++;
  1927. p += 2; f += 1;
  1928. } else {
  1929. if (LD_DWORD(p) == 0) n++;
  1930. p += 4; f += 2;
  1931. }
  1932. } while (--clust);
  1933. }
  1934. if (n < maxclust) {
  1935. fs->free_clust = n;
  1936. #if _USE_FSINFO
  1937. if (fat == FS_FAT32) fs->fsi_flag = 1;
  1938. #endif
  1939. }
  1940. *nclust = n;
  1941. return FR_OK;
  1942. }
  1943. /*-----------------------------------------------------------------------*/
  1944. /* Get Number of Free Clusters */
  1945. /*-----------------------------------------------------------------------*/
  1946. FRESULT f_getfree (
  1947. #if _USE_DRIVE_PREFIX == 0
  1948. FATFS *fs, /* Pointer to file system object */
  1949. #endif
  1950. const UCHAR *drv, /* Pointer to the logical drive number (root dir) */
  1951. DWORD *nclust /* Pointer to the variable to return number of free clusters */
  1952. #if _USE_DRIVE_PREFIX != 0
  1953. ,FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
  1954. #endif
  1955. )
  1956. {
  1957. FRESULT res;
  1958. #if _USE_DRIVE_PREFIX != 0
  1959. FATFS *fs;
  1960. #endif
  1961. /* Get drive number */
  1962. res = auto_mount(&drv, &fs, 0);
  1963. if (res != FR_OK) return res;
  1964. #if _USE_DRIVE_PREFIX != 0
  1965. *fatfs = fs;
  1966. #endif
  1967. return l_getfree(fs, drv, nclust, 0);
  1968. }
  1969. /*-----------------------------------------------------------------------*/
  1970. /* Delete a File or Directory */
  1971. /*-----------------------------------------------------------------------*/
  1972. FRESULT f_unlink (
  1973. #if _USE_DRIVE_PREFIX == 0
  1974. FATFS *fs, /* Pointer to file system object */
  1975. #endif
  1976. const UCHAR *path /* Pointer to the file or directory path */
  1977. )
  1978. {
  1979. FRESULT res;
  1980. DIR dj;
  1981. BYTE *dir, *sdir;
  1982. DWORD dclust, dsect;
  1983. UCHAR fn[8+3+1];
  1984. #if _USE_DRIVE_PREFIX != 0
  1985. FATFS *fs;
  1986. #endif
  1987. #if _USE_LFN != 0
  1988. DIR fileobj;
  1989. const UCHAR* spath;
  1990. UINT len;
  1991. #endif
  1992. res = auto_mount(&path, &fs, 1);
  1993. if (res != FR_OK) return res;
  1994. dj.fs = fs;
  1995. #if _USE_LFN != 0
  1996. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len);
  1997. #else
  1998. res = trace_path(&dj, fn, path, &dir); /* trace the file path */
  1999. #endif
  2000. if (res != FR_OK) return res; /* Trace failed */
  2001. if (dir == NULL) return FR_INVALID_NAME; /* It is the root directory */
  2002. if (dir[DIR_Attr] & AM_RDO) return FR_DENIED; /* It is a R/O object */
  2003. # if _USE_CHDIR != 0
  2004. if(fn[0]=='.')
  2005. return FR_INVALID_NAME;
  2006. # endif
  2007. dsect = FSBUF.sect;
  2008. dclust = ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) | LD_WORD(&dir[DIR_FstClusLO]);
  2009. if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */
  2010. #if _USE_CHDIR != 0 || _USE_CURR_DIR != 0
  2011. if (dclust == fs->curr_dir) /* Never delete the current directory */
  2012. return FR_DIR_NOT_EMPTY;
  2013. #endif
  2014. dj.clust = dclust; /* Check if the sub-dir is empty or not */
  2015. dj.sect = clust2sect(fs, dclust);
  2016. dj.index = 2;
  2017. do {
  2018. if (!move_fs_window(fs, dj.sect)) return FR_RW_ERROR;
  2019. sdir = &FSBUF.data[(dj.index & ((SS(fs) - 1) >> 5)) * 32];
  2020. if (sdir[DIR_Name] == 0) break;
  2021. if (sdir[DIR_Name] != 0xE5 && !(sdir[DIR_Attr] & AM_VOL))
  2022. return FR_DIR_NOT_EMPTY; /* The directory is not empty */
  2023. } while (next_dir_entry(&dj));
  2024. }
  2025. #if _USE_LFN != 0
  2026. len=(len+25)/13;
  2027. while(len--) {
  2028. if (!move_fs_window(fs, fileobj.sect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */
  2029. dir = &FSBUF.data[(fileobj.index & ((SS(fs) - 1) >> 5)) * 32];
  2030. dir[DIR_Name] = 0xE5;
  2031. FSBUF.dirty = TRUE;
  2032. if (len && !next_dir_entry(&fileobj)) /* Next directory pointer */
  2033. return FR_RW_ERROR;
  2034. }
  2035. #else
  2036. if (!move_fs_window(fs, dsect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */
  2037. dir[DIR_Name] = 0xE5;
  2038. FSBUF.dirty = TRUE;
  2039. #endif
  2040. if (!remove_chain(fs, dclust)) return FR_RW_ERROR; /* Remove the cluster chain */
  2041. return sync(fs);
  2042. }
  2043. /*-----------------------------------------------------------------------*/
  2044. /* Create a Directory */
  2045. /*-----------------------------------------------------------------------*/
  2046. FRESULT f_mkdir (
  2047. #if _USE_DRIVE_PREFIX == 0
  2048. FATFS *fs, /* Pointer to file system object */
  2049. #endif
  2050. const UCHAR *path /* Pointer to the directory path */
  2051. )
  2052. {
  2053. FRESULT res;
  2054. DIR dj;
  2055. BYTE *dir, *fw, n;
  2056. UCHAR fn[8+3+1];
  2057. DWORD sect, dsect, dclust, pclust, tim;
  2058. #if _USE_DRIVE_PREFIX != 0
  2059. FATFS *fs;
  2060. #endif
  2061. #if _USE_LFN != 0
  2062. UINT len;
  2063. DIR fileobj;
  2064. const UCHAR* spath;
  2065. #endif
  2066. res = auto_mount(&path, &fs, 1);
  2067. if (res != FR_OK) return res;
  2068. dj.fs = fs;
  2069. #if _USE_LFN != 0
  2070. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len);
  2071. #else
  2072. res = trace_path(&dj, fn, path, &dir); /* trace the file path */
  2073. #endif
  2074. if (res == FR_OK) return FR_EXIST; /* Any file or directory is already existing */
  2075. if (res != FR_NO_FILE) return res;
  2076. #if _USE_CHDIR != 0
  2077. if(fn[0]=='.')
  2078. return FR_INVALID_NAME;
  2079. #endif
  2080. #if _USE_LFN != 0
  2081. res = reserve_direntry(&dj, &dir,len); /* Reserve a directory entry */
  2082. #else
  2083. res = reserve_direntry(&dj, &dir); /* Reserve a directory entry */
  2084. #endif
  2085. if (res != FR_OK) return res;
  2086. sect = FSBUF.sect;
  2087. dclust = create_chain(fs, 0); /* Allocate a cluster for new directory table */
  2088. if (dclust == 1) return FR_RW_ERROR;
  2089. dsect = clust2sect(fs, dclust);
  2090. if (!dsect) return FR_DENIED;
  2091. if (!move_fs_window(fs, dsect)) return FR_RW_ERROR;
  2092. fw = FSBUF.data;
  2093. memset(fw, 0, SS(fs)); /* Clear the new directory table */
  2094. for (n = 1; n < fs->csize; n++) {
  2095. if (disk_write(fs->drive, fw, ++dsect, 1) != RES_OK)
  2096. return FR_RW_ERROR;
  2097. }
  2098. memset(&fw[DIR_Name], ' ', 8+3); /* Create "." entry */
  2099. fw[DIR_Name] = '.';
  2100. fw[DIR_Attr] = AM_DIR;
  2101. tim = get_fattime();
  2102. ST_DWORD(&fw[DIR_WrtTime], tim);
  2103. memcpy(&fw[32], &fw[0], 32); fw[33] = '.'; /* Create ".." entry */
  2104. ST_WORD(&fw[ DIR_FstClusLO], dclust);
  2105. ST_WORD(&fw[ DIR_FstClusHI], dclust >> 16);
  2106. pclust = dj.sclust;
  2107. if (fs->fs_type == FS_FAT32 && pclust == fs->dirbase) pclust = 0;
  2108. ST_WORD(&fw[32+DIR_FstClusLO], pclust);
  2109. ST_WORD(&fw[32+DIR_FstClusHI], pclust >> 16);
  2110. FSBUF.dirty = TRUE;
  2111. if (!move_fs_window(fs, sect)) return FR_RW_ERROR;
  2112. #if _USE_LFN != 0
  2113. if(len && add_direntry(&dj,&dir,spath,len,fn)) return FR_RW_ERROR;
  2114. #endif
  2115. memset(&dir[0], 0, 32); /* Initialize the new entry */
  2116. memcpy(&dir[DIR_Name], fn, 8+3); /* Name */
  2117. dir[DIR_NTres] = fn[11];
  2118. FSBUF.dirty = TRUE;
  2119. dir[DIR_Attr] = AM_DIR; /* Attribute */
  2120. ST_DWORD(&dir[DIR_WrtTime], tim); /* Crated time */
  2121. ST_WORD(&dir[DIR_FstClusLO], dclust); /* Table start cluster */
  2122. ST_WORD(&dir[DIR_FstClusHI], dclust >> 16);
  2123. return sync(fs);
  2124. }
  2125. #if _USE_CHDIR != 0
  2126. /*-----------------------------------------------------------------------*/
  2127. /* Change the current directory */
  2128. /*-----------------------------------------------------------------------*/
  2129. FRESULT f_chdir (
  2130. #if _USE_DRIVE_PREFIX == 0
  2131. FATFS *fs, /* Pointer to file system object */
  2132. #endif
  2133. const UCHAR *path /* Pointer to the file name */
  2134. )
  2135. {
  2136. #if _USE_DRIVE_PREFIX != 0
  2137. FATFS *fs;
  2138. #endif
  2139. FRESULT res;
  2140. BYTE *dir;
  2141. DIR dj;
  2142. UCHAR fn[8+3+1];
  2143. #if _USE_LFN != 0
  2144. UINT len;
  2145. DIR fileobj;
  2146. const UCHAR* spath;
  2147. #endif
  2148. res = auto_mount(&path, &fs, 0);
  2149. if (res != FR_OK) return res;
  2150. dj.fs = fs;
  2151. /* Trace the file path */
  2152. #if _USE_LFN != 0
  2153. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len);
  2154. #else
  2155. res = trace_path(&dj, fn, path, &dir); /* trace the file path */
  2156. #endif
  2157. if (res == FR_OK) {
  2158. if (dir == NULL) {
  2159. fs->curr_dir = 0;
  2160. } else if (dir[DIR_Attr] & AM_DIR) {
  2161. fs->curr_dir =
  2162. ((DWORD)LD_WORD(&dir[DIR_FstClusHI]) << 16) |
  2163. LD_WORD(&dir[DIR_FstClusLO]);
  2164. } else
  2165. return FR_NOT_DIRECTORY;
  2166. }
  2167. return res;
  2168. }
  2169. #endif
  2170. /*-----------------------------------------------------------------------*/
  2171. /* Change File Attribute */
  2172. /*-----------------------------------------------------------------------*/
  2173. FRESULT f_chmod (
  2174. #if _USE_DRIVE_PREFIX == 0
  2175. FATFS *fs, /* Pointer to file system object */
  2176. #endif
  2177. const UCHAR *path, /* Pointer to the file path */
  2178. BYTE value, /* Attribute bits */
  2179. BYTE mask /* Attribute mask to change */
  2180. )
  2181. {
  2182. FRESULT res;
  2183. DIR dj;
  2184. BYTE *dir;
  2185. UCHAR fn[8+3+1];
  2186. #if _USE_DRIVE_PREFIX != 0
  2187. FATFS *fs;
  2188. #endif
  2189. #if _USE_LFN != 0
  2190. UINT len;
  2191. DIR fileobj;
  2192. const UCHAR* spath;
  2193. #endif
  2194. res = auto_mount(&path, &fs, 1);
  2195. if (res == FR_OK) {
  2196. dj.fs = fs;
  2197. #if _USE_LFN != 0
  2198. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len); /* trace the file path */
  2199. #else
  2200. res = trace_path(&dj, fn, path, &dir); /* trace the file path */
  2201. #endif
  2202. if (res == FR_OK) { /* Trace completed */
  2203. if (!dir || fn[0]=='.') {
  2204. res = FR_INVALID_NAME; /* Root directory */
  2205. } else {
  2206. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  2207. dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  2208. res = sync(fs);
  2209. }
  2210. }
  2211. }
  2212. return res;
  2213. }
  2214. /*-----------------------------------------------------------------------*/
  2215. /* Change Timestamp */
  2216. /*-----------------------------------------------------------------------*/
  2217. #if _USE_UTIME
  2218. FRESULT f_utime (
  2219. #if _USE_DRIVE_PREFIX == 0
  2220. FATFS *fs, /* Pointer to file system object */
  2221. #endif
  2222. const UCHAR *path, /* Pointer to the file/directory name */
  2223. const FILINFO *finfo /* Pointer to the timestamp to be set */
  2224. )
  2225. {
  2226. #if _USE_DRIVE_PREFIX != 0
  2227. FATFS *fs;
  2228. #endif
  2229. FRESULT res;
  2230. DIR dj;
  2231. BYTE *dir;
  2232. CHAR fn[8+3+1];
  2233. #if _USE_LFN != 0
  2234. UINT len;
  2235. DIR fileobj;
  2236. const UCHAR* spath;
  2237. #endif
  2238. res = auto_mount(&path, &fs, 1);
  2239. if (res == FR_OK) {
  2240. dj.fs=fs;
  2241. #if _USE_LFN != 0
  2242. res = trace_path(&dj, fn, path, &dir, &fileobj, &spath, &len);
  2243. #else
  2244. res = trace_path(&dj, fn, path, &dir); /* trace the file path */
  2245. #endif
  2246. if (res == FR_OK) { /* Trace completed */
  2247. if (!dir) {
  2248. res = FR_INVALID_NAME; /* Root directory */
  2249. } else {
  2250. ST_WORD(&dir[DIR_WrtTime], finfo->ftime);
  2251. ST_WORD(&dir[DIR_WrtDate], finfo->fdate);
  2252. res = sync(fs);
  2253. }
  2254. }
  2255. }
  2256. return res;
  2257. }
  2258. #endif
  2259. /*-----------------------------------------------------------------------*/
  2260. /* Rename File/Directory */
  2261. /*-----------------------------------------------------------------------*/
  2262. FRESULT f_rename (
  2263. #if _USE_DRIVE_PREFIX == 0
  2264. FATFS *fs, /* Pointer to file system object */
  2265. #endif
  2266. const UCHAR *path_old, /* Pointer to the old name */
  2267. const UCHAR *path_new /* Pointer to the new name */
  2268. )
  2269. {
  2270. FRESULT res;
  2271. DIR dj;
  2272. DWORD sect_old;
  2273. BYTE *dir_old, *dir_new, direntry[32-11];
  2274. UCHAR fn[8+3+1];
  2275. #if _USE_DRIVE_PREFIX != 0
  2276. FATFS *fs;
  2277. #endif
  2278. #if _USE_LFN != 0
  2279. UINT len_old, len_new;
  2280. DIR fileobj;
  2281. const UCHAR* spath;
  2282. #endif
  2283. res = auto_mount(&path_old, &fs, 1);
  2284. if (res != FR_OK) return res;
  2285. dj.fs = fs;
  2286. #if _USE_LFN != 0
  2287. res = trace_path(&dj, fn, path_old, &dir_old, &fileobj, &spath, &len_old);
  2288. #else
  2289. res = trace_path(&dj, fn, path_old, &dir_old); /* trace the file path */
  2290. #endif
  2291. if (res != FR_OK) return res; /* The old object is not found */
  2292. if (!dir_old) return FR_NO_FILE;
  2293. sect_old = FSBUF.sect; /* Save the object information */
  2294. memcpy(direntry, &dir_old[DIR_Attr], 32-11);
  2295. #if _USE_LFN != 0
  2296. res = trace_path(&dj, fn, path_new, &dir_new, &fileobj, &spath, &len_new);
  2297. #else
  2298. res = trace_path(&dj, fn, path_new, &dir_new); /* trace the file path */
  2299. #endif
  2300. if (res == FR_OK) return FR_EXIST; /* The new object name is already existing */
  2301. if (res != FR_NO_FILE) return res; /* Is there no old name? */
  2302. #if _USE_CHDIR != 0
  2303. if(fn[0]=='.')
  2304. return FR_INVALID_NAME;
  2305. #endif
  2306. #if _USE_LFN != 0
  2307. res = reserve_direntry(&dj, &dir_new,len_new); /* Reserve a directory entry */
  2308. if (res != FR_OK) return res;
  2309. if(len_new && add_direntry(&dj,&dir_new,spath,len_new,fn)) /* need to get shortname, check it, and add all names */
  2310. return FR_RW_ERROR;
  2311. #else
  2312. res = reserve_direntry(&dj, &dir_new); /* Reserve a directory entry */
  2313. if (res != FR_OK) return res;
  2314. #endif
  2315. memcpy(&dir_new[DIR_Attr], direntry, 32-11); /* Create new entry */
  2316. memcpy(&dir_new[DIR_Name], fn, 8+3);
  2317. dir_new[DIR_NTres] = fn[11];
  2318. FSBUF.dirty = TRUE;
  2319. #if _USE_LFN != 0
  2320. /* Trace it again, fileobj was clobbered while tracing the new path */
  2321. res = trace_path(&dj, fn, path_old, &dir_old, &fileobj, &spath, &len_old);
  2322. len_old=(len_old+25)/13;
  2323. while(len_old--) {
  2324. if (!move_fs_window(fs, fileobj.sect)) return FR_RW_ERROR; /* Mark the directory entry 'deleted' */
  2325. dir_old = &FSBUF.data[(fileobj.index & ((SS(fs) - 1) >> 5)) * 32];
  2326. dir_old[DIR_Name] = 0xE5;
  2327. FSBUF.dirty = TRUE;
  2328. if (!next_dir_entry(&fileobj)) /* Next directory pointer */
  2329. return FR_RW_ERROR;
  2330. }
  2331. #else
  2332. if (!move_fs_window(fs, sect_old)) return FR_RW_ERROR; /* Remove old entry */
  2333. dir_old[DIR_Name] = 0xE5;
  2334. #endif
  2335. return sync(fs);
  2336. }
  2337. #endif /* !_FS_READONLY */
  2338. #endif /* _FS_MINIMIZE == 0 */
  2339. #endif /* _FS_MINIMIZE <= 1 */
  2340. #endif /* _FS_MINIMIZE <= 2 */
  2341. #if _USE_MKFS && !_FS_READONLY
  2342. /*-----------------------------------------------------------------------*/
  2343. /* Create File System on the Drive */
  2344. /*-----------------------------------------------------------------------*/
  2345. #define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */
  2346. #define N_FATS 1 /* 1 or 2 */
  2347. #define MAX_SECTOR 64000000UL /* Maximum partition size */
  2348. #define MIN_SECTOR 2000UL /* Minimum partition size */
  2349. FRESULT f_mkfs (
  2350. BYTE drv, /* Logical drive number */
  2351. BYTE partition, /* Partitioning rule 0:FDISK, 1:SFD */
  2352. WORD allocsize /* Allocation unit size [bytes] */
  2353. )
  2354. {
  2355. BYTE fmt, m, *tbl;
  2356. DWORD b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */
  2357. DWORD n_part, n_rsv, n_fat, n_dir; /* Area size */
  2358. DWORD n_clust, n;
  2359. FATFS *fs;
  2360. DSTATUS stat;
  2361. /* Check validity of the parameters */
  2362. if (drv >= _LOGICAL_DRIVES) return FR_INVALID_DRIVE;
  2363. if (partition >= 2) return FR_MKFS_ABORTED;
  2364. for (n = 512; n <= 32768U && n != allocsize; n <<= 1);
  2365. if (n != allocsize) return FR_MKFS_ABORTED;
  2366. /* Check mounted drive and clear work area */
  2367. fs = FatFs[drv];
  2368. if (!fs) return FR_NOT_ENABLED;
  2369. fs->fs_type = 0;
  2370. drv = LD2PD(drv);
  2371. /* Get disk statics */
  2372. stat = disk_initialize(drv);
  2373. if (stat & STA_NOINIT) return FR_NOT_READY;
  2374. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  2375. if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR)
  2376. return FR_MKFS_ABORTED;
  2377. if (n_part > MAX_SECTOR) n_part = MAX_SECTOR;
  2378. b_part = (!partition) ? 63 : 0; /* Boot sector */
  2379. n_part -= b_part;
  2380. #if S_MAX_SIZ > 512 /* Check disk sector size */
  2381. if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
  2382. || SS(fs) > S_MAX_SIZ
  2383. || SS(fs) > allocsize)
  2384. return FR_MKFS_ABORTED;
  2385. #endif
  2386. allocsize /= SS(fs); /* Number of sectors per cluster */
  2387. /* Pre-compute number of clusters and FAT type */
  2388. n_clust = n_part / allocsize;
  2389. fmt = FS_FAT12;
  2390. if (n_clust >= 0xFF5) fmt = FS_FAT16;
  2391. if (n_clust >= 0xFFF5) fmt = FS_FAT32;
  2392. /* Determine offset and size of FAT structure */
  2393. switch (fmt) {
  2394. case FS_FAT12:
  2395. n_fat = ((n_clust * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs);
  2396. n_rsv = 1 + partition;
  2397. n_dir = N_ROOTDIR * 32 / SS(fs);
  2398. break;
  2399. case FS_FAT16:
  2400. n_fat = ((n_clust * 2) + 4 + SS(fs) - 1) / SS(fs);
  2401. n_rsv = 1 + partition;
  2402. n_dir = N_ROOTDIR * 32 / SS(fs);
  2403. break;
  2404. default:
  2405. n_fat = ((n_clust * 4) + 8 + SS(fs) - 1) / SS(fs);
  2406. n_rsv = 33 - partition;
  2407. n_dir = 0;
  2408. }
  2409. b_fat = b_part + n_rsv; /* FATs start sector */
  2410. b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */
  2411. b_data = b_dir + n_dir; /* Data start sector */
  2412. /* Align data start sector to erase block boundary (for flash memory media) */
  2413. if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED;
  2414. n = (b_data + n - 1) & ~(n - 1);
  2415. n_fat += (n - b_data) / N_FATS;
  2416. /* b_dir and b_data are no longer used below */
  2417. /* Determine number of cluster and final check of validity of the FAT type */
  2418. n_clust = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize;
  2419. if ( (fmt == FS_FAT16 && n_clust < 0xFF5)
  2420. || (fmt == FS_FAT32 && n_clust < 0xFFF5))
  2421. return FR_MKFS_ABORTED;
  2422. /* Create partition table if needed */
  2423. if (!partition) {
  2424. DWORD n_disk = b_part + n_part;
  2425. tbl = &FSBUF.data[MBR_Table];
  2426. ST_DWORD(&tbl[0], 0x00010180); /* Partition start in CHS */
  2427. if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */
  2428. n_disk = n_disk / 63 / 255;
  2429. tbl[7] = (BYTE)n_disk;
  2430. tbl[6] = (BYTE)((n_disk >> 2) | 63);
  2431. } else {
  2432. ST_WORD(&tbl[6], 0xFFFF);
  2433. }
  2434. tbl[5] = 254;
  2435. if (fmt != FS_FAT32) /* System ID */
  2436. tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06;
  2437. else
  2438. tbl[4] = 0x0c;
  2439. ST_DWORD(&tbl[8], 63); /* Partition start in LBA */
  2440. ST_DWORD(&tbl[12], n_part); /* Partition size in LBA */
  2441. ST_WORD(&tbl[64], 0xAA55); /* Signature */
  2442. if (disk_write(drv, FSBUF.data, 0, 1) != RES_OK)
  2443. return FR_RW_ERROR;
  2444. }
  2445. /* Create boot record */
  2446. tbl = FSBUF.data; /* Clear buffer */
  2447. memset(tbl, 0, SS(fs));
  2448. ST_DWORD(&tbl[BS_jmpBoot], 0x90FEEB); /* Boot code (jmp $, nop) */
  2449. ST_WORD(&tbl[BPB_BytsPerSec], SS(fs)); /* Sector size */
  2450. tbl[BPB_SecPerClus] = (BYTE)allocsize; /* Sectors per cluster */
  2451. ST_WORD(&tbl[BPB_RsvdSecCnt], n_rsv); /* Reserved sectors */
  2452. tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
  2453. ST_WORD(&tbl[BPB_RootEntCnt], SS(fs) / 32 * n_dir); /* Number of rootdir entries */
  2454. if (n_part < 0x10000) { /* Number of total sectors */
  2455. ST_WORD(&tbl[BPB_TotSec16], n_part);
  2456. } else {
  2457. ST_DWORD(&tbl[BPB_TotSec32], n_part);
  2458. }
  2459. tbl[BPB_Media] = 0xF8; /* Media descripter */
  2460. ST_WORD(&tbl[BPB_SecPerTrk], 63); /* Number of sectors per track */
  2461. ST_WORD(&tbl[BPB_NumHeads], 255); /* Number of heads */
  2462. ST_DWORD(&tbl[BPB_HiddSec], b_part); /* Hidden sectors */
  2463. n = get_fattime(); /* Use current time as a VSN */
  2464. if (fmt != FS_FAT32) {
  2465. ST_DWORD(&tbl[BS_VolID], n); /* Volume serial number */
  2466. ST_WORD(&tbl[BPB_FATSz16], n_fat); /* Number of secters per FAT */
  2467. tbl[BS_DrvNum] = 0x80; /* Drive number */
  2468. tbl[BS_BootSig] = 0x29; /* Extended boot signature */
  2469. memcpy(&tbl[BS_VolLab], "NO NAME FAT ", 19); /* Volume lavel, FAT signature */
  2470. } else {
  2471. ST_DWORD(&tbl[BS_VolID32], n); /* Volume serial number */
  2472. ST_DWORD(&tbl[BPB_FATSz32], n_fat); /* Number of secters per FAT */
  2473. ST_DWORD(&tbl[BPB_RootClus], 2); /* Root directory cluster (2) */
  2474. ST_WORD(&tbl[BPB_FSInfo], 1); /* FSInfo record (bs+1) */
  2475. ST_WORD(&tbl[BPB_BkBootSec], 6); /* Backup boot record (bs+6) */
  2476. tbl[BS_DrvNum32] = 0x80; /* Drive number */
  2477. tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
  2478. memcpy(&tbl[BS_VolLab32], "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */
  2479. }
  2480. ST_WORD(&tbl[BS_55AA], 0xAA55); /* Signature */
  2481. if (disk_write(drv, tbl, b_part+0, 1) != RES_OK)
  2482. return FR_RW_ERROR;
  2483. if (fmt == FS_FAT32)
  2484. disk_write(drv, tbl, b_part+6, 1);
  2485. /* Initialize FAT area */
  2486. for (m = 0; m < N_FATS; m++) {
  2487. memset(tbl, 0, SS(fs)); /* 1st sector of the FAT */
  2488. if (fmt != FS_FAT32) {
  2489. n = (fmt == FS_FAT12) ? 0x00FFFFF8 : 0xFFFFFFF8;
  2490. ST_DWORD(&tbl[0], n); /* Reserve cluster #0-1 (FAT12/16) */
  2491. } else {
  2492. ST_DWORD(&tbl[0], 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */
  2493. ST_DWORD(&tbl[4], 0xFFFFFFFF);
  2494. ST_DWORD(&tbl[8], 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
  2495. }
  2496. if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
  2497. return FR_RW_ERROR;
  2498. memset(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */
  2499. for (n = 1; n < n_fat; n++) {
  2500. if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
  2501. return FR_RW_ERROR;
  2502. }
  2503. }
  2504. /* Initialize Root directory */
  2505. m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir);
  2506. do {
  2507. if (disk_write(drv, tbl, b_fat++, 1) != RES_OK)
  2508. return FR_RW_ERROR;
  2509. } while (--m);
  2510. /* Create FSInfo record if needed */
  2511. if (fmt == FS_FAT32) {
  2512. ST_WORD(&tbl[BS_55AA], 0xAA55);
  2513. ST_DWORD(&tbl[FSI_LeadSig], 0x41615252);
  2514. ST_DWORD(&tbl[FSI_StrucSig], 0x61417272);
  2515. ST_DWORD(&tbl[FSI_Free_Count], n_clust - 1);
  2516. ST_DWORD(&tbl[FSI_Nxt_Free], 0xFFFFFFFF);
  2517. disk_write(drv, tbl, b_part+1, 1);
  2518. disk_write(drv, tbl, b_part+7, 1);
  2519. }
  2520. return (disk_ioctl(drv, CTRL_SYNC, NULL) == RES_OK) ? FR_OK : FR_RW_ERROR;
  2521. }
  2522. #endif /* _USE_MKFS && !_FS_READONLY */
  2523. #if _USE_STRFUNC >= 1
  2524. /*-----------------------------------------------------------------------*/
  2525. /* Get a string from the file */
  2526. /*-----------------------------------------------------------------------*/
  2527. char* fgets (
  2528. char* buff, /* Pointer to the string buffer to read */
  2529. int len, /* Size of string buffer */
  2530. FIL* fil /* Pointer to the file object */
  2531. )
  2532. {
  2533. int i = 0;
  2534. char *p = buff;
  2535. UINT rc;
  2536. while (i < len - 1) { /* Read bytes until buffer gets filled */
  2537. f_read(fil, p, 1, &rc);
  2538. if (rc != 1) break; /* Break when no data to read */
  2539. #if _USE_STRFUNC >= 2
  2540. if (*p == '\r') continue; /* Strip '\r' */
  2541. #endif
  2542. i++;
  2543. if (*p++ == '\n') break; /* Break when reached end of line */
  2544. }
  2545. *p = 0;
  2546. return i ? buff : 0; /* When no data read (eof or error), return with error. */
  2547. }
  2548. #if !_FS_READONLY
  2549. #include <stdarg.h>
  2550. /*-----------------------------------------------------------------------*/
  2551. /* Put a character to the file */
  2552. /*-----------------------------------------------------------------------*/
  2553. int fputc (
  2554. int chr, /* A character to be output */
  2555. FIL* fil /* Ponter to the file object */
  2556. )
  2557. {
  2558. UINT bw;
  2559. char c;
  2560. #if _USE_STRFUNC >= 2
  2561. if (chr == '\n') fputc ('\r', fil); /* LF -> CRLF conversion */
  2562. #endif
  2563. if (!fil) { /* Special value may be used to switch the destination to any other device */
  2564. /* put_console(chr); */
  2565. return chr;
  2566. }
  2567. c = (char)chr;
  2568. f_write(fil, &c, 1, &bw); /* Write a byte to the file */
  2569. return bw ? chr : EOF; /* Return the resulut */
  2570. }
  2571. /*-----------------------------------------------------------------------*/
  2572. /* Put a string to the file */
  2573. /*-----------------------------------------------------------------------*/
  2574. int fputs (
  2575. const char* str, /* Pointer to the string to be output */
  2576. FIL* fil /* Pointer to the file object */
  2577. )
  2578. {
  2579. int n;
  2580. for (n = 0; *str; str++, n++) {
  2581. if (fputc(*str, fil) == EOF) return EOF;
  2582. }
  2583. return n;
  2584. }
  2585. /*-----------------------------------------------------------------------*/
  2586. /* Put a formatted string to the file */
  2587. /*-----------------------------------------------------------------------*/
  2588. int fprintf (
  2589. FIL* fil, /* Pointer to the file object */
  2590. const char* str, /* Pointer to the format string */
  2591. ... /* Optional arguments... */
  2592. )
  2593. {
  2594. va_list arp;
  2595. UCHAR c, f, r;
  2596. ULONG val;
  2597. char s[16];
  2598. int i, w, res, cc;
  2599. va_start(arp, str);
  2600. for (cc = res = 0; cc != EOF; res += cc) {
  2601. c = *str++;
  2602. if (c == 0) break; /* End of string */
  2603. if (c != '%') { /* Non escape cahracter */
  2604. cc = fputc(c, fil);
  2605. if (cc != EOF) cc = 1;
  2606. continue;
  2607. }
  2608. w = f = 0;
  2609. c = *str++;
  2610. if (c == '0') { /* Flag: '0' padding */
  2611. f = 1; c = *str++;
  2612. }
  2613. while (c >= '0' && c <= '9') { /* Precision */
  2614. w = w * 10 + (c - '0');
  2615. c = *str++;
  2616. }
  2617. if (c == 'l') { /* Prefix: Size is long int */
  2618. f |= 2; c = *str++;
  2619. }
  2620. if (c == 's') { /* Type is string */
  2621. cc = fputs(va_arg(arp, char*), fil);
  2622. continue;
  2623. }
  2624. if (c == 'c') { /* Type is character */
  2625. cc = fputc(va_arg(arp, char), fil);
  2626. if (cc != EOF) cc = 1;
  2627. continue;
  2628. }
  2629. r = 0;
  2630. if (c == 'd') r = 10; /* Type is signed decimal */
  2631. if (c == 'u') r = 10; /* Type is unsigned decimal */
  2632. if (c == 'X') r = 16; /* Type is unsigned hexdecimal */
  2633. if (r == 0) break; /* Unknown type */
  2634. if (f & 2) { /* Get the value */
  2635. val = (ULONG)va_arg(arp, long);
  2636. } else {
  2637. val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int);
  2638. }
  2639. /* Put numeral string */
  2640. if (c == 'd') {
  2641. if (val >= 0x80000000) {
  2642. val = 0 - val;
  2643. f |= 4;
  2644. }
  2645. }
  2646. i = sizeof(s) - 1; s[i] = 0;
  2647. do {
  2648. c = (UCHAR)(val % r + '0');
  2649. if (c > '9') c += 7;
  2650. s[--i] = c;
  2651. val /= r;
  2652. } while (i && val);
  2653. if (i && (f & 4)) s[--i] = '-';
  2654. w = sizeof(s) - 1 - w;
  2655. while (i && i > w) s[--i] = (f & 1) ? '0' : ' ';
  2656. cc = fputs(&s[i], fil);
  2657. }
  2658. va_end(arp);
  2659. return (cc == EOF) ? cc : res;
  2660. }
  2661. #endif /* !_FS_READONLY */
  2662. #endif /* _USE_STRFUNC >= 1*/