ff.c 114 KB

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