ff.c 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - FAT file system module R0.08a (C)ChaN, 2010
  3. /-----------------------------------------------------------------------------/
  4. / FatFs module is a generic FAT file system module for small embedded systems.
  5. / This is a free software that opened for education, research and commercial
  6. / developments under license policy of following terms.
  7. /
  8. / Copyright (C) 2010, ChaN, all right reserved.
  9. /
  10. / * The FatFs module is a free software and there is NO WARRANTY.
  11. / * No restriction on use. You can use, modify and redistribute it for
  12. / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
  13. / * Redistributions of source code must retain the above copyright notice.
  14. /
  15. /-----------------------------------------------------------------------------/
  16. / Feb 26,'06 R0.00 Prototype.
  17. /
  18. / Apr 29,'06 R0.01 First stable version.
  19. /
  20. / Jun 01,'06 R0.02 Added FAT12 support.
  21. / Removed unbuffered mode.
  22. / Fixed a problem on small (<32M) partition.
  23. / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
  24. /
  25. / Sep 22,'06 R0.03 Added f_rename().
  26. / Changed option _FS_MINIMUM to _FS_MINIMIZE.
  27. / Dec 11,'06 R0.03a Improved cluster scan algorithm to write files fast.
  28. / Fixed f_mkdir() creates incorrect directory on FAT32.
  29. /
  30. / Feb 04,'07 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,'07 R0.04a Supported multiple partitions on a physical 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,'07 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,'07 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,'08 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 without write.
  50. /
  51. / Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets().
  52. / Improved performance of f_lseek() on moving to the same or following cluster.
  53. /
  54. / Apr 01,'09 R0.07 Merged Tiny-FatFs as a buffer configuration option. (_FS_TINY)
  55. / Added long file name support.
  56. / Added multiple code page support.
  57. / Added re-entrancy for multitask operation.
  58. / Added auto cluster size selection to f_mkfs().
  59. / Added rewind option to f_readdir().
  60. / Changed result code of critical errors.
  61. / Renamed string functions to avoid name collision.
  62. / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
  63. / Added multiple sector size support.
  64. / Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
  65. / Fixed wrong cache control in f_lseek().
  66. / Added relative path feature.
  67. / Added f_chdir() and f_chdrive().
  68. / Added proper case conversion to extended char.
  69. / Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
  70. / Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
  71. / Fixed name matching error on the 13 char boundary.
  72. / Added a configuration option, _LFN_UNICODE.
  73. / Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
  74. /
  75. / May 15,'10 R0.08 Added a memory configuration option. (_USE_LFN = 3)
  76. / Added file lock feature. (_FS_SHARE)
  77. / Added fast seek feature. (_USE_FASTSEEK)
  78. / Changed some types on the API, XCHAR->TCHAR.
  79. / Changed fname member in the FILINFO structure on Unicode cfg.
  80. / String functions support UTF-8 encoding files on Unicode cfg.
  81. / Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2)
  82. / Added sector erase feature. (_USE_ERASE)
  83. / Moved file lock semaphore table from fs object to the bss.
  84. / Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'.
  85. / Fixed f_mkfs() creates wrong FAT32 volume.
  86. /---------------------------------------------------------------------------*/
  87. #include "ff.h" /* FatFs configurations and declarations */
  88. #include "diskio.h" /* Declarations of low level disk I/O functions */
  89. #include "config.h"
  90. #include "uart.h"
  91. /*--------------------------------------------------------------------------
  92. Module Private Definitions
  93. ---------------------------------------------------------------------------*/
  94. #if _FATFS != 8255
  95. #error Wrong include file (ff.h).
  96. #endif
  97. /* Definitions on sector size */
  98. #if _MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096
  99. #error Wrong sector size.
  100. #endif
  101. #if _MAX_SS != 512
  102. #define SS(fs) ((fs)->ssize) /* Multiple sector size */
  103. #else
  104. #define SS(fs) 512U /* Fixed sector size */
  105. #endif
  106. /* Reentrancy related */
  107. #if _FS_REENTRANT
  108. #if _USE_LFN == 1
  109. #error Static LFN work area must not be used in re-entrant configuration.
  110. #endif
  111. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  112. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  113. #else
  114. #define ENTER_FF(fs)
  115. #define LEAVE_FF(fs, res) return res
  116. #endif
  117. #define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
  118. /* File shareing feature */
  119. #if _FS_SHARE
  120. #if _FS_READONLY
  121. #error _FS_SHARE must be 0 on read-only cfg.
  122. #endif
  123. typedef struct {
  124. FATFS *fs; /* File ID 1, volume (NULL:blank entry) */
  125. DWORD clu; /* File ID 2, directory */
  126. WORD idx; /* File ID 3, directory index */
  127. WORD ctr; /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */
  128. } FILESEM;
  129. #endif
  130. /* Misc definitions */
  131. #define LD_CLUST(dir) (((DWORD)LD_WORD(dir+DIR_FstClusHI)<<16) | LD_WORD(dir+DIR_FstClusLO))
  132. #define ST_CLUST(dir,cl) {ST_WORD(dir+DIR_FstClusLO, cl); ST_WORD(dir+DIR_FstClusHI, (DWORD)cl>>16);}
  133. /* Character code support macros */
  134. #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
  135. #define IsLower(c) (((c)>='a')&&((c)<='z'))
  136. #define IsDigit(c) (((c)>='0')&&((c)<='9'))
  137. #if _DF1S /* Code page is DBCS */
  138. #ifdef _DF2S /* Two 1st byte areas */
  139. #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  140. #else /* One 1st byte area */
  141. #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  142. #endif
  143. #ifdef _DS3S /* Three 2nd byte areas */
  144. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  145. #else /* Two 2nd byte areas */
  146. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  147. #endif
  148. #else /* Code page is SBCS */
  149. #define IsDBCS1(c) 0
  150. #define IsDBCS2(c) 0
  151. #endif /* _DF1S */
  152. /* Name status flags */
  153. #define NS 11 /* Offset of name status byte */
  154. #define NS_LOSS 0x01 /* Out of 8.3 format */
  155. #define NS_LFN 0x02 /* Force to create LFN entry */
  156. #define NS_LAST 0x04 /* Last segment */
  157. #define NS_BODY 0x08 /* Lower case flag (body) */
  158. #define NS_EXT 0x10 /* Lower case flag (ext) */
  159. #define NS_DOT 0x20 /* Dot entry */
  160. /* FAT sub-type boundaries */
  161. /* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */
  162. #define MIN_FAT16 4086 /* Minimum number of clusters for FAT16 */
  163. #define MIN_FAT32 65526 /* Minimum number of clusters for FAT32 */
  164. /* FatFs refers the members in the FAT structures as byte array instead of
  165. / structure member because there are incompatibility of the packing option
  166. / between compilers. */
  167. #define BS_jmpBoot 0
  168. #define BS_OEMName 3
  169. #define BPB_BytsPerSec 11
  170. #define BPB_SecPerClus 13
  171. #define BPB_RsvdSecCnt 14
  172. #define BPB_NumFATs 16
  173. #define BPB_RootEntCnt 17
  174. #define BPB_TotSec16 19
  175. #define BPB_Media 21
  176. #define BPB_FATSz16 22
  177. #define BPB_SecPerTrk 24
  178. #define BPB_NumHeads 26
  179. #define BPB_HiddSec 28
  180. #define BPB_TotSec32 32
  181. #define BS_DrvNum 36
  182. #define BS_BootSig 38
  183. #define BS_VolID 39
  184. #define BS_VolLab 43
  185. #define BS_FilSysType 54
  186. #define BPB_FATSz32 36
  187. #define BPB_ExtFlags 40
  188. #define BPB_FSVer 42
  189. #define BPB_RootClus 44
  190. #define BPB_FSInfo 48
  191. #define BPB_BkBootSec 50
  192. #define BS_DrvNum32 64
  193. #define BS_BootSig32 66
  194. #define BS_VolID32 67
  195. #define BS_VolLab32 71
  196. #define BS_FilSysType32 82
  197. #define FSI_LeadSig 0
  198. #define FSI_StrucSig 484
  199. #define FSI_Free_Count 488
  200. #define FSI_Nxt_Free 492
  201. #define MBR_Table 446
  202. #define BS_55AA 510
  203. #define DIR_Name 0
  204. #define DIR_Attr 11
  205. #define DIR_NTres 12
  206. #define DIR_CrtTime 14
  207. #define DIR_CrtDate 16
  208. #define DIR_FstClusHI 20
  209. #define DIR_WrtTime 22
  210. #define DIR_WrtDate 24
  211. #define DIR_FstClusLO 26
  212. #define DIR_FileSize 28
  213. #define LDIR_Ord 0
  214. #define LDIR_Attr 11
  215. #define LDIR_Type 12
  216. #define LDIR_Chksum 13
  217. #define LDIR_FstClusLO 26
  218. /*------------------------------------------------------------*/
  219. /* Work area */
  220. #if _VOLUMES
  221. static
  222. FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
  223. #else
  224. #error Number of drives must not be 0.
  225. #endif
  226. static
  227. WORD Fsid; /* File system mount ID */
  228. #if _FS_RPATH
  229. static
  230. BYTE CurrVol; /* Current drive */
  231. #endif
  232. #if _FS_SHARE
  233. static
  234. FILESEM Files[_FS_SHARE]; /* File lock semaphores */
  235. #endif
  236. #if _USE_LFN == 0 /* No LFN */
  237. #define DEF_NAMEBUF BYTE sfn[12]
  238. #define INIT_BUF(dobj) (dobj).fn = sfn
  239. #define FREE_BUF()
  240. #elif _USE_LFN == 1 /* LFN with static LFN working buffer */
  241. static WCHAR LfnBuf[_MAX_LFN+1];
  242. #define DEF_NAMEBUF BYTE sfn[12]
  243. #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }
  244. #define FREE_BUF()
  245. #elif _USE_LFN == 2 /* LFN with dynamic LFN working buffer on the stack */
  246. #define DEF_NAMEBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]
  247. #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = lbuf; }
  248. #define FREE_BUF()
  249. #elif _USE_LFN == 3 /* LFN with dynamic LFN working buffer on the heap */
  250. #define DEF_NAMEBUF BYTE sfn[12]; WCHAR *lfn
  251. #define INIT_BUF(dobj) { lfn = ff_memalloc((_MAX_LFN + 1) * 2); \
  252. if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); \
  253. (dobj).lfn = lfn; (dobj).fn = sfn; }
  254. #define FREE_BUF() ff_memfree(lfn)
  255. #else
  256. #error Wrong LFN configuration.
  257. #endif
  258. /*--------------------------------------------------------------------------
  259. Module Private Functions
  260. ---------------------------------------------------------------------------*/
  261. /*-----------------------------------------------------------------------*/
  262. /* String functions */
  263. /*-----------------------------------------------------------------------*/
  264. /* Copy memory to memory */
  265. static
  266. void mem_cpy (void* dst, const void* src, UINT cnt) {
  267. BYTE *d = (BYTE*)dst;
  268. const BYTE *s = (const BYTE*)src;
  269. #if _WORD_ACCESS == 1
  270. while (cnt >= sizeof(int)) {
  271. *(int*)d = *(int*)s;
  272. d += sizeof(int); s += sizeof(int);
  273. cnt -= sizeof(int);
  274. }
  275. #endif
  276. while (cnt--)
  277. *d++ = *s++;
  278. }
  279. /* Fill memory */
  280. static
  281. void mem_set (void* dst, int val, UINT cnt) {
  282. BYTE *d = (BYTE*)dst;
  283. while (cnt--)
  284. *d++ = (BYTE)val;
  285. }
  286. /* Compare memory to memory */
  287. static
  288. int mem_cmp (const void* dst, const void* src, UINT cnt) {
  289. const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
  290. int r = 0;
  291. while (cnt-- && (r = *d++ - *s++) == 0) ;
  292. return r;
  293. }
  294. /* Check if chr is contained in the string */
  295. static
  296. int chk_chr (const char* str, int chr) {
  297. while (*str && *str != chr) str++;
  298. return *str;
  299. }
  300. /*-----------------------------------------------------------------------*/
  301. /* Request/Release grant to access the volume */
  302. /*-----------------------------------------------------------------------*/
  303. #if _FS_REENTRANT
  304. static
  305. int lock_fs (
  306. FATFS *fs /* File system object */
  307. )
  308. {
  309. return ff_req_grant(fs->sobj);
  310. }
  311. static
  312. void unlock_fs (
  313. FATFS *fs, /* File system object */
  314. FRESULT res /* Result code to be returned */
  315. )
  316. {
  317. if (res != FR_NOT_ENABLED &&
  318. res != FR_INVALID_DRIVE &&
  319. res != FR_INVALID_OBJECT &&
  320. res != FR_TIMEOUT) {
  321. ff_rel_grant(fs->sobj);
  322. }
  323. }
  324. #endif
  325. /*-----------------------------------------------------------------------*/
  326. /* File shareing control functions */
  327. /*-----------------------------------------------------------------------*/
  328. #if _FS_SHARE
  329. static
  330. FRESULT chk_lock ( /* Check if the file can be accessed */
  331. DIR* dj, /* Directory object pointing the file to be checked */
  332. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  333. )
  334. {
  335. UINT i, be;
  336. /* Search file semaphore table */
  337. for (i = be = 0; i < _FS_SHARE; i++) {
  338. if (Files[i].fs) { /* Existing entry */
  339. if (Files[i].fs == dj->fs && /* Check if the file matched with an open file */
  340. Files[i].clu == dj->sclust &&
  341. Files[i].idx == dj->index) break;
  342. } else { /* Blank entry */
  343. be++;
  344. }
  345. }
  346. if (i == _FS_SHARE) /* The file is not opened */
  347. return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new file? */
  348. /* The file has been opened. Reject any open against writing file and all write mode open */
  349. return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  350. }
  351. static
  352. int enq_lock ( /* Check if an entry is available for a new file */
  353. FATFS* fs /* File system object */
  354. )
  355. {
  356. UINT i;
  357. for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;
  358. return (i == _FS_SHARE) ? 0 : 1;
  359. }
  360. static
  361. UINT inc_lock ( /* Increment file open counter and returns its index (0:int error) */
  362. DIR* dj, /* Directory object pointing the file to register or increment */
  363. int acc /* Desired access mode (0:Read, !0:Write) */
  364. )
  365. {
  366. UINT i;
  367. for (i = 0; i < _FS_SHARE; i++) { /* Find the file */
  368. if (Files[i].fs == dj->fs &&
  369. Files[i].clu == dj->sclust &&
  370. Files[i].idx == dj->index) break;
  371. }
  372. if (i == _FS_SHARE) { /* Not opened. Register it as new. */
  373. for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;
  374. if (i == _FS_SHARE) return 0; /* No space to register (int err) */
  375. Files[i].fs = dj->fs;
  376. Files[i].clu = dj->sclust;
  377. Files[i].idx = dj->index;
  378. Files[i].ctr = 0;
  379. }
  380. if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
  381. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  382. return i + 1;
  383. }
  384. static
  385. FRESULT dec_lock ( /* Decrement file open counter */
  386. UINT i /* Semaphore index */
  387. )
  388. {
  389. WORD n;
  390. FRESULT res;
  391. if (--i < _FS_SHARE) {
  392. n = Files[i].ctr;
  393. if (n == 0x100) n = 0;
  394. if (n) n--;
  395. Files[i].ctr = n;
  396. if (!n) Files[i].fs = 0;
  397. res = FR_OK;
  398. } else {
  399. res = FR_INT_ERR;
  400. }
  401. return res;
  402. }
  403. static
  404. void clear_lock ( /* Clear lock entries of the volume */
  405. FATFS *fs
  406. )
  407. {
  408. UINT i;
  409. for (i = 0; i < _FS_SHARE; i++) {
  410. if (Files[i].fs == fs) Files[i].fs = 0;
  411. }
  412. }
  413. #endif
  414. /*-----------------------------------------------------------------------*/
  415. /* Change window offset */
  416. /*-----------------------------------------------------------------------*/
  417. static
  418. FRESULT move_window (
  419. FATFS *fs, /* File system object */
  420. DWORD sector /* Sector number to make appearance in the fs->win[] */
  421. ) /* Move to zero only writes back dirty window */
  422. {
  423. DWORD wsect;
  424. wsect = fs->winsect;
  425. if (wsect != sector) { /* Changed current window */
  426. #if !_FS_READONLY
  427. if (fs->wflag) { /* Write back dirty window if needed */
  428. if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK)
  429. return FR_DISK_ERR;
  430. fs->wflag = 0;
  431. if (wsect < (fs->fatbase + fs->fsize)) { /* In FAT area */
  432. BYTE nf;
  433. for (nf = fs->n_fats; nf > 1; nf--) { /* Reflect the change to all FAT copies */
  434. wsect += fs->fsize;
  435. disk_write(fs->drv, fs->win, wsect, 1);
  436. }
  437. }
  438. }
  439. #endif
  440. if (sector) {
  441. if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK)
  442. return FR_DISK_ERR;
  443. fs->winsect = sector;
  444. }
  445. }
  446. return FR_OK;
  447. }
  448. /*-----------------------------------------------------------------------*/
  449. /* Clean-up cached data */
  450. /*-----------------------------------------------------------------------*/
  451. #if !_FS_READONLY
  452. static
  453. FRESULT sync ( /* FR_OK: successful, FR_DISK_ERR: failed */
  454. FATFS *fs /* File system object */
  455. )
  456. {
  457. FRESULT res;
  458. res = move_window(fs, 0);
  459. if (res == FR_OK) {
  460. /* Update FSInfo sector if needed */
  461. if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
  462. fs->winsect = 0;
  463. mem_set(fs->win, 0, 512);
  464. ST_WORD(fs->win+BS_55AA, 0xAA55);
  465. ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);
  466. ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);
  467. ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);
  468. ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
  469. disk_write(fs->drv, fs->win, fs->fsi_sector, 1);
  470. fs->fsi_flag = 0;
  471. }
  472. /* Make sure that no pending write process in the physical drive */
  473. if (disk_ioctl(fs->drv, CTRL_SYNC, (void*)0) != RES_OK)
  474. res = FR_DISK_ERR;
  475. }
  476. return res;
  477. }
  478. #endif
  479. /*-----------------------------------------------------------------------*/
  480. /* Get sector# from cluster# */
  481. /*-----------------------------------------------------------------------*/
  482. DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */
  483. FATFS *fs, /* File system object */
  484. DWORD clst /* Cluster# to be converted */
  485. )
  486. {
  487. clst -= 2;
  488. if (clst >= (fs->n_fatent - 2)) return 0; /* Invalid cluster# */
  489. return clst * fs->csize + fs->database;
  490. }
  491. /*-----------------------------------------------------------------------*/
  492. /* FAT access - Read value of a FAT entry */
  493. /*-----------------------------------------------------------------------*/
  494. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status */
  495. FATFS *fs, /* File system object */
  496. DWORD clst /* Cluster# to get the link information */
  497. )
  498. {
  499. UINT wc, bc;
  500. BYTE *p;
  501. if (clst < 2 || clst >= fs->n_fatent) /* Chack range */
  502. return 1;
  503. switch (fs->fs_type) {
  504. case FS_FAT12 :
  505. bc = (UINT)clst; bc += bc / 2;
  506. if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
  507. wc = fs->win[bc % SS(fs)]; bc++;
  508. if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
  509. wc |= fs->win[bc % SS(fs)] << 8;
  510. return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  511. case FS_FAT16 :
  512. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)))) break;
  513. p = &fs->win[clst * 2 % SS(fs)];
  514. return LD_WORD(p);
  515. case FS_FAT32 :
  516. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)))) break;
  517. p = &fs->win[clst * 4 % SS(fs)];
  518. return LD_DWORD(p) & 0x0FFFFFFF;
  519. }
  520. return 0xFFFFFFFF; /* An error occurred at the disk I/O layer */
  521. }
  522. /*-----------------------------------------------------------------------*/
  523. /* FAT access - Change value of a FAT entry */
  524. /*-----------------------------------------------------------------------*/
  525. #if !_FS_READONLY
  526. FRESULT put_fat (
  527. FATFS *fs, /* File system object */
  528. DWORD clst, /* Cluster# to be changed in range of 2 to fs->n_fatent - 1 */
  529. DWORD val /* New value to mark the cluster */
  530. )
  531. {
  532. UINT bc;
  533. BYTE *p;
  534. FRESULT res;
  535. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  536. res = FR_INT_ERR;
  537. } else {
  538. switch (fs->fs_type) {
  539. case FS_FAT12 :
  540. bc = clst; bc += bc / 2;
  541. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  542. if (res != FR_OK) break;
  543. p = &fs->win[bc % SS(fs)];
  544. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  545. bc++;
  546. fs->wflag = 1;
  547. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  548. if (res != FR_OK) break;
  549. p = &fs->win[bc % SS(fs)];
  550. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  551. break;
  552. case FS_FAT16 :
  553. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  554. if (res != FR_OK) break;
  555. p = &fs->win[clst * 2 % SS(fs)];
  556. ST_WORD(p, (WORD)val);
  557. break;
  558. case FS_FAT32 :
  559. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  560. if (res != FR_OK) break;
  561. p = &fs->win[clst * 4 % SS(fs)];
  562. val |= LD_DWORD(p) & 0xF0000000;
  563. ST_DWORD(p, val);
  564. break;
  565. default :
  566. res = FR_INT_ERR;
  567. }
  568. fs->wflag = 1;
  569. }
  570. return res;
  571. }
  572. #endif /* !_FS_READONLY */
  573. /*-----------------------------------------------------------------------*/
  574. /* FAT handling - Remove a cluster chain */
  575. /*-----------------------------------------------------------------------*/
  576. #if !_FS_READONLY
  577. static
  578. FRESULT remove_chain (
  579. FATFS *fs, /* File system object */
  580. DWORD clst /* Cluster# to remove a chain from */
  581. )
  582. {
  583. FRESULT res;
  584. DWORD nxt;
  585. #if _USE_ERASE
  586. DWORD scl = clst, ecl = clst, resion[2];
  587. #endif
  588. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  589. res = FR_INT_ERR;
  590. } else {
  591. res = FR_OK;
  592. while (clst < fs->n_fatent) { /* Not a last link? */
  593. nxt = get_fat(fs, clst); /* Get cluster status */
  594. if (nxt == 0) break; /* Empty cluster? */
  595. if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */
  596. if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */
  597. res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */
  598. if (res != FR_OK) break;
  599. if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */
  600. fs->free_clust++;
  601. fs->fsi_flag = 1;
  602. }
  603. #if _USE_ERASE
  604. if (ecl + 1 == nxt) { /* Next cluster is contiguous */
  605. ecl = nxt;
  606. } else { /* End of contiguous clusters */
  607. resion[0] = clust2sect(fs, scl); /* Start sector */
  608. resion[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
  609. disk_ioctl(fs->drv, CTRL_ERASE_SECTOR, resion); /* Erase the block */
  610. scl = ecl = nxt;
  611. }
  612. #endif
  613. clst = nxt; /* Next cluster */
  614. }
  615. }
  616. return res;
  617. }
  618. #endif
  619. /*-----------------------------------------------------------------------*/
  620. /* FAT handling - Stretch or Create a cluster chain */
  621. /*-----------------------------------------------------------------------*/
  622. #if !_FS_READONLY
  623. static
  624. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  625. FATFS *fs, /* File system object */
  626. DWORD clst /* Cluster# to stretch. 0 means create a new chain. */
  627. )
  628. {
  629. DWORD cs, ncl, scl;
  630. FRESULT res;
  631. if (clst == 0) { /* Create a new chain */
  632. scl = fs->last_clust; /* Get suggested start point */
  633. if (!scl || scl >= fs->n_fatent) scl = 1;
  634. }
  635. else { /* Stretch the current chain */
  636. cs = get_fat(fs, clst); /* Check the cluster status */
  637. if (cs < 2) return 1; /* It is an invalid cluster */
  638. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  639. scl = clst;
  640. }
  641. ncl = scl; /* Start cluster */
  642. for (;;) {
  643. ncl++; /* Next cluster */
  644. if (ncl >= fs->n_fatent) { /* Wrap around */
  645. ncl = 2;
  646. if (ncl > scl) return 0; /* No free cluster */
  647. }
  648. cs = get_fat(fs, ncl); /* Get the cluster status */
  649. if (cs == 0) break; /* Found a free cluster */
  650. if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */
  651. return cs;
  652. if (ncl == scl) return 0; /* No free cluster */
  653. }
  654. res = put_fat(fs, ncl, 0x0FFFFFFF); /* Mark the new cluster "last link" */
  655. if (res == FR_OK && clst != 0) {
  656. res = put_fat(fs, clst, ncl); /* Link it to the previous one if needed */
  657. }
  658. if (res == FR_OK) {
  659. fs->last_clust = ncl; /* Update FSINFO */
  660. if (fs->free_clust != 0xFFFFFFFF) {
  661. fs->free_clust--;
  662. fs->fsi_flag = 1;
  663. }
  664. } else {
  665. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;
  666. }
  667. return ncl; /* Return new cluster number or error code */
  668. }
  669. #endif /* !_FS_READONLY */
  670. /*-----------------------------------------------------------------------*/
  671. /* Directory handling - Set directory index */
  672. /*-----------------------------------------------------------------------*/
  673. static
  674. FRESULT dir_sdi (
  675. DIR *dj, /* Pointer to directory object */
  676. WORD idx /* Directory index number */
  677. )
  678. {
  679. DWORD clst;
  680. WORD ic;
  681. dj->index = idx;
  682. clst = dj->sclust;
  683. if (clst == 1 || clst >= dj->fs->n_fatent) /* Check start cluster range */
  684. return FR_INT_ERR;
  685. if (!clst && dj->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */
  686. clst = dj->fs->dirbase;
  687. if (clst == 0) { /* Static table (root-dir in FAT12/16) */
  688. dj->clust = clst;
  689. if (idx >= dj->fs->n_rootdir) /* Index is out of range */
  690. return FR_INT_ERR;
  691. dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / 32); /* Sector# */
  692. }
  693. else { /* Dynamic table (sub-dirs or root-dir in FAT32) */
  694. ic = SS(dj->fs) / 32 * dj->fs->csize; /* Entries per cluster */
  695. while (idx >= ic) { /* Follow cluster chain */
  696. clst = get_fat(dj->fs, clst); /* Get next cluster */
  697. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  698. if (clst < 2 || clst >= dj->fs->n_fatent) /* Reached to end of table or int error */
  699. return FR_INT_ERR;
  700. idx -= ic;
  701. }
  702. dj->clust = clst;
  703. dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / 32); /* Sector# */
  704. }
  705. dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32; /* Ptr to the entry in the sector */
  706. return FR_OK; /* Seek succeeded */
  707. }
  708. /*-----------------------------------------------------------------------*/
  709. /* Directory handling - Move directory index next */
  710. /*-----------------------------------------------------------------------*/
  711. static
  712. FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not stretch */
  713. DIR *dj, /* Pointer to directory object */
  714. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  715. )
  716. {
  717. DWORD clst;
  718. WORD i;
  719. i = dj->index + 1;
  720. if (!i || !dj->sect) /* Report EOT when index has reached 65535 */
  721. return FR_NO_FILE;
  722. if (!(i % (SS(dj->fs) / 32))) { /* Sector changed? */
  723. dj->sect++; /* Next sector */
  724. if (dj->clust == 0) { /* Static table */
  725. if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */
  726. return FR_NO_FILE;
  727. }
  728. else { /* Dynamic table */
  729. if (((i / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */
  730. clst = get_fat(dj->fs, dj->clust); /* Get next cluster */
  731. if (clst <= 1) return FR_INT_ERR;
  732. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  733. if (clst >= dj->fs->n_fatent) { /* When it reached end of dynamic table */
  734. #if !_FS_READONLY
  735. BYTE c;
  736. if (!stretch) return FR_NO_FILE; /* When do not stretch, report EOT */
  737. clst = create_chain(dj->fs, dj->clust); /* Stretch cluster chain */
  738. if (clst == 0) return FR_DENIED; /* No free cluster */
  739. if (clst == 1) return FR_INT_ERR;
  740. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  741. /* Clean-up stretched table */
  742. if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */
  743. mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */
  744. dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */
  745. for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */
  746. dj->fs->wflag = 1;
  747. if (move_window(dj->fs, 0)) return FR_DISK_ERR;
  748. dj->fs->winsect++;
  749. }
  750. dj->fs->winsect -= c; /* Rewind window address */
  751. #else
  752. return FR_NO_FILE; /* Report EOT */
  753. #endif
  754. }
  755. dj->clust = clst; /* Initialize data for new cluster */
  756. dj->sect = clust2sect(dj->fs, clst);
  757. }
  758. }
  759. }
  760. dj->index = i;
  761. dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32;
  762. return FR_OK;
  763. }
  764. /*-----------------------------------------------------------------------*/
  765. /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
  766. /*-----------------------------------------------------------------------*/
  767. #if _USE_LFN
  768. static
  769. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */
  770. static
  771. int cmp_lfn ( /* 1:Matched, 0:Not matched */
  772. WCHAR *lfnbuf, /* Pointer to the LFN to be compared */
  773. BYTE *dir /* Pointer to the directory entry containing a part of LFN */
  774. )
  775. {
  776. UINT i, s;
  777. WCHAR wc, uc;
  778. i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13; /* Get offset in the LFN buffer */
  779. s = 0; wc = 1;
  780. do {
  781. uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
  782. if (wc) { /* Last char has not been processed */
  783. wc = ff_wtoupper(uc); /* Convert it to upper case */
  784. if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it */
  785. return 0; /* Not matched */
  786. } else {
  787. if (uc != 0xFFFF) return 0; /* Check filler */
  788. }
  789. } while (++s < 13); /* Repeat until all chars in the entry are checked */
  790. if ((dir[LDIR_Ord] & 0x40) && wc && lfnbuf[i]) /* Last segment matched but different length */
  791. return 0;
  792. return 1; /* The part of LFN matched */
  793. }
  794. static
  795. int pick_lfn ( /* 1:Succeeded, 0:Buffer overflow */
  796. WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */
  797. BYTE *dir /* Pointer to the directory entry */
  798. )
  799. {
  800. UINT i, s;
  801. WCHAR wc, uc;
  802. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  803. s = 0; wc = 1;
  804. do {
  805. uc = LD_WORD(dir+LfnOfs[s]); /* Pick an LFN character from the entry */
  806. if (wc) { /* Last char has not been processed */
  807. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  808. lfnbuf[i++] = wc = uc; /* Store it */
  809. } else {
  810. if (uc != 0xFFFF) return 0; /* Check filler */
  811. }
  812. } while (++s < 13); /* Read all character in the entry */
  813. if (dir[LDIR_Ord] & 0x40) { /* Put terminator if it is the last LFN part */
  814. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  815. lfnbuf[i] = 0;
  816. }
  817. return 1;
  818. }
  819. #if !_FS_READONLY
  820. static
  821. void fit_lfn (
  822. const WCHAR *lfnbuf, /* Pointer to the LFN buffer */
  823. BYTE *dir, /* Pointer to the directory entry */
  824. BYTE ord, /* LFN order (1-20) */
  825. BYTE sum /* SFN sum */
  826. )
  827. {
  828. UINT i, s;
  829. WCHAR wc;
  830. dir[LDIR_Chksum] = sum; /* Set check sum */
  831. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  832. dir[LDIR_Type] = 0;
  833. ST_WORD(dir+LDIR_FstClusLO, 0);
  834. i = (ord - 1) * 13; /* Get offset in the LFN buffer */
  835. s = wc = 0;
  836. do {
  837. if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective char */
  838. ST_WORD(dir+LfnOfs[s], wc); /* Put it */
  839. if (!wc) wc = 0xFFFF; /* Padding chars following last char */
  840. } while (++s < 13);
  841. if (wc == 0xFFFF || !lfnbuf[i]) ord |= 0x40; /* Bottom LFN part is the start of LFN sequence */
  842. dir[LDIR_Ord] = ord; /* Set the LFN order */
  843. }
  844. #endif
  845. #endif
  846. /*-----------------------------------------------------------------------*/
  847. /* Create numbered name */
  848. /*-----------------------------------------------------------------------*/
  849. #if _USE_LFN
  850. void gen_numname (
  851. BYTE *dst, /* Pointer to generated SFN */
  852. const BYTE *src, /* Pointer to source SFN to be modified */
  853. const WCHAR *lfn, /* Pointer to LFN */
  854. WORD seq /* Sequence number */
  855. )
  856. {
  857. BYTE ns[8], c;
  858. UINT i, j;
  859. mem_cpy(dst, src, 11);
  860. if (seq > 5) { /* On many collisions, generate a hash number instead of sequential number */
  861. do seq = (seq >> 1) + (seq << 15) + (WORD)*lfn++; while (*lfn);
  862. }
  863. /* itoa */
  864. i = 7;
  865. do {
  866. c = (seq % 16) + '0';
  867. if (c > '9') c += 7;
  868. ns[i--] = c;
  869. seq /= 16;
  870. } while (seq);
  871. ns[i] = '~';
  872. /* Append the number */
  873. for (j = 0; j < i && dst[j] != ' '; j++) {
  874. if (IsDBCS1(dst[j])) {
  875. if (j == i - 1) break;
  876. j++;
  877. }
  878. }
  879. do {
  880. dst[j++] = (i < 8) ? ns[i++] : ' ';
  881. } while (j < 8);
  882. }
  883. #endif
  884. /*-----------------------------------------------------------------------*/
  885. /* Calculate sum of an SFN */
  886. /*-----------------------------------------------------------------------*/
  887. #if _USE_LFN
  888. static
  889. BYTE sum_sfn (
  890. const BYTE *dir /* Ptr to directory entry */
  891. )
  892. {
  893. BYTE sum = 0;
  894. UINT n = 11;
  895. do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  896. return sum;
  897. }
  898. #endif
  899. /*-----------------------------------------------------------------------*/
  900. /* Directory handling - Find an object in the directory */
  901. /*-----------------------------------------------------------------------*/
  902. static
  903. FRESULT dir_find (
  904. DIR *dj /* Pointer to the directory object linked to the file name */
  905. )
  906. {
  907. FRESULT res;
  908. BYTE c, *dir;
  909. #if _USE_LFN
  910. BYTE a, ord, sum;
  911. #endif
  912. res = dir_sdi(dj, 0); /* Rewind directory object */
  913. if (res != FR_OK) return res;
  914. #if _USE_LFN
  915. ord = sum = 0xFF;
  916. #endif
  917. do {
  918. res = move_window(dj->fs, dj->sect);
  919. if (res != FR_OK) break;
  920. dir = dj->dir; /* Ptr to the directory entry of current index */
  921. c = dir[DIR_Name];
  922. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  923. #if _USE_LFN /* LFN configuration */
  924. a = dir[DIR_Attr] & AM_MASK;
  925. if (c == 0xE5 || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  926. ord = 0xFF;
  927. } else {
  928. if (a == AM_LFN) { /* An LFN entry is found */
  929. if (dj->lfn) {
  930. if (c & 0x40) { /* Is it start of LFN sequence? */
  931. sum = dir[LDIR_Chksum];
  932. c &= 0xBF; ord = c; /* LFN start order */
  933. dj->lfn_idx = dj->index;
  934. }
  935. /* Check validity of the LFN entry and compare it with given name */
  936. ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  937. }
  938. } else { /* An SFN entry is found */
  939. if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */
  940. ord = 0xFF; dj->lfn_idx = 0xFFFF; /* Reset LFN sequence */
  941. if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break; /* SFN matched? */
  942. }
  943. }
  944. #else /* Non LFN configuration */
  945. if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
  946. break;
  947. #endif
  948. res = dir_next(dj, 0); /* Next entry */
  949. } while (res == FR_OK);
  950. return res;
  951. }
  952. /*-----------------------------------------------------------------------*/
  953. /* Read an object from the directory */
  954. /*-----------------------------------------------------------------------*/
  955. #if _FS_MINIMIZE <= 1
  956. static
  957. FRESULT dir_read (
  958. DIR *dj /* Pointer to the directory object that pointing the entry to be read */
  959. )
  960. {
  961. FRESULT res;
  962. BYTE c, *dir;
  963. #if _USE_LFN
  964. BYTE a, ord = 0xFF, sum = 0xFF;
  965. #endif
  966. res = FR_NO_FILE;
  967. while (dj->sect) {
  968. res = move_window(dj->fs, dj->sect);
  969. if (res != FR_OK) break;
  970. dir = dj->dir; /* Ptr to the directory entry of current index */
  971. c = dir[DIR_Name];
  972. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  973. #if _USE_LFN /* LFN configuration */
  974. a = dir[DIR_Attr] & AM_MASK;
  975. if (c == 0xE5 || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  976. ord = 0xFF;
  977. } else {
  978. if (a == AM_LFN) { /* An LFN entry is found */
  979. if (c & 0x40) { /* Is it start of LFN sequence? */
  980. sum = dir[LDIR_Chksum];
  981. c &= 0xBF; ord = c;
  982. dj->lfn_idx = dj->index;
  983. }
  984. /* Check LFN validity and capture it */
  985. ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
  986. } else { /* An SFN entry is found */
  987. if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */
  988. dj->lfn_idx = 0xFFFF; /* It has no LFN. */
  989. break;
  990. }
  991. }
  992. #else /* Non LFN configuration */
  993. if (c != 0xE5 && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */
  994. break;
  995. #endif
  996. res = dir_next(dj, 0); /* Next entry */
  997. if (res != FR_OK) break;
  998. }
  999. if (res != FR_OK) dj->sect = 0;
  1000. return res;
  1001. }
  1002. #endif
  1003. /*-----------------------------------------------------------------------*/
  1004. /* Register an object to the directory */
  1005. /*-----------------------------------------------------------------------*/
  1006. #if !_FS_READONLY
  1007. static
  1008. FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
  1009. DIR *dj /* Target directory with object name to be created */
  1010. )
  1011. {
  1012. FRESULT res;
  1013. BYTE c, *dir;
  1014. #if _USE_LFN /* LFN configuration */
  1015. WORD n, ne, is;
  1016. BYTE sn[12], *fn, sum;
  1017. WCHAR *lfn;
  1018. fn = dj->fn; lfn = dj->lfn;
  1019. mem_cpy(sn, fn, 12);
  1020. if (_FS_RPATH && (sn[NS] & NS_DOT)) /* Cannot create dot entry */
  1021. return FR_INVALID_NAME;
  1022. if (sn[NS] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  1023. fn[NS] = 0; dj->lfn = 0; /* Find only SFN */
  1024. for (n = 1; n < 100; n++) {
  1025. gen_numname(fn, sn, lfn, n); /* Generate a numbered name */
  1026. res = dir_find(dj); /* Check if the name collides with existing SFN */
  1027. if (res != FR_OK) break;
  1028. }
  1029. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  1030. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  1031. fn[NS] = sn[NS]; dj->lfn = lfn;
  1032. }
  1033. if (sn[NS] & NS_LFN) { /* When LFN is to be created, reserve an SFN + LFN entries. */
  1034. for (ne = 0; lfn[ne]; ne++) ;
  1035. ne = (ne + 25) / 13;
  1036. } else { /* Otherwise reserve only an SFN entry. */
  1037. ne = 1;
  1038. }
  1039. /* Reserve contiguous entries */
  1040. res = dir_sdi(dj, 0);
  1041. if (res != FR_OK) return res;
  1042. n = is = 0;
  1043. do {
  1044. res = move_window(dj->fs, dj->sect);
  1045. if (res != FR_OK) break;
  1046. c = *dj->dir; /* Check the entry status */
  1047. if (c == 0xE5 || c == 0) { /* Is it a blank entry? */
  1048. if (n == 0) is = dj->index; /* First index of the contiguous entry */
  1049. if (++n == ne) break; /* A contiguous entry that required count is found */
  1050. } else {
  1051. n = 0; /* Not a blank entry. Restart to search */
  1052. }
  1053. res = dir_next(dj, 1); /* Next entry with table stretch */
  1054. } while (res == FR_OK);
  1055. if (res == FR_OK && ne > 1) { /* Initialize LFN entry if needed */
  1056. res = dir_sdi(dj, is);
  1057. if (res == FR_OK) {
  1058. sum = sum_sfn(dj->fn); /* Sum of the SFN tied to the LFN */
  1059. ne--;
  1060. do { /* Store LFN entries in bottom first */
  1061. res = move_window(dj->fs, dj->sect);
  1062. if (res != FR_OK) break;
  1063. fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);
  1064. dj->fs->wflag = 1;
  1065. res = dir_next(dj, 0); /* Next entry */
  1066. } while (res == FR_OK && --ne);
  1067. }
  1068. }
  1069. #else /* Non LFN configuration */
  1070. res = dir_sdi(dj, 0);
  1071. if (res == FR_OK) {
  1072. do { /* Find a blank entry for the SFN */
  1073. res = move_window(dj->fs, dj->sect);
  1074. if (res != FR_OK) break;
  1075. c = *dj->dir;
  1076. if (c == 0xE5 || c == 0) break; /* Is it a blank entry? */
  1077. res = dir_next(dj, 1); /* Next entry with table stretch */
  1078. } while (res == FR_OK);
  1079. }
  1080. #endif
  1081. if (res == FR_OK) { /* Initialize the SFN entry */
  1082. res = move_window(dj->fs, dj->sect);
  1083. if (res == FR_OK) {
  1084. dir = dj->dir;
  1085. mem_set(dir, 0, 32); /* Clean the entry */
  1086. mem_cpy(dir, dj->fn, 11); /* Put SFN */
  1087. #if _USE_LFN
  1088. dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT); /* Put NT flag */
  1089. #endif
  1090. dj->fs->wflag = 1;
  1091. }
  1092. }
  1093. return res;
  1094. }
  1095. #endif /* !_FS_READONLY */
  1096. /*-----------------------------------------------------------------------*/
  1097. /* Remove an object from the directory */
  1098. /*-----------------------------------------------------------------------*/
  1099. #if !_FS_READONLY && !_FS_MINIMIZE
  1100. static
  1101. FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */
  1102. DIR *dj /* Directory object pointing the entry to be removed */
  1103. )
  1104. {
  1105. FRESULT res;
  1106. #if _USE_LFN /* LFN configuration */
  1107. WORD i;
  1108. i = dj->index; /* SFN index */
  1109. res = dir_sdi(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx)); /* Goto the SFN or top of the LFN entries */
  1110. if (res == FR_OK) {
  1111. do {
  1112. res = move_window(dj->fs, dj->sect);
  1113. if (res != FR_OK) break;
  1114. *dj->dir = 0xE5; /* Mark the entry "deleted" */
  1115. dj->fs->wflag = 1;
  1116. if (dj->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */
  1117. res = dir_next(dj, 0); /* Next entry */
  1118. } while (res == FR_OK);
  1119. if (res == FR_NO_FILE) res = FR_INT_ERR;
  1120. }
  1121. #else /* Non LFN configuration */
  1122. res = dir_sdi(dj, dj->index);
  1123. if (res == FR_OK) {
  1124. res = move_window(dj->fs, dj->sect);
  1125. if (res == FR_OK) {
  1126. *dj->dir = 0xE5; /* Mark the entry "deleted" */
  1127. dj->fs->wflag = 1;
  1128. }
  1129. }
  1130. #endif
  1131. return res;
  1132. }
  1133. #endif /* !_FS_READONLY */
  1134. /*-----------------------------------------------------------------------*/
  1135. /* Pick a segment and create the object name in directory form */
  1136. /*-----------------------------------------------------------------------*/
  1137. static
  1138. FRESULT create_name (
  1139. DIR *dj, /* Pointer to the directory object */
  1140. const TCHAR **path /* Pointer to pointer to the segment in the path string */
  1141. )
  1142. {
  1143. #ifdef _EXCVT
  1144. static const BYTE excvt[] = _EXCVT; /* Upper conversion table for extended chars */
  1145. #endif
  1146. #if _USE_LFN /* LFN configuration */
  1147. BYTE b, cf;
  1148. WCHAR w, *lfn;
  1149. UINT i, ni, si, di;
  1150. const TCHAR *p;
  1151. /* Create LFN in Unicode */
  1152. si = di = 0;
  1153. p = *path;
  1154. lfn = dj->lfn;
  1155. for (;;) {
  1156. w = p[si++]; /* Get a character */
  1157. if (w < ' ' || w == '/' || w == '\\') break; /* Break on end of segment */
  1158. if (di >= _MAX_LFN) /* Reject too long name */
  1159. return FR_INVALID_NAME;
  1160. #if !_LFN_UNICODE
  1161. w &= 0xFF;
  1162. if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1163. b = (BYTE)p[si++]; /* Get 2nd byte */
  1164. if (!IsDBCS2(b))
  1165. return FR_INVALID_NAME; /* Reject invalid sequence */
  1166. w = (w << 8) + b; /* Create a DBC */
  1167. }
  1168. w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
  1169. if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  1170. #endif
  1171. if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */
  1172. return FR_INVALID_NAME;
  1173. lfn[di++] = w; /* Store the Unicode char */
  1174. }
  1175. *path = &p[si]; /* Return pointer to the next segment */
  1176. cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
  1177. #if _FS_RPATH
  1178. if ((di == 1 && lfn[di-1] == '.') || /* Is this a dot entry? */
  1179. (di == 2 && lfn[di-1] == '.' && lfn[di-2] == '.')) {
  1180. lfn[di] = 0;
  1181. for (i = 0; i < 11; i++)
  1182. dj->fn[i] = (i < di) ? '.' : ' ';
  1183. dj->fn[i] = cf | NS_DOT; /* This is a dot entry */
  1184. return FR_OK;
  1185. }
  1186. #endif
  1187. while (di) { /* Strip trailing spaces and dots */
  1188. w = lfn[di-1];
  1189. if (w != ' ' && w != '.') break;
  1190. di--;
  1191. }
  1192. if (!di) return FR_INVALID_NAME; /* Reject nul string */
  1193. lfn[di] = 0; /* LFN is created */
  1194. /* Create SFN in directory form */
  1195. mem_set(dj->fn, ' ', 11);
  1196. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  1197. if (si) cf |= NS_LOSS | NS_LFN;
  1198. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  1199. b = i = 0; ni = 8;
  1200. for (;;) {
  1201. w = lfn[si++]; /* Get an LFN char */
  1202. if (!w) break; /* Break on end of the LFN */
  1203. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  1204. cf |= NS_LOSS | NS_LFN; continue;
  1205. }
  1206. if (i >= ni || si == di) { /* Extension or end of SFN */
  1207. if (ni == 11) { /* Long extension */
  1208. cf |= NS_LOSS | NS_LFN; break;
  1209. }
  1210. if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
  1211. if (si > di) break; /* No extension */
  1212. si = di; i = 8; ni = 11; /* Enter extension section */
  1213. b <<= 2; continue;
  1214. }
  1215. if (w >= 0x80) { /* Non ASCII char */
  1216. #ifdef _EXCVT
  1217. w = ff_convert(w, 0); /* Unicode -> OEM code */
  1218. if (w) w = excvt[w - 0x80]; /* Convert extended char to upper (SBCS) */
  1219. #else
  1220. w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
  1221. #endif
  1222. cf |= NS_LFN; /* Force create LFN entry */
  1223. }
  1224. if (_DF1S && w >= 0x100) { /* Double byte char (always false on SBCS cfg) */
  1225. if (i >= ni - 1) {
  1226. cf |= NS_LOSS | NS_LFN; i = ni; continue;
  1227. }
  1228. dj->fn[i++] = (BYTE)(w >> 8);
  1229. } else { /* Single byte char */
  1230. if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal chars for SFN */
  1231. w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  1232. } else {
  1233. if (IsUpper(w)) { /* ASCII large capital */
  1234. b |= 2;
  1235. } else {
  1236. if (IsLower(w)) { /* ASCII small capital */
  1237. b |= 1; w -= 0x20;
  1238. }
  1239. }
  1240. }
  1241. }
  1242. dj->fn[i++] = (BYTE)w;
  1243. }
  1244. if (dj->fn[0] == 0xE5) dj->fn[0] = 0x05; /* If the first char collides with deleted mark, replace it with 0x05 */
  1245. if (ni == 8) b <<= 2;
  1246. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */
  1247. cf |= NS_LFN;
  1248. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended char, NT flags are created */
  1249. if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
  1250. if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
  1251. }
  1252. dj->fn[NS] = cf; /* SFN is created */
  1253. return FR_OK;
  1254. #else /* Non-LFN configuration */
  1255. BYTE b, c, d, *sfn;
  1256. UINT ni, si, i;
  1257. const char *p;
  1258. /* Create file name in directory form */
  1259. sfn = dj->fn;
  1260. mem_set(sfn, ' ', 11);
  1261. si = i = b = 0; ni = 8;
  1262. p = *path;
  1263. #if _FS_RPATH
  1264. if (p[si] == '.') { /* Is this a dot entry? */
  1265. for (;;) {
  1266. c = (BYTE)p[si++];
  1267. if (c != '.' || si >= 3) break;
  1268. sfn[i++] = c;
  1269. }
  1270. if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  1271. *path = &p[si]; /* Return pointer to the next segment */
  1272. sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of path */
  1273. return FR_OK;
  1274. }
  1275. #endif
  1276. for (;;) {
  1277. c = (BYTE)p[si++];
  1278. if (c <= ' ' || c == '/' || c == '\\') break; /* Break on end of segment */
  1279. if (c == '.' || i >= ni) {
  1280. if (ni != 8 || c != '.') return FR_INVALID_NAME;
  1281. i = 8; ni = 11;
  1282. b <<= 2; continue;
  1283. }
  1284. if (c >= 0x80) { /* Extended char? */
  1285. b |= 3; /* Eliminate NT flag */
  1286. #ifdef _EXCVT
  1287. c = excvt[c-0x80]; /* Upper conversion (SBCS) */
  1288. #else
  1289. #if !_DF1S /* ASCII only cfg */
  1290. return FR_INVALID_NAME;
  1291. #endif
  1292. #endif
  1293. }
  1294. if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1295. d = (BYTE)p[si++]; /* Get 2nd byte */
  1296. if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */
  1297. return FR_INVALID_NAME;
  1298. sfn[i++] = c;
  1299. sfn[i++] = d;
  1300. } else { /* Single byte code */
  1301. if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) /* Reject illegal chrs for SFN */
  1302. return FR_INVALID_NAME;
  1303. if (IsUpper(c)) { /* ASCII large capital? */
  1304. b |= 2;
  1305. } else {
  1306. if (IsLower(c)) { /* ASCII small capital? */
  1307. b |= 1; c -= 0x20;
  1308. }
  1309. }
  1310. sfn[i++] = c;
  1311. }
  1312. }
  1313. *path = &p[si]; /* Return pointer to the next segment */
  1314. c = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
  1315. if (!i) return FR_INVALID_NAME; /* Reject nul string */
  1316. if (sfn[0] == 0xE5) sfn[0] = 0x05; /* When first char collides with 0xE5, replace it with 0x05 */
  1317. if (ni == 8) b <<= 2;
  1318. if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Name extension has only small capital) */
  1319. if ((b & 0x0C) == 0x04) c |= NS_BODY; /* NT flag (Name body has only small capital) */
  1320. sfn[NS] = c; /* Store NT flag, File name is created */
  1321. return FR_OK;
  1322. #endif
  1323. }
  1324. /*-----------------------------------------------------------------------*/
  1325. /* Get file information from directory entry */
  1326. /*-----------------------------------------------------------------------*/
  1327. #if _FS_MINIMIZE <= 1
  1328. static
  1329. void get_fileinfo ( /* No return code */
  1330. DIR *dj, /* Pointer to the directory object */
  1331. FILINFO *fno /* Pointer to the file information to be filled */
  1332. )
  1333. {
  1334. UINT i;
  1335. BYTE nt, *dir;
  1336. TCHAR *p, c;
  1337. p = fno->fname;
  1338. if (dj->sect) {
  1339. dir = dj->dir;
  1340. nt = dir[DIR_NTres]; /* NT flag */
  1341. for (i = 0; i < 8; i++) { /* Copy name body */
  1342. c = dir[i];
  1343. if (c == ' ') break;
  1344. if (c == 0x05) c = (TCHAR)0xE5;
  1345. if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;
  1346. #if _LFN_UNICODE
  1347. if (IsDBCS1(c) && i < 7 && IsDBCS2(dir[i+1]))
  1348. c = (c << 8) | dir[++i];
  1349. c = ff_convert(c, 1);
  1350. if (!c) c = '?';
  1351. #endif
  1352. *p++ = c;
  1353. }
  1354. if (dir[8] != ' ') { /* Copy name extension */
  1355. *p++ = '.';
  1356. for (i = 8; i < 11; i++) {
  1357. c = dir[i];
  1358. if (c == ' ') break;
  1359. if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;
  1360. #if _LFN_UNICODE
  1361. if (IsDBCS1(c) && i < 10 && IsDBCS2(dir[i+1]))
  1362. c = (c << 8) | dir[++i];
  1363. c = ff_convert(c, 1);
  1364. if (!c) c = '?';
  1365. #endif
  1366. *p++ = c;
  1367. }
  1368. }
  1369. fno->fattrib = dir[DIR_Attr]; /* Attribute */
  1370. fno->fsize = LD_DWORD(dir+DIR_FileSize); /* Size */
  1371. fno->fdate = LD_WORD(dir+DIR_WrtDate); /* Date */
  1372. fno->ftime = LD_WORD(dir+DIR_WrtTime); /* Time */
  1373. fno->clust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16)
  1374. | LD_WORD(dir+DIR_FstClusLO);
  1375. }
  1376. *p = 0; /* Terminate SFN str by a \0 */
  1377. #if _USE_LFN
  1378. if (fno->lfname && fno->lfsize) {
  1379. TCHAR *tp = fno->lfname;
  1380. WCHAR w, *lfn;
  1381. i = 0;
  1382. if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
  1383. lfn = dj->lfn;
  1384. while ((w = *lfn++) != 0) { /* Get an LFN char */
  1385. #if !_LFN_UNICODE
  1386. w = ff_convert(w, 0); /* Unicode -> OEM conversion */
  1387. if (!w) { i = 0; break; } /* Could not convert, no LFN */
  1388. if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */
  1389. tp[i++] = (TCHAR)(w >> 8);
  1390. #endif
  1391. if (i >= fno->lfsize - 1) { i = 0; break; } /* Buffer overflow, no LFN */
  1392. tp[i++] = (TCHAR)w;
  1393. }
  1394. }
  1395. tp[i] = 0; /* Terminate the LFN str by a \0 */
  1396. }
  1397. #endif
  1398. }
  1399. #endif /* _FS_MINIMIZE <= 1 */
  1400. /*-----------------------------------------------------------------------*/
  1401. /* Follow a file path */
  1402. /*-----------------------------------------------------------------------*/
  1403. static
  1404. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  1405. DIR *dj, /* Directory object to return last directory and found object */
  1406. const TCHAR *path /* Full-path string to find a file or directory */
  1407. )
  1408. {
  1409. FRESULT res;
  1410. BYTE *dir, ns;
  1411. #if _FS_RPATH
  1412. if (*path == '/' || *path == '\\') { /* There is a heading separator */
  1413. path++; dj->sclust = 0; /* Strip it and start from the root dir */
  1414. } else { /* No heading separator */
  1415. dj->sclust = dj->fs->cdir; /* Start from the current dir */
  1416. }
  1417. #else
  1418. if (*path == '/' || *path == '\\') /* Strip heading separator if exist */
  1419. path++;
  1420. dj->sclust = 0; /* Start from the root dir */
  1421. #endif
  1422. if ((UINT)*path < ' ') { /* Nul path means the start directory itself */
  1423. res = dir_sdi(dj, 0);
  1424. dj->dir = 0;
  1425. } else { /* Follow path */
  1426. for (;;) {
  1427. res = create_name(dj, &path); /* Get a segment */
  1428. if (res != FR_OK) break;
  1429. res = dir_find(dj); /* Find it */
  1430. ns = *(dj->fn+NS);
  1431. if (res != FR_OK) { /* Failed to find the object */
  1432. if (res != FR_NO_FILE) break; /* Abort if any hard error occured */
  1433. /* Object not found */
  1434. if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exit */
  1435. dj->sclust = 0; dj->dir = 0; /* It is the root dir */
  1436. res = FR_OK;
  1437. if (!(ns & NS_LAST)) continue;
  1438. } else { /* Could not find the object */
  1439. if (!(ns & NS_LAST)) res = FR_NO_PATH;
  1440. }
  1441. break;
  1442. }
  1443. if (ns & NS_LAST) break; /* Last segment match. Function completed. */
  1444. dir = dj->dir; /* There is next segment. Follow the sub directory */
  1445. if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */
  1446. res = FR_NO_PATH; break;
  1447. }
  1448. dj->sclust = LD_CLUST(dir);
  1449. }
  1450. }
  1451. return res;
  1452. }
  1453. /*-----------------------------------------------------------------------*/
  1454. /* Load boot record and check if it is an FAT boot record */
  1455. /*-----------------------------------------------------------------------*/
  1456. static
  1457. BYTE check_fs ( /* 0:The FAT BR, 1:Valid BR but not an FAT, 2:Not a BR, 3:Disk error */
  1458. FATFS *fs, /* File system object */
  1459. DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */
  1460. )
  1461. {
  1462. if (disk_read(fs->drv, fs->win, sect, 1) != RES_OK) /* Load boot record */
  1463. return 3;
  1464. if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */
  1465. return 2;
  1466. if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
  1467. return 0;
  1468. if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)
  1469. return 0;
  1470. return 1;
  1471. }
  1472. /*-----------------------------------------------------------------------*/
  1473. /* Check if the file system object is valid or not */
  1474. /*-----------------------------------------------------------------------*/
  1475. static
  1476. FRESULT chk_mounted ( /* FR_OK(0): successful, !=0: any error occurred */
  1477. const TCHAR **path, /* Pointer to pointer to the path name (drive number) */
  1478. FATFS **rfs, /* Pointer to pointer to the found file system object */
  1479. BYTE chk_wp /* !=0: Check media write protection for write access */
  1480. )
  1481. {
  1482. BYTE fmt, b, *tbl;
  1483. UINT vol;
  1484. DSTATUS stat;
  1485. DWORD bsect, fasize, tsect, sysect, nclst, szbfat;
  1486. WORD nrsv;
  1487. const TCHAR *p = *path;
  1488. FATFS *fs;
  1489. /* Get logical drive number from the path name */
  1490. vol = p[0] - '0'; /* Is there a drive number? */
  1491. if (vol <= 9 && p[1] == ':') { /* Found a drive number, get and strip it */
  1492. p += 2; *path = p; /* Return pointer to the path name */
  1493. } else { /* No drive number is given */
  1494. #if _FS_RPATH
  1495. vol = CurrVol; /* Use current drive */
  1496. #else
  1497. vol = 0; /* Use drive 0 */
  1498. #endif
  1499. }
  1500. /* Check if the logical drive is valid or not */
  1501. if (vol >= _VOLUMES) /* Is the drive number valid? */
  1502. return FR_INVALID_DRIVE;
  1503. *rfs = fs = FatFs[vol]; /* Return pointer to the corresponding file system object */
  1504. if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
  1505. ENTER_FF(fs); /* Lock file system */
  1506. if (fs->fs_type) { /* If the logical drive has been mounted */
  1507. stat = disk_status(fs->drv);
  1508. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized (has not been changed), */
  1509. #if !_FS_READONLY
  1510. if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */
  1511. return FR_WRITE_PROTECTED;
  1512. #endif
  1513. return FR_OK; /* The file system object is valid */
  1514. }
  1515. }
  1516. /* The logical drive must be mounted. */
  1517. /* Following code attempts to mount a volume. (analyze BPB and initialize the fs object) */
  1518. fs->fs_type = 0; /* Clear the file system object */
  1519. fs->drv = (BYTE)LD2PD(vol); /* Bind the logical drive and a physical drive */
  1520. stat = disk_initialize(fs->drv); /* Initialize low level disk I/O layer */
  1521. if (stat & STA_NOINIT) /* Check if the initialization succeeded */
  1522. return FR_NOT_READY; /* Failed to initialize due to no media or hard error */
  1523. #if _MAX_SS != 512 /* Get disk sector size (variable sector size cfg only) */
  1524. if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &fs->ssize) != RES_OK)
  1525. return FR_DISK_ERR;
  1526. #endif
  1527. #if !_FS_READONLY
  1528. if (chk_wp && (stat & STA_PROTECT)) /* Check disk write protection if needed */
  1529. return FR_WRITE_PROTECTED;
  1530. #endif
  1531. /* Search FAT partition on the drive. Supports only generic partitionings, FDISK and SFD. */
  1532. fmt = check_fs(fs, bsect = 0); /* Check sector 0 if it is a VBR */
  1533. if (fmt == 1) { /* Not an FAT-VBR, the disk may be partitioned */
  1534. /* Check the partition listed in top of the partition table */
  1535. tbl = &fs->win[MBR_Table + LD2PT(vol) * 16]; /* Partition table */
  1536. if (tbl[4]) { /* Is the partition existing? */
  1537. bsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */
  1538. fmt = check_fs(fs, bsect); /* Check the partition */
  1539. }
  1540. }
  1541. if (fmt == 3) return FR_DISK_ERR;
  1542. if (fmt) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  1543. /* Following code initializes the file system object */
  1544. if (LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs)) /* (BPB_BytsPerSec must be equal to the physical sector size) */
  1545. return FR_NO_FILESYSTEM;
  1546. fasize = LD_WORD(fs->win+BPB_FATSz16); /* Number of sectors per FAT */
  1547. if (!fasize) fasize = LD_DWORD(fs->win+BPB_FATSz32);
  1548. fs->fsize = fasize;
  1549. fs->n_fats = b = fs->win[BPB_NumFATs]; /* Number of FAT copies */
  1550. if (b != 1 && b != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  1551. fasize *= b; /* Number of sectors for FAT area */
  1552. fs->csize = b = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
  1553. if (!b || (b & (b - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  1554. fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt); /* Number of root directory entries */
  1555. if (fs->n_rootdir % (SS(fs) / 32)) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be sector aligned) */
  1556. tsect = LD_WORD(fs->win+BPB_TotSec16); /* Number of sectors on the volume */
  1557. if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);
  1558. nrsv = LD_WORD(fs->win+BPB_RsvdSecCnt); /* Number of reserved sectors */
  1559. if (!nrsv) return FR_NO_FILESYSTEM; /* (BPB_RsvdSecCnt must not be 0) */
  1560. /* Determine the FAT sub type */
  1561. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / 32); /* RSV+FAT+DIR */
  1562. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  1563. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  1564. if (!nclst) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  1565. fmt = FS_FAT12;
  1566. if (nclst >= MIN_FAT16) fmt = FS_FAT16;
  1567. if (nclst >= MIN_FAT32) fmt = FS_FAT32;
  1568. /* Boundaries and Limits */
  1569. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  1570. fs->database = bsect + sysect; /* Data start sector */
  1571. fs->fatbase = bsect + nrsv; /* FAT start sector */
  1572. if (fmt == FS_FAT32) {
  1573. if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  1574. fs->dirbase = LD_DWORD(fs->win+BPB_RootClus); /* Root directory start cluster */
  1575. szbfat = fs->n_fatent * 4; /* (Required FAT size) */
  1576. } else {
  1577. if (!fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */
  1578. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  1579. szbfat = (fmt == FS_FAT16) ? /* (Required FAT size) */
  1580. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  1581. }
  1582. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) /* (FAT size must not be less than FAT sectors */
  1583. return FR_NO_FILESYSTEM;
  1584. #if !_FS_READONLY
  1585. /* Initialize cluster allocation information */
  1586. fs->free_clust = 0xFFFFFFFF;
  1587. fs->last_clust = 0;
  1588. /* Get fsinfo if available */
  1589. if (fmt == FS_FAT32) {
  1590. fs->fsi_flag = 0;
  1591. fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);
  1592. if (disk_read(fs->drv, fs->win, fs->fsi_sector, 1) == RES_OK &&
  1593. LD_WORD(fs->win+BS_55AA) == 0xAA55 &&
  1594. LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&
  1595. LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {
  1596. fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);
  1597. fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);
  1598. }
  1599. }
  1600. #endif
  1601. fs->fs_type = fmt; /* FAT sub-type */
  1602. fs->id = ++Fsid; /* File system mount ID */
  1603. fs->winsect = 0; /* Invalidate sector cache */
  1604. fs->wflag = 0;
  1605. #if _FS_RPATH
  1606. fs->cdir = 0; /* Current directory (root dir) */
  1607. #endif
  1608. #if _FS_SHARE /* Clear file lock semaphores */
  1609. clear_lock(fs);
  1610. #endif
  1611. return FR_OK;
  1612. }
  1613. /*-----------------------------------------------------------------------*/
  1614. /* Check if the file/dir object is valid or not */
  1615. /*-----------------------------------------------------------------------*/
  1616. static
  1617. FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
  1618. FATFS *fs, /* Pointer to the file system object */
  1619. WORD id /* Member id of the target object to be checked */
  1620. )
  1621. {
  1622. // printf("fs=%p fs->fs_type=%d fs->id=%d id=%d\n", fs, fs->fs_type, fs->id, id);
  1623. if (!fs || !fs->fs_type || fs->id != id)
  1624. return FR_INVALID_OBJECT;
  1625. ENTER_FF(fs); /* Lock file system */
  1626. if (disk_status(fs->drv) & STA_NOINIT)
  1627. return FR_NOT_READY;
  1628. return FR_OK;
  1629. }
  1630. /*--------------------------------------------------------------------------
  1631. Public Functions
  1632. --------------------------------------------------------------------------*/
  1633. /*-----------------------------------------------------------------------*/
  1634. /* Mount/Unmount a Logical Drive */
  1635. /*-----------------------------------------------------------------------*/
  1636. FRESULT f_mount (
  1637. BYTE vol, /* Logical drive number to be mounted/unmounted */
  1638. FATFS *fs /* Pointer to new file system object (NULL for unmount)*/
  1639. )
  1640. {
  1641. FATFS *rfs;
  1642. if (vol >= _VOLUMES) /* Check if the drive number is valid */
  1643. return FR_INVALID_DRIVE;
  1644. rfs = FatFs[vol]; /* Get current fs object */
  1645. if (rfs) {
  1646. #if _FS_SHARE
  1647. clear_lock(rfs);
  1648. #endif
  1649. #if _FS_REENTRANT /* Discard sync object of the current volume */
  1650. if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;
  1651. #endif
  1652. rfs->fs_type = 0; /* Clear old fs object */
  1653. }
  1654. if (fs) {
  1655. fs->fs_type = 0; /* Clear new fs object */
  1656. #if _FS_REENTRANT /* Create sync object for the new volume */
  1657. if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
  1658. #endif
  1659. }
  1660. FatFs[vol] = fs; /* Register new fs object */
  1661. return FR_OK;
  1662. }
  1663. /*-----------------------------------------------------------------------*/
  1664. /* Open or Create a File */
  1665. /*-----------------------------------------------------------------------*/
  1666. FRESULT f_open (
  1667. FIL *fp, /* Pointer to the blank file object */
  1668. const TCHAR *path, /* Pointer to the file name */
  1669. BYTE mode /* Access mode and file open mode flags */
  1670. )
  1671. {
  1672. FRESULT res;
  1673. DIR dj;
  1674. BYTE *dir;
  1675. DEF_NAMEBUF;
  1676. fp->fs = 0; /* Clear file object */
  1677. #if !_FS_READONLY
  1678. mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;
  1679. res = chk_mounted(&path, &dj.fs, (BYTE)(mode & ~FA_READ));
  1680. #else
  1681. mode &= FA_READ;
  1682. res = chk_mounted(&path, &dj.fs, 0);
  1683. #endif
  1684. INIT_BUF(dj);
  1685. if (res == FR_OK)
  1686. res = follow_path(&dj, path); /* Follow the file path */
  1687. dir = dj.dir;
  1688. #if !_FS_READONLY /* R/W configuration */
  1689. if (res == FR_OK) {
  1690. if (!dir) /* Current dir itself */
  1691. res = FR_INVALID_NAME;
  1692. #if _FS_SHARE
  1693. else
  1694. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  1695. #endif
  1696. }
  1697. /* Create or Open a file */
  1698. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  1699. DWORD dw, cl;
  1700. if (res != FR_OK) { /* No file, create new */
  1701. if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
  1702. #if _FS_SHARE
  1703. res = enq_lock(dj.fs) ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  1704. #else
  1705. res = dir_register(&dj);
  1706. #endif
  1707. mode |= FA_CREATE_ALWAYS; /* File is created */
  1708. dir = dj.dir; /* New entry */
  1709. }
  1710. else { /* Any object is already existing */
  1711. if (mode & FA_CREATE_NEW) { /* Cannot create new */
  1712. res = FR_EXIST;
  1713. } else {
  1714. if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) /* Cannot overwrite it (R/O or DIR) */
  1715. res = FR_DENIED;
  1716. }
  1717. }
  1718. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
  1719. dw = get_fattime(); /* Created time */
  1720. ST_DWORD(dir+DIR_CrtTime, dw);
  1721. dir[DIR_Attr] = 0; /* Reset attribute */
  1722. ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */
  1723. cl = LD_CLUST(dir); /* Get start cluster */
  1724. ST_CLUST(dir, 0); /* cluster = 0 */
  1725. dj.fs->wflag = 1;
  1726. if (cl) { /* Remove the cluster chain if exist */
  1727. dw = dj.fs->winsect;
  1728. res = remove_chain(dj.fs, cl);
  1729. if (res == FR_OK) {
  1730. dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */
  1731. res = move_window(dj.fs, dw);
  1732. }
  1733. }
  1734. }
  1735. }
  1736. else { /* Open an existing file */
  1737. if (res == FR_OK) { /* Follow succeeded */
  1738. if (dir[DIR_Attr] & AM_DIR) { /* It is a directory */
  1739. res = FR_NO_FILE;
  1740. } else {
  1741. if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
  1742. res = FR_DENIED;
  1743. }
  1744. }
  1745. }
  1746. if (res == FR_OK) {
  1747. if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
  1748. mode |= FA__WRITTEN;
  1749. fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
  1750. fp->dir_ptr = dir;
  1751. #if _FS_SHARE
  1752. fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  1753. if (!fp->lockid) res = FR_INT_ERR;
  1754. #endif
  1755. }
  1756. #else /* R/O configuration */
  1757. if (res == FR_OK) { /* Follow succeeded */
  1758. if (!dir) { /* Current dir itself */
  1759. res = FR_INVALID_NAME;
  1760. } else {
  1761. if (dir[DIR_Attr] & AM_DIR) /* It is a directory */
  1762. res = FR_NO_FILE;
  1763. }
  1764. }
  1765. #endif
  1766. FREE_BUF();
  1767. if (res == FR_OK) {
  1768. fp->flag = mode; /* File access mode */
  1769. fp->org_clust = LD_CLUST(dir); /* File start cluster */
  1770. fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */
  1771. fp->fptr = 0; /* File pointer */
  1772. fp->dsect = 0;
  1773. #if _USE_FASTSEEK
  1774. fp->cltbl = 0; /* No cluster link map table */
  1775. #endif
  1776. fp->fs = dj.fs; fp->id = dj.fs->id; /* Validate file object */
  1777. }
  1778. LEAVE_FF(dj.fs, res);
  1779. }
  1780. /*-----------------------------------------------------------------------*/
  1781. /* Read File */
  1782. /*-----------------------------------------------------------------------*/
  1783. FRESULT f_read (
  1784. FIL *fp, /* Pointer to the file object */
  1785. void *buff, /* Pointer to data buffer */
  1786. UINT btr, /* Number of bytes to read */
  1787. UINT *br /* Pointer to number of bytes read */
  1788. )
  1789. {
  1790. FRESULT res;
  1791. DWORD clst, sect, remain;
  1792. UINT rcnt, cc;
  1793. BYTE csect, *rbuff = buff;
  1794. if(btr>512 && !ff_sd_offload) printf("WARNING: read >512 bytes but offloading is inactive!!\n");
  1795. *br = 0; /* Initialize byte counter */
  1796. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1797. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  1798. if (fp->flag & FA__ERROR) /* Check abort flag */
  1799. LEAVE_FF(fp->fs, FR_INT_ERR);
  1800. if (!(fp->flag & FA_READ)) /* Check access mode */
  1801. LEAVE_FF(fp->fs, FR_DENIED);
  1802. remain = fp->fsize - fp->fptr;
  1803. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  1804. for ( ; btr; /* Repeat until all data transferred */
  1805. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  1806. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  1807. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  1808. if (!csect) { /* On the cluster boundary? */
  1809. clst = (fp->fptr == 0) ? /* On the top of the file? */
  1810. fp->org_clust : get_fat(fp->fs, fp->curr_clust);
  1811. if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  1812. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  1813. fp->curr_clust = clst; /* Update current cluster */
  1814. }
  1815. sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */
  1816. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  1817. sect += csect;
  1818. cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */
  1819. if (cc) { /* Read maximum contiguous sectors directly */
  1820. if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  1821. cc = fp->fs->csize - csect;
  1822. /* XXX OFFLOAD GOES HERE */
  1823. if (ff_sd_offload) {
  1824. sd_offload = 1;
  1825. }
  1826. if (disk_read(fp->fs->drv, rbuff, sect, (BYTE)cc) != RES_OK)
  1827. ABORT(fp->fs, FR_DISK_ERR);
  1828. sd_offload = 0;
  1829. #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  1830. #if _FS_TINY
  1831. if (fp->fs->wflag && fp->fs->winsect - sect < cc)
  1832. mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));
  1833. #else
  1834. if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc){
  1835. mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs)); uart_putc('Y');}
  1836. #endif
  1837. #endif
  1838. rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  1839. continue;
  1840. }
  1841. #if !_FS_TINY
  1842. #if !_FS_READONLY
  1843. if (fp->flag & FA__DIRTY) { /* Write sector I/O buffer if needed */
  1844. printf("DIRTY!?!\n");
  1845. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  1846. ABORT(fp->fs, FR_DISK_ERR);
  1847. fp->flag &= ~FA__DIRTY;
  1848. }
  1849. #endif
  1850. if (fp->dsect != sect) { /* Fill sector buffer with file data */
  1851. if(!ff_sd_offload) {
  1852. if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)
  1853. ABORT(fp->fs, FR_DISK_ERR);
  1854. }
  1855. }
  1856. #endif
  1857. fp->dsect = sect;
  1858. }
  1859. rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */
  1860. if (rcnt > btr) rcnt = btr;
  1861. if(!ff_sd_offload) {
  1862. #if _FS_TINY
  1863. if (move_window(fp->fs, fp->dsect)) /* Move sector window */
  1864. ABORT(fp->fs, FR_DISK_ERR);
  1865. mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  1866. #else
  1867. mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  1868. printf("final mem_cpy, rcnt=%d, rbuff-buff=%d\n", rcnt, (void*)rbuff-buff);
  1869. } else {
  1870. sd_offload_partial_start = fp->fptr % SS(fp->fs);
  1871. sd_offload_partial_end = sd_offload_partial_start + rcnt;
  1872. // printf("partial dma. sect=%08lx start=%d end=%d\n", fp->dsect, sd_offload_partial_start, sd_offload_partial_end);
  1873. /* set start + end */
  1874. sd_offload = 1;
  1875. sd_offload_partial = 1;
  1876. if(disk_read(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK) {
  1877. sd_offload = 0;
  1878. ABORT(fp->fs, FR_DISK_ERR);
  1879. }
  1880. sd_offload = 0;
  1881. #endif
  1882. }
  1883. }
  1884. ff_sd_offload = 0;
  1885. LEAVE_FF(fp->fs, FR_OK);
  1886. }
  1887. #if !_FS_READONLY
  1888. /*-----------------------------------------------------------------------*/
  1889. /* Write File */
  1890. /*-----------------------------------------------------------------------*/
  1891. FRESULT f_write (
  1892. FIL *fp, /* Pointer to the file object */
  1893. const void *buff, /* Pointer to the data to be written */
  1894. UINT btw, /* Number of bytes to write */
  1895. UINT *bw /* Pointer to number of bytes written */
  1896. )
  1897. {
  1898. FRESULT res;
  1899. DWORD clst, sect;
  1900. UINT wcnt, cc;
  1901. const BYTE *wbuff = buff;
  1902. BYTE csect;
  1903. *bw = 0; /* Initialize byte counter */
  1904. res = validate(fp->fs, fp->id); /* Check validity of the object */
  1905. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  1906. if (fp->flag & FA__ERROR) /* Check abort flag */
  1907. LEAVE_FF(fp->fs, FR_INT_ERR);
  1908. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  1909. LEAVE_FF(fp->fs, FR_DENIED);
  1910. if (fp->fsize + btw < fp->fsize) btw = 0; /* File size cannot reach 4GB */
  1911. for ( ; btw; /* Repeat until all data transferred */
  1912. wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
  1913. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  1914. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  1915. if (!csect) { /* On the cluster boundary? */
  1916. if (fp->fptr == 0) { /* On the top of the file? */
  1917. clst = fp->org_clust; /* Follow from the origin */
  1918. if (clst == 0) /* When there is no cluster chain, */
  1919. fp->org_clust = clst = create_chain(fp->fs, 0); /* Create a new cluster chain */
  1920. } else { /* Middle or end of the file */
  1921. clst = create_chain(fp->fs, fp->curr_clust); /* Follow or stretch cluster chain */
  1922. }
  1923. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  1924. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  1925. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  1926. fp->curr_clust = clst; /* Update current cluster */
  1927. }
  1928. #if _FS_TINY
  1929. if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0)) /* Write back data buffer prior to following direct transfer */
  1930. ABORT(fp->fs, FR_DISK_ERR);
  1931. #else
  1932. if (fp->flag & FA__DIRTY) { /* Write back data buffer prior to following direct transfer */
  1933. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  1934. ABORT(fp->fs, FR_DISK_ERR);
  1935. fp->flag &= ~FA__DIRTY;
  1936. }
  1937. #endif
  1938. sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */
  1939. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  1940. sect += csect;
  1941. cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */
  1942. if (cc) { /* Write maximum contiguous sectors directly */
  1943. if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  1944. cc = fp->fs->csize - csect;
  1945. if (disk_write(fp->fs->drv, wbuff, sect, (BYTE)cc) != RES_OK)
  1946. ABORT(fp->fs, FR_DISK_ERR);
  1947. #if _FS_TINY
  1948. if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets dirty by the direct write */
  1949. mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));
  1950. fp->fs->wflag = 0;
  1951. }
  1952. #else
  1953. if (fp->dsect - sect < cc) { /* Refill sector cache if it gets dirty by the direct write */
  1954. mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
  1955. fp->flag &= ~FA__DIRTY;
  1956. }
  1957. #endif
  1958. wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  1959. continue;
  1960. }
  1961. #if _FS_TINY
  1962. if (fp->fptr >= fp->fsize) { /* Avoid silly buffer filling at growing edge */
  1963. if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);
  1964. fp->fs->winsect = sect;
  1965. }
  1966. #else
  1967. if (fp->dsect != sect) { /* Fill sector buffer with file data */
  1968. if (fp->fptr < fp->fsize &&
  1969. disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)
  1970. ABORT(fp->fs, FR_DISK_ERR);
  1971. }
  1972. #endif
  1973. fp->dsect = sect;
  1974. }
  1975. wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));/* Put partial sector into file I/O buffer */
  1976. if (wcnt > btw) wcnt = btw;
  1977. #if _FS_TINY
  1978. if (move_window(fp->fs, fp->dsect)) /* Move sector window */
  1979. ABORT(fp->fs, FR_DISK_ERR);
  1980. mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  1981. fp->fs->wflag = 1;
  1982. #else
  1983. mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  1984. fp->flag |= FA__DIRTY;
  1985. #endif
  1986. }
  1987. if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
  1988. fp->flag |= FA__WRITTEN; /* Set file change flag */
  1989. LEAVE_FF(fp->fs, FR_OK);
  1990. }
  1991. /*-----------------------------------------------------------------------*/
  1992. /* Synchronize the File Object */
  1993. /*-----------------------------------------------------------------------*/
  1994. FRESULT f_sync (
  1995. FIL *fp /* Pointer to the file object */
  1996. )
  1997. {
  1998. FRESULT res;
  1999. DWORD tim;
  2000. BYTE *dir;
  2001. res = validate(fp->fs, fp->id); /* Check validity of the object */
  2002. if (res == FR_OK) {
  2003. if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
  2004. printf("DIRTY?!?!?!\n");
  2005. #if !_FS_TINY /* Write-back dirty buffer */
  2006. if (fp->flag & FA__DIRTY) {
  2007. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2008. LEAVE_FF(fp->fs, FR_DISK_ERR);
  2009. fp->flag &= ~FA__DIRTY;
  2010. }
  2011. #endif
  2012. /* Update the directory entry */
  2013. res = move_window(fp->fs, fp->dir_sect);
  2014. if (res == FR_OK) {
  2015. dir = fp->dir_ptr;
  2016. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  2017. ST_DWORD(dir+DIR_FileSize, fp->fsize); /* Update file size */
  2018. ST_CLUST(dir, fp->org_clust); /* Update start cluster */
  2019. tim = get_fattime(); /* Update updated time */
  2020. ST_DWORD(dir+DIR_WrtTime, tim);
  2021. fp->flag &= ~FA__WRITTEN;
  2022. fp->fs->wflag = 1;
  2023. res = sync(fp->fs);
  2024. }
  2025. }
  2026. }
  2027. LEAVE_FF(fp->fs, res);
  2028. }
  2029. #endif /* !_FS_READONLY */
  2030. /*-----------------------------------------------------------------------*/
  2031. /* Close File */
  2032. /*-----------------------------------------------------------------------*/
  2033. FRESULT f_close (
  2034. FIL *fp /* Pointer to the file object to be closed */
  2035. )
  2036. {
  2037. FRESULT res;
  2038. #if _FS_READONLY
  2039. FATFS *fs = fp->fs;
  2040. res = validate(fs, fp->id);
  2041. if (res == FR_OK) fp->fs = 0; /* Discard file object */
  2042. LEAVE_FF(fs, res);
  2043. #else
  2044. res = f_sync(fp); /* Flush cached data */
  2045. #if _FS_SHARE
  2046. if (res == FR_OK) { /* Decrement open counter */
  2047. #if _FS_REENTRANT
  2048. res = validate(fp->fs, fp->id);
  2049. if (res == FR_OK) {
  2050. res = dec_lock(fp->lockid);
  2051. unlock_fs(fp->fs, FR_OK);
  2052. }
  2053. #else
  2054. res = dec_lock(fp->lockid);
  2055. #endif
  2056. }
  2057. #endif
  2058. if (res == FR_OK) fp->fs = 0; /* Discard file object */
  2059. return res;
  2060. #endif
  2061. }
  2062. /*-----------------------------------------------------------------------*/
  2063. /* Current Drive/Directory Handlings */
  2064. /*-----------------------------------------------------------------------*/
  2065. #if _FS_RPATH >= 1
  2066. FRESULT f_chdrive (
  2067. BYTE drv /* Drive number */
  2068. )
  2069. {
  2070. if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
  2071. CurrVol = drv;
  2072. return FR_OK;
  2073. }
  2074. FRESULT f_chdir (
  2075. const TCHAR *path /* Pointer to the directory path */
  2076. )
  2077. {
  2078. FRESULT res;
  2079. DIR dj;
  2080. DEF_NAMEBUF;
  2081. res = chk_mounted(&path, &dj.fs, 0);
  2082. if (res == FR_OK) {
  2083. INIT_BUF(dj);
  2084. res = follow_path(&dj, path); /* Follow the path */
  2085. FREE_BUF();
  2086. if (res == FR_OK) { /* Follow completed */
  2087. if (!dj.dir) {
  2088. dj.fs->cdir = dj.sclust; /* Start directory itself */
  2089. } else {
  2090. if (dj.dir[DIR_Attr] & AM_DIR) /* Reached to the directory */
  2091. dj.fs->cdir = LD_CLUST(dj.dir);
  2092. else
  2093. res = FR_NO_PATH; /* Reached but a file */
  2094. }
  2095. }
  2096. if (res == FR_NO_FILE) res = FR_NO_PATH;
  2097. }
  2098. LEAVE_FF(dj.fs, res);
  2099. }
  2100. #if _FS_RPATH >= 2
  2101. FRESULT f_getcwd (
  2102. TCHAR *path, /* Pointer to the directory path */
  2103. UINT sz_path /* Size of path */
  2104. )
  2105. {
  2106. FRESULT res;
  2107. DIR dj;
  2108. UINT i, n;
  2109. DWORD ccl;
  2110. TCHAR *tp;
  2111. FILINFO fno;
  2112. DEF_NAMEBUF;
  2113. *path = 0;
  2114. res = chk_mounted((const TCHAR**)&path, &dj.fs, 0); /* Get current volume */
  2115. if (res == FR_OK) {
  2116. INIT_BUF(dj);
  2117. i = sz_path; /* Bottom of buffer (dir stack base) */
  2118. dj.sclust = dj.fs->cdir; /* Start to follow upper dir from current dir */
  2119. while ((ccl = dj.sclust) != 0) { /* Repeat while current dir is a sub-dir */
  2120. res = dir_sdi(&dj, 1); /* Get parent dir */
  2121. if (res != FR_OK) break;
  2122. res = dir_read(&dj);
  2123. if (res != FR_OK) break;
  2124. dj.sclust = LD_CLUST(dj.dir); /* Goto parent dir */
  2125. res = dir_sdi(&dj, 0);
  2126. if (res != FR_OK) break;
  2127. do { /* Find the entry links to the child dir */
  2128. res = dir_read(&dj);
  2129. if (res != FR_OK) break;
  2130. if (ccl == LD_CLUST(dj.dir)) break; /* Found the entry */
  2131. res = dir_next(&dj, 0);
  2132. } while (res == FR_OK);
  2133. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  2134. if (res != FR_OK) break;
  2135. #if _USE_LFN
  2136. fno.lfname = path;
  2137. fno.lfsize = i;
  2138. #endif
  2139. get_fileinfo(&dj, &fno); /* Get the dir name and push it to the buffer */
  2140. tp = fno.fname;
  2141. if (_USE_LFN && *path) tp = path;
  2142. for (n = 0; tp[n]; n++) ;
  2143. if (i < n + 3) {
  2144. res = FR_NOT_ENOUGH_CORE; break;
  2145. }
  2146. while (n) path[--i] = tp[--n];
  2147. path[--i] = '/';
  2148. }
  2149. tp = path;
  2150. if (res == FR_OK) {
  2151. *tp++ = '0' + CurrVol; /* Put drive number */
  2152. *tp++ = ':';
  2153. if (i == sz_path) { /* Root-dir */
  2154. *tp++ = '/';
  2155. } else { /* Sub-dir */
  2156. do /* Add stacked path str */
  2157. *tp++ = path[i++];
  2158. while (i < sz_path);
  2159. }
  2160. }
  2161. *tp = 0;
  2162. FREE_BUF();
  2163. }
  2164. LEAVE_FF(dj.fs, res);
  2165. }
  2166. #endif /* _FS_RPATH >= 2 */
  2167. #endif /* _FS_RPATH >= 1 */
  2168. #if _FS_MINIMIZE <= 2
  2169. /*-----------------------------------------------------------------------*/
  2170. /* Seek File R/W Pointer */
  2171. /*-----------------------------------------------------------------------*/
  2172. FRESULT f_lseek (
  2173. FIL *fp, /* Pointer to the file object */
  2174. DWORD ofs /* File pointer from top of file */
  2175. )
  2176. {
  2177. FRESULT res;
  2178. res = validate(fp->fs, fp->id); /* Check validity of the object */
  2179. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2180. if (fp->flag & FA__ERROR) /* Check abort flag */
  2181. LEAVE_FF(fp->fs, FR_INT_ERR);
  2182. #if _USE_FASTSEEK
  2183. if (fp->cltbl) { /* Fast seek */
  2184. DWORD cl, pcl, ncl, tcl, dsc, tlen, *tbl = fp->cltbl;
  2185. BYTE csc;
  2186. tlen = *tbl++;
  2187. if (ofs == CREATE_LINKMAP) { /* Create link map table */
  2188. cl = fp->org_clust;
  2189. if (cl) {
  2190. do {
  2191. if (tlen < 4) { /* Not enough table items */
  2192. res = FR_NOT_ENOUGH_CORE; break;
  2193. }
  2194. tcl = cl; ncl = 0;
  2195. do { /* Get a fragment and store the top and length */
  2196. pcl = cl; ncl++;
  2197. cl = get_fat(fp->fs, cl);
  2198. if (cl <= 1) ABORT(fp->fs, FR_INT_ERR);
  2199. if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2200. } while (cl == pcl + 1);
  2201. *tbl++ = ncl; *tbl++ = tcl;
  2202. tlen -= 2;
  2203. } while (cl < fp->fs->n_fatent);
  2204. }
  2205. *tbl = 0; /* Terminate table */
  2206. } else { /* Fast seek */
  2207. if (ofs > fp->fsize) /* Clip offset at the file size */
  2208. ofs = fp->fsize;
  2209. fp->fptr = ofs; /* Set file pointer */
  2210. if (ofs) {
  2211. dsc = (ofs - 1) / SS(fp->fs);
  2212. cl = dsc / fp->fs->csize;
  2213. for (;;) {
  2214. ncl = *tbl++;
  2215. if (!ncl) ABORT(fp->fs, FR_INT_ERR);
  2216. if (cl < ncl) break;
  2217. cl -= ncl; tbl++;
  2218. }
  2219. fp->curr_clust = cl + *tbl;
  2220. csc = (BYTE)(dsc & (fp->fs->csize - 1));
  2221. dsc = clust2sect(fp->fs, fp->curr_clust);
  2222. if (!dsc) ABORT(fp->fs, FR_INT_ERR);
  2223. dsc += csc;
  2224. if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) {
  2225. #if !_FS_TINY
  2226. #if !_FS_READONLY
  2227. if (fp->flag & FA__DIRTY) { /* Flush dirty buffer if needed */
  2228. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2229. ABORT(fp->fs, FR_DISK_ERR);
  2230. fp->flag &= ~FA__DIRTY;
  2231. }
  2232. #endif
  2233. if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK)
  2234. ABORT(fp->fs, FR_DISK_ERR);
  2235. #endif
  2236. fp->dsect = dsc;
  2237. }
  2238. }
  2239. }
  2240. } else
  2241. #endif
  2242. /* Normal Seek */
  2243. {
  2244. DWORD clst, bcs, nsect, ifptr;
  2245. if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
  2246. #if !_FS_READONLY
  2247. && !(fp->flag & FA_WRITE)
  2248. #endif
  2249. ) ofs = fp->fsize;
  2250. ifptr = fp->fptr;
  2251. fp->fptr = nsect = 0;
  2252. if (ofs) {
  2253. bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */
  2254. if (ifptr > 0 &&
  2255. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  2256. fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */
  2257. ofs -= fp->fptr;
  2258. clst = fp->curr_clust;
  2259. } else { /* When seek to back cluster, */
  2260. clst = fp->org_clust; /* start from the first cluster */
  2261. #if !_FS_READONLY
  2262. if (clst == 0) { /* If no cluster chain, create a new chain */
  2263. clst = create_chain(fp->fs, 0);
  2264. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2265. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2266. fp->org_clust = clst;
  2267. }
  2268. #endif
  2269. fp->curr_clust = clst;
  2270. }
  2271. if (clst != 0) {
  2272. while (ofs > bcs) { /* Cluster following loop */
  2273. #if !_FS_READONLY
  2274. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  2275. clst = create_chain(fp->fs, clst); /* Force stretch if in write mode */
  2276. if (clst == 0) { /* When disk gets full, clip file size */
  2277. ofs = bcs; break;
  2278. }
  2279. } else
  2280. #endif
  2281. clst = get_fat(fp->fs, clst); /* Follow cluster chain if not in write mode */
  2282. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2283. if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR);
  2284. fp->curr_clust = clst;
  2285. fp->fptr += bcs;
  2286. ofs -= bcs;
  2287. }
  2288. fp->fptr += ofs;
  2289. if (ofs % SS(fp->fs)) {
  2290. nsect = clust2sect(fp->fs, clst); /* Current sector */
  2291. if (!nsect) ABORT(fp->fs, FR_INT_ERR);
  2292. nsect += ofs / SS(fp->fs);
  2293. }
  2294. }
  2295. }
  2296. if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {
  2297. #if !_FS_TINY
  2298. #if !_FS_READONLY
  2299. if (fp->flag & FA__DIRTY) { /* Flush dirty buffer if needed */
  2300. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2301. ABORT(fp->fs, FR_DISK_ERR);
  2302. fp->flag &= ~FA__DIRTY;
  2303. }
  2304. #endif
  2305. if(!ff_sd_offload) {
  2306. sd_offload_partial=0;
  2307. if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK)
  2308. ABORT(fp->fs, FR_DISK_ERR);
  2309. } else {
  2310. sd_offload_partial=1;
  2311. sd_offload_partial_start = fp->fptr % SS(fp->fs);
  2312. }
  2313. #endif
  2314. fp->dsect = nsect;
  2315. }
  2316. #if !_FS_READONLY
  2317. if (fp->fptr > fp->fsize) { /* Set change flag if the file size is extended */
  2318. fp->fsize = fp->fptr;
  2319. fp->flag |= FA__WRITTEN;
  2320. }
  2321. #endif
  2322. }
  2323. ff_sd_offload = 0;
  2324. LEAVE_FF(fp->fs, res);
  2325. }
  2326. #if _FS_MINIMIZE <= 1
  2327. /*-----------------------------------------------------------------------*/
  2328. /* Create a Directroy Object */
  2329. /*-----------------------------------------------------------------------*/
  2330. FRESULT f_opendir (
  2331. DIR *dj, /* Pointer to directory object to create */
  2332. const TCHAR *path /* Pointer to the directory path */
  2333. )
  2334. {
  2335. FRESULT res;
  2336. DEF_NAMEBUF;
  2337. res = chk_mounted(&path, &dj->fs, 0);
  2338. if (res == FR_OK) {
  2339. INIT_BUF(*dj);
  2340. res = follow_path(dj, path); /* Follow the path to the directory */
  2341. FREE_BUF();
  2342. if (res == FR_OK) { /* Follow completed */
  2343. if (dj->dir) { /* It is not the root dir */
  2344. if (dj->dir[DIR_Attr] & AM_DIR) { /* The object is a directory */
  2345. dj->sclust = LD_CLUST(dj->dir);
  2346. } else { /* The object is not a directory */
  2347. res = FR_NO_PATH;
  2348. }
  2349. }
  2350. if (res == FR_OK) {
  2351. dj->id = dj->fs->id;
  2352. res = dir_sdi(dj, 0); /* Rewind dir */
  2353. }
  2354. }
  2355. if (res == FR_NO_FILE) res = FR_NO_PATH;
  2356. }
  2357. LEAVE_FF(dj->fs, res);
  2358. }
  2359. /*-----------------------------------------------------------------------*/
  2360. /* Read Directory Entry in Sequense */
  2361. /*-----------------------------------------------------------------------*/
  2362. FRESULT f_readdir (
  2363. DIR *dj, /* Pointer to the open directory object */
  2364. FILINFO *fno /* Pointer to file information to return */
  2365. )
  2366. {
  2367. FRESULT res;
  2368. DEF_NAMEBUF;
  2369. res = validate(dj->fs, dj->id); /* Check validity of the object */
  2370. if (res == FR_OK) {
  2371. if (!fno) {
  2372. res = dir_sdi(dj, 0); /* Rewind the directory object */
  2373. } else {
  2374. INIT_BUF(*dj);
  2375. res = dir_read(dj); /* Read an directory item */
  2376. if (res == FR_NO_FILE) { /* Reached end of dir */
  2377. dj->sect = 0;
  2378. res = FR_OK;
  2379. }
  2380. if (res == FR_OK) { /* A valid entry is found */
  2381. get_fileinfo(dj, fno); /* Get the object information */
  2382. res = dir_next(dj, 0); /* Increment index for next */
  2383. if (res == FR_NO_FILE) {
  2384. dj->sect = 0;
  2385. res = FR_OK;
  2386. }
  2387. }
  2388. FREE_BUF();
  2389. }
  2390. }
  2391. LEAVE_FF(dj->fs, res);
  2392. }
  2393. #if _FS_MINIMIZE == 0
  2394. /*-----------------------------------------------------------------------*/
  2395. /* Get File Status */
  2396. /*-----------------------------------------------------------------------*/
  2397. FRESULT f_stat (
  2398. const TCHAR *path, /* Pointer to the file path */
  2399. FILINFO *fno /* Pointer to file information to return */
  2400. )
  2401. {
  2402. FRESULT res;
  2403. DIR dj;
  2404. DEF_NAMEBUF;
  2405. res = chk_mounted(&path, &dj.fs, 0);
  2406. if (res == FR_OK) {
  2407. INIT_BUF(dj);
  2408. res = follow_path(&dj, path); /* Follow the file path */
  2409. if (res == FR_OK) { /* Follow completed */
  2410. if (dj.dir) /* Found an object */
  2411. get_fileinfo(&dj, fno);
  2412. else /* It is root dir */
  2413. res = FR_INVALID_NAME;
  2414. }
  2415. FREE_BUF();
  2416. }
  2417. LEAVE_FF(dj.fs, res);
  2418. }
  2419. FRESULT l_openfilebycluster (
  2420. FATFS *fs, /* Pointer to file system object */
  2421. FIL *fp, /* Pointer to the blank file object */
  2422. const TCHAR *path,
  2423. DWORD clust, /* Cluster number to be opened */
  2424. DWORD fsize /* File size to be assumed */
  2425. )
  2426. {
  2427. chk_mounted(&path, &fs, 0);
  2428. fp->flag = FA_READ;
  2429. fp->org_clust = clust;
  2430. fp->fsize = fsize;
  2431. fp->fptr = 0;
  2432. fp->dsect = 0;
  2433. fp->fs = fs;
  2434. return FR_OK;
  2435. }
  2436. #if !_FS_READONLY
  2437. /*-----------------------------------------------------------------------*/
  2438. /* Get Number of Free Clusters */
  2439. /*-----------------------------------------------------------------------*/
  2440. FRESULT f_getfree (
  2441. const TCHAR *path, /* Pointer to the logical drive number (root dir) */
  2442. DWORD *nclst, /* Pointer to the variable to return number of free clusters */
  2443. FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */
  2444. )
  2445. {
  2446. FRESULT res;
  2447. DWORD n, clst, sect, stat;
  2448. UINT i;
  2449. BYTE fat, *p;
  2450. /* Get drive number */
  2451. res = chk_mounted(&path, fatfs, 0);
  2452. if (res == FR_OK) {
  2453. /* If free_clust is valid, return it without full cluster scan */
  2454. if ((*fatfs)->free_clust <= (*fatfs)->n_fatent - 2) {
  2455. *nclst = (*fatfs)->free_clust;
  2456. } else {
  2457. /* Get number of free clusters */
  2458. fat = (*fatfs)->fs_type;
  2459. n = 0;
  2460. if (fat == FS_FAT12) {
  2461. clst = 2;
  2462. do {
  2463. stat = get_fat(*fatfs, clst);
  2464. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  2465. if (stat == 1) { res = FR_INT_ERR; break; }
  2466. if (stat == 0) n++;
  2467. } while (++clst < (*fatfs)->n_fatent);
  2468. } else {
  2469. clst = (*fatfs)->n_fatent;
  2470. sect = (*fatfs)->fatbase;
  2471. i = 0; p = 0;
  2472. do {
  2473. if (!i) {
  2474. res = move_window(*fatfs, sect++);
  2475. if (res != FR_OK) break;
  2476. p = (*fatfs)->win;
  2477. i = SS(*fatfs);
  2478. }
  2479. if (fat == FS_FAT16) {
  2480. if (LD_WORD(p) == 0) n++;
  2481. p += 2; i -= 2;
  2482. } else {
  2483. if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;
  2484. p += 4; i -= 4;
  2485. }
  2486. } while (--clst);
  2487. }
  2488. (*fatfs)->free_clust = n;
  2489. if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
  2490. *nclst = n;
  2491. }
  2492. }
  2493. LEAVE_FF(*fatfs, res);
  2494. }
  2495. /*-----------------------------------------------------------------------*/
  2496. /* Truncate File */
  2497. /*-----------------------------------------------------------------------*/
  2498. FRESULT f_truncate (
  2499. FIL *fp /* Pointer to the file object */
  2500. )
  2501. {
  2502. FRESULT res;
  2503. DWORD ncl;
  2504. res = validate(fp->fs, fp->id); /* Check validity of the object */
  2505. if (res == FR_OK) {
  2506. if (fp->flag & FA__ERROR) { /* Check abort flag */
  2507. res = FR_INT_ERR;
  2508. } else {
  2509. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  2510. res = FR_DENIED;
  2511. }
  2512. }
  2513. if (res == FR_OK) {
  2514. if (fp->fsize > fp->fptr) {
  2515. fp->fsize = fp->fptr; /* Set file size to current R/W point */
  2516. fp->flag |= FA__WRITTEN;
  2517. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  2518. res = remove_chain(fp->fs, fp->org_clust);
  2519. fp->org_clust = 0;
  2520. } else { /* When truncate a part of the file, remove remaining clusters */
  2521. ncl = get_fat(fp->fs, fp->curr_clust);
  2522. res = FR_OK;
  2523. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  2524. if (ncl == 1) res = FR_INT_ERR;
  2525. if (res == FR_OK && ncl < fp->fs->n_fatent) {
  2526. res = put_fat(fp->fs, fp->curr_clust, 0x0FFFFFFF);
  2527. if (res == FR_OK) res = remove_chain(fp->fs, ncl);
  2528. }
  2529. }
  2530. }
  2531. if (res != FR_OK) fp->flag |= FA__ERROR;
  2532. }
  2533. LEAVE_FF(fp->fs, res);
  2534. }
  2535. /*-----------------------------------------------------------------------*/
  2536. /* Delete a File or Directory */
  2537. /*-----------------------------------------------------------------------*/
  2538. FRESULT f_unlink (
  2539. const TCHAR *path /* Pointer to the file or directory path */
  2540. )
  2541. {
  2542. FRESULT res;
  2543. DIR dj, sdj;
  2544. BYTE *dir;
  2545. DWORD dclst;
  2546. DEF_NAMEBUF;
  2547. res = chk_mounted(&path, &dj.fs, 1);
  2548. if (res == FR_OK) {
  2549. INIT_BUF(dj);
  2550. res = follow_path(&dj, path); /* Follow the file path */
  2551. if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
  2552. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  2553. #if _FS_SHARE
  2554. if (res == FR_OK) res = chk_lock(&dj, 2); /* Cannot remove open file */
  2555. #endif
  2556. if (res == FR_OK) { /* The object is accessible */
  2557. dir = dj.dir;
  2558. if (!dir) {
  2559. res = FR_INVALID_NAME; /* Cannot remove the start directory */
  2560. } else {
  2561. if (dir[DIR_Attr] & AM_RDO)
  2562. res = FR_DENIED; /* Cannot remove R/O object */
  2563. }
  2564. dclst = LD_CLUST(dir);
  2565. if (res == FR_OK && (dir[DIR_Attr] & AM_DIR)) { /* Is it a sub-dir? */
  2566. if (dclst < 2) {
  2567. res = FR_INT_ERR;
  2568. } else {
  2569. mem_cpy(&sdj, &dj, sizeof(DIR)); /* Check if the sub-dir is empty or not */
  2570. sdj.sclust = dclst;
  2571. res = dir_sdi(&sdj, 2); /* Exclude dot entries */
  2572. if (res == FR_OK) {
  2573. res = dir_read(&sdj);
  2574. if (res == FR_OK /* Not empty dir */
  2575. #if _FS_RPATH
  2576. || dclst == sdj.fs->cdir /* Current dir */
  2577. #endif
  2578. ) res = FR_DENIED;
  2579. if (res == FR_NO_FILE) res = FR_OK; /* Empty */
  2580. }
  2581. }
  2582. }
  2583. if (res == FR_OK) {
  2584. res = dir_remove(&dj); /* Remove the directory entry */
  2585. if (res == FR_OK) {
  2586. if (dclst) /* Remove the cluster chain if exist */
  2587. res = remove_chain(dj.fs, dclst);
  2588. if (res == FR_OK) res = sync(dj.fs);
  2589. }
  2590. }
  2591. }
  2592. FREE_BUF();
  2593. }
  2594. LEAVE_FF(dj.fs, res);
  2595. }
  2596. /*-----------------------------------------------------------------------*/
  2597. /* Create a Directory */
  2598. /*-----------------------------------------------------------------------*/
  2599. FRESULT f_mkdir (
  2600. const TCHAR *path /* Pointer to the directory path */
  2601. )
  2602. {
  2603. FRESULT res;
  2604. DIR dj;
  2605. BYTE *dir, n;
  2606. DWORD dsc, dcl, pcl, tim = get_fattime();
  2607. DEF_NAMEBUF;
  2608. res = chk_mounted(&path, &dj.fs, 1);
  2609. if (res == FR_OK) {
  2610. INIT_BUF(dj);
  2611. res = follow_path(&dj, path); /* Follow the file path */
  2612. if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
  2613. if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NS] & NS_DOT))
  2614. res = FR_INVALID_NAME;
  2615. if (res == FR_NO_FILE) { /* Can create a new directory */
  2616. dcl = create_chain(dj.fs, 0); /* Allocate a cluster for the new directory table */
  2617. res = FR_OK;
  2618. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
  2619. if (dcl == 1) res = FR_INT_ERR;
  2620. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  2621. if (res == FR_OK) /* Flush FAT */
  2622. res = move_window(dj.fs, 0);
  2623. if (res == FR_OK) { /* Initialize the new directory table */
  2624. dsc = clust2sect(dj.fs, dcl);
  2625. dir = dj.fs->win;
  2626. mem_set(dir, 0, SS(dj.fs));
  2627. mem_set(dir+DIR_Name, ' ', 8+3); /* Create "." entry */
  2628. dir[DIR_Name] = '.';
  2629. dir[DIR_Attr] = AM_DIR;
  2630. ST_DWORD(dir+DIR_WrtTime, tim);
  2631. ST_CLUST(dir, dcl);
  2632. mem_cpy(dir+32, dir, 32); /* Create ".." entry */
  2633. dir[33] = '.'; pcl = dj.sclust;
  2634. if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase)
  2635. pcl = 0;
  2636. ST_CLUST(dir+32, pcl);
  2637. for (n = dj.fs->csize; n; n--) { /* Write dot entries and clear following sectors */
  2638. dj.fs->winsect = dsc++;
  2639. dj.fs->wflag = 1;
  2640. res = move_window(dj.fs, 0);
  2641. if (res != FR_OK) break;
  2642. mem_set(dir, 0, SS(dj.fs));
  2643. }
  2644. }
  2645. if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
  2646. if (res != FR_OK) {
  2647. remove_chain(dj.fs, dcl); /* Could not register, remove cluster chain */
  2648. } else {
  2649. dir = dj.dir;
  2650. dir[DIR_Attr] = AM_DIR; /* Attribute */
  2651. ST_DWORD(dir+DIR_WrtTime, tim); /* Created time */
  2652. ST_CLUST(dir, dcl); /* Table start cluster */
  2653. dj.fs->wflag = 1;
  2654. res = sync(dj.fs);
  2655. }
  2656. }
  2657. FREE_BUF();
  2658. }
  2659. LEAVE_FF(dj.fs, res);
  2660. }
  2661. /*-----------------------------------------------------------------------*/
  2662. /* Change Attribute */
  2663. /*-----------------------------------------------------------------------*/
  2664. FRESULT f_chmod (
  2665. const TCHAR *path, /* Pointer to the file path */
  2666. BYTE value, /* Attribute bits */
  2667. BYTE mask /* Attribute mask to change */
  2668. )
  2669. {
  2670. FRESULT res;
  2671. DIR dj;
  2672. BYTE *dir;
  2673. DEF_NAMEBUF;
  2674. res = chk_mounted(&path, &dj.fs, 1);
  2675. if (res == FR_OK) {
  2676. INIT_BUF(dj);
  2677. res = follow_path(&dj, path); /* Follow the file path */
  2678. FREE_BUF();
  2679. if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
  2680. res = FR_INVALID_NAME;
  2681. if (res == FR_OK) {
  2682. dir = dj.dir;
  2683. if (!dir) { /* Is it a root directory? */
  2684. res = FR_INVALID_NAME;
  2685. } else { /* File or sub directory */
  2686. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  2687. dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  2688. dj.fs->wflag = 1;
  2689. res = sync(dj.fs);
  2690. }
  2691. }
  2692. }
  2693. LEAVE_FF(dj.fs, res);
  2694. }
  2695. /*-----------------------------------------------------------------------*/
  2696. /* Change Timestamp */
  2697. /*-----------------------------------------------------------------------*/
  2698. FRESULT f_utime (
  2699. const TCHAR *path, /* Pointer to the file/directory name */
  2700. const FILINFO *fno /* Pointer to the time stamp to be set */
  2701. )
  2702. {
  2703. FRESULT res;
  2704. DIR dj;
  2705. BYTE *dir;
  2706. DEF_NAMEBUF;
  2707. res = chk_mounted(&path, &dj.fs, 1);
  2708. if (res == FR_OK) {
  2709. INIT_BUF(dj);
  2710. res = follow_path(&dj, path); /* Follow the file path */
  2711. FREE_BUF();
  2712. if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
  2713. res = FR_INVALID_NAME;
  2714. if (res == FR_OK) {
  2715. dir = dj.dir;
  2716. if (!dir) { /* Root directory */
  2717. res = FR_INVALID_NAME;
  2718. } else { /* File or sub-directory */
  2719. ST_WORD(dir+DIR_WrtTime, fno->ftime);
  2720. ST_WORD(dir+DIR_WrtDate, fno->fdate);
  2721. dj.fs->wflag = 1;
  2722. res = sync(dj.fs);
  2723. }
  2724. }
  2725. }
  2726. LEAVE_FF(dj.fs, res);
  2727. }
  2728. /*-----------------------------------------------------------------------*/
  2729. /* Rename File/Directory */
  2730. /*-----------------------------------------------------------------------*/
  2731. FRESULT f_rename (
  2732. const TCHAR *path_old, /* Pointer to the old name */
  2733. const TCHAR *path_new /* Pointer to the new name */
  2734. )
  2735. {
  2736. FRESULT res;
  2737. DIR djo, djn;
  2738. BYTE buf[21], *dir;
  2739. DWORD dw;
  2740. DEF_NAMEBUF;
  2741. res = chk_mounted(&path_old, &djo.fs, 1);
  2742. if (res == FR_OK) {
  2743. djn.fs = djo.fs;
  2744. INIT_BUF(djo);
  2745. res = follow_path(&djo, path_old); /* Check old object */
  2746. if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
  2747. res = FR_INVALID_NAME;
  2748. #if _FS_SHARE
  2749. if (res == FR_OK) res = chk_lock(&djo, 2);
  2750. #endif
  2751. if (res == FR_OK) { /* Old object is found */
  2752. if (!djo.dir) { /* Is root dir? */
  2753. res = FR_NO_FILE;
  2754. } else {
  2755. mem_cpy(buf, djo.dir+DIR_Attr, 21); /* Save the object information except for name */
  2756. mem_cpy(&djn, &djo, sizeof(DIR)); /* Check new object */
  2757. res = follow_path(&djn, path_new);
  2758. if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */
  2759. if (res == FR_NO_FILE) { /* Is it a valid path and no name collision? */
  2760. /* Start critical section that any interruption or error can cause cross-link */
  2761. res = dir_register(&djn); /* Register the new entry */
  2762. if (res == FR_OK) {
  2763. dir = djn.dir; /* Copy object information except for name */
  2764. mem_cpy(dir+13, buf+2, 19);
  2765. dir[DIR_Attr] = buf[0] | AM_ARC;
  2766. djo.fs->wflag = 1;
  2767. if (djo.sclust != djn.sclust && (dir[DIR_Attr] & AM_DIR)) { /* Update .. entry in the directory if needed */
  2768. dw = clust2sect(djn.fs, LD_CLUST(dir));
  2769. if (!dw) {
  2770. res = FR_INT_ERR;
  2771. } else {
  2772. res = move_window(djn.fs, dw);
  2773. dir = djn.fs->win+32; /* .. entry */
  2774. if (res == FR_OK && dir[1] == '.') {
  2775. dw = (djn.fs->fs_type == FS_FAT32 && djn.sclust == djn.fs->dirbase) ? 0 : djn.sclust;
  2776. ST_CLUST(dir, dw);
  2777. djn.fs->wflag = 1;
  2778. }
  2779. }
  2780. }
  2781. if (res == FR_OK) {
  2782. res = dir_remove(&djo); /* Remove old entry */
  2783. if (res == FR_OK)
  2784. res = sync(djo.fs);
  2785. }
  2786. }
  2787. /* End critical section */
  2788. }
  2789. }
  2790. }
  2791. FREE_BUF();
  2792. }
  2793. LEAVE_FF(djo.fs, res);
  2794. }
  2795. #endif /* !_FS_READONLY */
  2796. #endif /* _FS_MINIMIZE == 0 */
  2797. #endif /* _FS_MINIMIZE <= 1 */
  2798. #endif /* _FS_MINIMIZE <= 2 */
  2799. /*-----------------------------------------------------------------------*/
  2800. /* Forward data to the stream directly (available on only tiny cfg) */
  2801. /*-----------------------------------------------------------------------*/
  2802. #if _USE_FORWARD && _FS_TINY
  2803. FRESULT f_forward (
  2804. FIL *fp, /* Pointer to the file object */
  2805. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  2806. UINT btr, /* Number of bytes to forward */
  2807. UINT *bf /* Pointer to number of bytes forwarded */
  2808. )
  2809. {
  2810. FRESULT res;
  2811. DWORD remain, clst, sect;
  2812. UINT rcnt;
  2813. BYTE csect;
  2814. *bf = 0; /* Initialize byte counter */
  2815. res = validate(fp->fs, fp->id); /* Check validity of the object */
  2816. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2817. if (fp->flag & FA__ERROR) /* Check error flag */
  2818. LEAVE_FF(fp->fs, FR_INT_ERR);
  2819. if (!(fp->flag & FA_READ)) /* Check access mode */
  2820. LEAVE_FF(fp->fs, FR_DENIED);
  2821. remain = fp->fsize - fp->fptr;
  2822. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2823. for ( ; btr && (*func)(0, 0); /* Repeat until all data transferred or stream becomes busy */
  2824. fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {
  2825. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  2826. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  2827. if (!csect) { /* On the cluster boundary? */
  2828. clst = (fp->fptr == 0) ? /* On the top of the file? */
  2829. fp->org_clust : get_fat(fp->fs, fp->curr_clust);
  2830. if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  2831. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2832. fp->curr_clust = clst; /* Update current cluster */
  2833. }
  2834. }
  2835. sect = clust2sect(fp->fs, fp->curr_clust); /* Get current data sector */
  2836. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2837. sect += csect;
  2838. if (move_window(fp->fs, sect)) /* Move sector window */
  2839. ABORT(fp->fs, FR_DISK_ERR);
  2840. fp->dsect = sect;
  2841. rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */
  2842. if (rcnt > btr) rcnt = btr;
  2843. rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
  2844. if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
  2845. }
  2846. LEAVE_FF(fp->fs, FR_OK);
  2847. }
  2848. #endif /* _USE_FORWARD */
  2849. #if _USE_MKFS && !_FS_READONLY
  2850. /*-----------------------------------------------------------------------*/
  2851. /* Create File System on the Drive */
  2852. /*-----------------------------------------------------------------------*/
  2853. #define N_ROOTDIR 512 /* Multiple of 32 */
  2854. #define N_FATS 1 /* 1 or 2 */
  2855. FRESULT f_mkfs (
  2856. BYTE drv, /* Logical drive number */
  2857. BYTE sfd, /* Partitioning rule 0:FDISK, 1:SFD */
  2858. UINT au /* Allocation unit size [bytes] */
  2859. )
  2860. {
  2861. static const WORD vst[] = { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0};
  2862. static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
  2863. BYTE fmt, md, *tbl;
  2864. DWORD n_clst, vs, n, wsect;
  2865. UINT i;
  2866. DWORD b_vol, b_fat, b_dir, b_data; /* Offset (LBA) */
  2867. DWORD n_vol, n_rsv, n_fat, n_dir; /* Size */
  2868. FATFS *fs;
  2869. DSTATUS stat;
  2870. /* Check mounted drive and clear work area */
  2871. if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
  2872. fs = FatFs[drv];
  2873. if (!fs) return FR_NOT_ENABLED;
  2874. fs->fs_type = 0;
  2875. drv = LD2PD(drv);
  2876. /* Get disk statics */
  2877. stat = disk_initialize(drv);
  2878. if (stat & STA_NOINIT) return FR_NOT_READY;
  2879. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  2880. #if _MAX_SS != 512 /* Get disk sector size */
  2881. if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK)
  2882. return FR_DISK_ERR;
  2883. #endif
  2884. if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128)
  2885. return FR_DISK_ERR;
  2886. b_vol = (sfd) ? 0 : 63; /* Volume start sector */
  2887. n_vol -= b_vol;
  2888. if (au & (au - 1)) au = 0; /* Check validity of the allocation unit size */
  2889. if (!au) { /* AU auto selection */
  2890. vs = n_vol / (2000 / (SS(fs) / 512));
  2891. for (i = 0; vs < vst[i]; i++) ;
  2892. au = cst[i];
  2893. }
  2894. au /= SS(fs); /* Number of sectors per cluster */
  2895. if (au == 0) au = 1;
  2896. if (au > 128) au = 128;
  2897. /* Pre-compute number of clusters and FAT syb-type */
  2898. n_clst = n_vol / au;
  2899. fmt = FS_FAT12;
  2900. if (n_clst >= MIN_FAT16) fmt = FS_FAT16;
  2901. if (n_clst >= MIN_FAT32) fmt = FS_FAT32;
  2902. /* Determine offset and size of FAT structure */
  2903. if (fmt == FS_FAT32) {
  2904. n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
  2905. n_rsv = 32;
  2906. n_dir = 0;
  2907. } else {
  2908. n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4;
  2909. n_fat = (n_fat + SS(fs) - 1) / SS(fs);
  2910. n_rsv = 1;
  2911. n_dir = N_ROOTDIR * 32UL / SS(fs);
  2912. }
  2913. b_fat = b_vol + n_rsv; /* FAT area start sector */
  2914. b_dir = b_fat + n_fat * N_FATS; /* Directory area start sector */
  2915. b_data = b_dir + n_dir; /* Data area start sector */
  2916. if (n_vol < b_data + au) return FR_MKFS_ABORTED; /* Too small volume */
  2917. /* Align data start sector to erase block boundary (for flash memory media) */
  2918. if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;
  2919. n = (b_data + n - 1) & ~(n - 1); /* Next nearest erase block from current data start */
  2920. n = (n - b_data) / N_FATS;
  2921. if (fmt == FS_FAT32) { /* FAT32: Move FAT offset */
  2922. n_rsv += n;
  2923. b_fat += n;
  2924. } else { /* FAT12/16: Expand FAT size */
  2925. n_fat += n;
  2926. }
  2927. /* Determine number of cluster and final check of validity of the FAT sub-type */
  2928. n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au;
  2929. if ( (fmt == FS_FAT16 && n_clst < MIN_FAT16)
  2930. || (fmt == FS_FAT32 && n_clst < MIN_FAT32))
  2931. return FR_MKFS_ABORTED;
  2932. /* Create partition table if required */
  2933. if (sfd) {
  2934. md = 0xF0;
  2935. } else {
  2936. DWORD n_disk = b_vol + n_vol;
  2937. mem_set(fs->win, 0, SS(fs));
  2938. tbl = fs->win+MBR_Table;
  2939. ST_DWORD(tbl, 0x00010180); /* Partition start in CHS */
  2940. if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */
  2941. n_disk = n_disk / 63 / 255;
  2942. tbl[7] = (BYTE)n_disk;
  2943. tbl[6] = (BYTE)((n_disk >> 2) | 63);
  2944. } else {
  2945. ST_WORD(&tbl[6], 0xFFFF);
  2946. }
  2947. tbl[5] = 254;
  2948. if (fmt != FS_FAT32) /* System ID */
  2949. tbl[4] = (n_vol < 0x10000) ? 0x04 : 0x06;
  2950. else
  2951. tbl[4] = 0x0c;
  2952. ST_DWORD(tbl+8, 63); /* Partition start in LBA */
  2953. ST_DWORD(tbl+12, n_vol); /* Partition size in LBA */
  2954. ST_WORD(tbl+64, 0xAA55); /* Signature */
  2955. if (disk_write(drv, fs->win, 0, 1) != RES_OK)
  2956. return FR_DISK_ERR;
  2957. md = 0xF8;
  2958. }
  2959. /* Create volume boot record */
  2960. tbl = fs->win; /* Clear sector */
  2961. mem_set(tbl, 0, SS(fs));
  2962. mem_cpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot code, OEM name */
  2963. i = SS(fs); /* Sector size */
  2964. ST_WORD(tbl+BPB_BytsPerSec, i);
  2965. tbl[BPB_SecPerClus] = (BYTE)au; /* Sectors per cluster */
  2966. ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */
  2967. tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
  2968. i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR; /* Number of rootdir entries */
  2969. ST_WORD(tbl+BPB_RootEntCnt, i);
  2970. if (n_vol < 0x10000) { /* Number of total sectors */
  2971. ST_WORD(tbl+BPB_TotSec16, n_vol);
  2972. } else {
  2973. ST_DWORD(tbl+BPB_TotSec32, n_vol);
  2974. }
  2975. tbl[BPB_Media] = md; /* Media descriptor */
  2976. ST_WORD(tbl+BPB_SecPerTrk, 63); /* Number of sectors per track */
  2977. ST_WORD(tbl+BPB_NumHeads, 255); /* Number of heads */
  2978. ST_DWORD(tbl+BPB_HiddSec, b_vol); /* Hidden sectors */
  2979. n = get_fattime(); /* Use current time as VSN */
  2980. if (fmt == FS_FAT32) {
  2981. ST_DWORD(tbl+BS_VolID32, n); /* VSN */
  2982. ST_DWORD(tbl+BPB_FATSz32, n_fat); /* Number of sectors per FAT */
  2983. ST_DWORD(tbl+BPB_RootClus, 2); /* Root directory start cluster (2) */
  2984. ST_WORD(tbl+BPB_FSInfo, 1); /* FSInfo record offset (VBR+1) */
  2985. ST_WORD(tbl+BPB_BkBootSec, 6); /* Backup boot record offset (VBR+6) */
  2986. tbl[BS_DrvNum32] = 0x80; /* Drive number */
  2987. tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
  2988. mem_cpy(tbl+BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  2989. } else {
  2990. ST_DWORD(tbl+BS_VolID, n); /* VSN */
  2991. ST_WORD(tbl+BPB_FATSz16, n_fat); /* Number of sectors per FAT */
  2992. tbl[BS_DrvNum] = 0x80; /* Drive number */
  2993. tbl[BS_BootSig] = 0x29; /* Extended boot signature */
  2994. mem_cpy(tbl+BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  2995. }
  2996. ST_WORD(tbl+BS_55AA, 0xAA55); /* Signature (Offset is fixed here regardless of sector size) */
  2997. if (disk_write(drv, tbl, b_vol, 1) != RES_OK)/* Write original (VBR) */
  2998. return FR_DISK_ERR;
  2999. if (fmt == FS_FAT32) /* Write backup (VBR+6) */
  3000. disk_write(drv, tbl, b_vol + 6, 1);
  3001. /* Initialize FAT area */
  3002. wsect = b_fat;
  3003. for (i = 0; i < N_FATS; i++) {
  3004. mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */
  3005. n = md; /* Media descriptor byte */
  3006. if (fmt != FS_FAT32) {
  3007. n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
  3008. ST_DWORD(tbl+0, n); /* Reserve cluster #0-1 (FAT12/16) */
  3009. } else {
  3010. n |= 0xFFFFFF00;
  3011. ST_DWORD(tbl+0, n); /* Reserve cluster #0-1 (FAT32) */
  3012. ST_DWORD(tbl+4, 0xFFFFFFFF);
  3013. ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */
  3014. }
  3015. if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
  3016. return FR_DISK_ERR;
  3017. mem_set(tbl, 0, SS(fs)); /* Fill following FAT entries with zero */
  3018. for (n = 1; n < n_fat; n++) { /* This loop may take a time on FAT32 volume due to many single sector write */
  3019. if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
  3020. return FR_DISK_ERR;
  3021. }
  3022. }
  3023. /* Initialize root directory */
  3024. i = (fmt == FS_FAT32) ? au : n_dir;
  3025. do {
  3026. if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
  3027. return FR_DISK_ERR;
  3028. } while (--i);
  3029. #if _USE_ERASE /* Erase data area if needed */
  3030. {
  3031. DWORD eb[2];
  3032. eb[0] = wsect; eb[1] = wsect + n_clst * au - 1;
  3033. disk_ioctl(drv, CTRL_ERASE_SECTOR, eb);
  3034. }
  3035. #endif
  3036. /* Create FSInfo if needed */
  3037. if (fmt == FS_FAT32) {
  3038. ST_WORD(tbl+BS_55AA, 0xAA55);
  3039. ST_DWORD(tbl+FSI_LeadSig, 0x41615252);
  3040. ST_DWORD(tbl+FSI_StrucSig, 0x61417272);
  3041. ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);
  3042. ST_DWORD(tbl+FSI_Nxt_Free, 0xFFFFFFFF);
  3043. disk_write(drv, tbl, b_vol + 1, 1); /* Write original (VBR+1) */
  3044. disk_write(drv, tbl, b_vol + 7, 1); /* Write backup (VBR+7) */
  3045. }
  3046. return (disk_ioctl(drv, CTRL_SYNC, (void*)0) == RES_OK) ? FR_OK : FR_DISK_ERR;
  3047. }
  3048. #endif /* _USE_MKFS && !_FS_READONLY */
  3049. #if _USE_STRFUNC
  3050. /*-----------------------------------------------------------------------*/
  3051. /* Get a string from the file */
  3052. /*-----------------------------------------------------------------------*/
  3053. TCHAR* f_gets (
  3054. TCHAR* buff, /* Pointer to the string buffer to read */
  3055. int len, /* Size of string buffer (characters) */
  3056. FIL* fil /* Pointer to the file object */
  3057. )
  3058. {
  3059. int n = 0;
  3060. TCHAR c, *p = buff;
  3061. BYTE s[2];
  3062. UINT rc;
  3063. while (n < len - 1) { /* Read bytes until buffer gets filled */
  3064. f_read(fil, s, 1, &rc);
  3065. if (rc != 1) break; /* Break on EOF or error */
  3066. c = s[0];
  3067. #if _LFN_UNICODE /* Read a character in UTF-8 encoding */
  3068. if (c >= 0x80) {
  3069. if (c < 0xC0) continue; /* Skip stray trailer */
  3070. if (c < 0xE0) { /* Two-byte sequense */
  3071. f_read(fil, s, 1, &rc);
  3072. if (rc != 1) break;
  3073. c = ((c & 0x1F) << 6) | (s[0] & 0x3F);
  3074. if (c < 0x80) c = '?';
  3075. } else {
  3076. if (c < 0xF0) { /* Three-byte sequense */
  3077. f_read(fil, s, 2, &rc);
  3078. if (rc != 2) break;
  3079. c = (c << 12) | ((s[0] & 0x3F) << 6) | (s[1] & 0x3F);
  3080. if (c < 0x800) c = '?';
  3081. } else { /* Reject four-byte sequense */
  3082. c = '?';
  3083. }
  3084. }
  3085. }
  3086. #endif
  3087. #if _USE_STRFUNC >= 2
  3088. if (c == '\r') continue; /* Strip '\r' */
  3089. #endif
  3090. *p++ = c;
  3091. n++;
  3092. if (c == '\n') break; /* Break on EOL */
  3093. }
  3094. *p = 0;
  3095. return n ? buff : 0; /* When no data read (eof or error), return with error. */
  3096. }
  3097. #if !_FS_READONLY
  3098. #include <stdarg.h>
  3099. /*-----------------------------------------------------------------------*/
  3100. /* Put a character to the file */
  3101. /*-----------------------------------------------------------------------*/
  3102. int f_putc (
  3103. TCHAR c, /* A character to be output */
  3104. FIL* fil /* Pointer to the file object */
  3105. )
  3106. {
  3107. UINT bw, btw;
  3108. BYTE s[3];
  3109. #if _USE_STRFUNC >= 2
  3110. if (c == '\n') f_putc ('\r', fil); /* LF -> CRLF conversion */
  3111. #endif
  3112. #if _LFN_UNICODE /* Write the character in UTF-8 encoding */
  3113. if (c < 0x80) { /* 7-bit */
  3114. s[0] = (BYTE)c;
  3115. btw = 1;
  3116. } else {
  3117. if (c < 0x800) { /* 11-bit */
  3118. s[0] = (BYTE)(0xC0 | (c >> 6));
  3119. s[1] = (BYTE)(0x80 | (c & 0x3F));
  3120. btw = 2;
  3121. } else { /* 16-bit */
  3122. s[0] = (BYTE)(0xE0 | (c >> 12));
  3123. s[1] = (BYTE)(0x80 | ((c >> 6) & 0x3F));
  3124. s[2] = (BYTE)(0x80 | (c & 0x3F));
  3125. btw = 3;
  3126. }
  3127. }
  3128. #else /* Write the character without conversion */
  3129. s[0] = (BYTE)c;
  3130. btw = 1;
  3131. #endif
  3132. f_write(fil, s, btw, &bw); /* Write the char to the file */
  3133. return (bw == btw) ? 1 : EOF; /* Return the result */
  3134. }
  3135. /*-----------------------------------------------------------------------*/
  3136. /* Put a string to the file */
  3137. /*-----------------------------------------------------------------------*/
  3138. int f_puts (
  3139. const TCHAR* str, /* Pointer to the string to be output */
  3140. FIL* fil /* Pointer to the file object */
  3141. )
  3142. {
  3143. int n;
  3144. for (n = 0; *str; str++, n++) {
  3145. if (f_putc(*str, fil) == EOF) return EOF;
  3146. }
  3147. return n;
  3148. }
  3149. /*-----------------------------------------------------------------------*/
  3150. /* Put a formatted string to the file */
  3151. /*-----------------------------------------------------------------------*/
  3152. int f_printf (
  3153. FIL* fil, /* Pointer to the file object */
  3154. const TCHAR* str, /* Pointer to the format string */
  3155. ... /* Optional arguments... */
  3156. )
  3157. {
  3158. va_list arp;
  3159. BYTE f, r;
  3160. UINT i, w;
  3161. ULONG val;
  3162. TCHAR c, d, s[16];
  3163. int res, cc;
  3164. va_start(arp, str);
  3165. for (cc = res = 0; cc != EOF; res += cc) {
  3166. c = *str++;
  3167. if (c == 0) break; /* End of string */
  3168. if (c != '%') { /* Non escape character */
  3169. cc = f_putc(c, fil);
  3170. if (cc != EOF) cc = 1;
  3171. continue;
  3172. }
  3173. w = f = 0;
  3174. c = *str++;
  3175. if (c == '0') { /* Flag: '0' padding */
  3176. f = 1; c = *str++;
  3177. }
  3178. while (IsDigit(c)) { /* Precision */
  3179. w = w * 10 + c - '0';
  3180. c = *str++;
  3181. }
  3182. if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
  3183. f |= 2; c = *str++;
  3184. }
  3185. if (!c) break;
  3186. d = c;
  3187. if (IsLower(d)) d -= 0x20;
  3188. switch (d) { /* Type is... */
  3189. case 'S' : /* String */
  3190. cc = f_puts(va_arg(arp, TCHAR*), fil); continue;
  3191. case 'C' : /* Character */
  3192. cc = f_putc((TCHAR)va_arg(arp, int), fil); continue;
  3193. case 'B' : /* Binary */
  3194. r = 2; break;
  3195. case 'O' : /* Octal */
  3196. r = 8; break;
  3197. case 'D' : /* Signed decimal */
  3198. case 'U' : /* Unsigned decimal */
  3199. r = 10; break;
  3200. case 'X' : /* Hexdecimal */
  3201. r = 16; break;
  3202. default: /* Unknown */
  3203. cc = f_putc(c, fil); continue;
  3204. }
  3205. /* Get an argument */
  3206. val = (f & 2) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : va_arg(arp, unsigned int));
  3207. if (d == 'D' && (val & 0x80000000)) {
  3208. val = 0 - val;
  3209. f |= 4;
  3210. }
  3211. /* Put it in numeral string */
  3212. i = 0;
  3213. do {
  3214. d = (TCHAR)(val % r); val /= r;
  3215. if (d > 9) {
  3216. d += 7;
  3217. if (c == 'x') d += 0x20;
  3218. }
  3219. s[i++] = d + '0';
  3220. } while (val && i < sizeof(s) / sizeof(s[0]));
  3221. if (f & 4) s[i++] = '-';
  3222. cc = 0;
  3223. while (i < w-- && cc != EOF) {
  3224. cc = f_putc((TCHAR)((f & 1) ? '0' : ' '), fil);
  3225. res++;
  3226. }
  3227. do {
  3228. cc = f_putc(s[--i], fil);
  3229. res++;
  3230. } while (i && cc != EOF);
  3231. if (cc != EOF) cc = 0;
  3232. }
  3233. va_end(arp);
  3234. return (cc == EOF) ? cc : res;
  3235. }
  3236. #endif /* !_FS_READONLY */
  3237. #endif /* _USE_STRFUNC */