ff.c 116 KB

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