ff.c 93 KB

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