ff.c 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - FAT file system module R0.11 (C)ChaN, 2015
  3. /-----------------------------------------------------------------------------/
  4. / FatFs module is a free software that opened under license policy of
  5. / following conditions.
  6. /
  7. / Copyright (C) 2015, ChaN, all right reserved.
  8. /
  9. / 1. Redistributions of source code must retain the above copyright notice,
  10. / this condition and the following disclaimer.
  11. /
  12. / This software is provided by the copyright holder and contributors "AS IS"
  13. / and any warranties related to this software are DISCLAIMED.
  14. / The copyright owner or contributors be NOT LIABLE for any damages caused
  15. / by use of this software.
  16. /----------------------------------------------------------------------------*/
  17. #include "ff.h" /* Declarations of FatFs API */
  18. #include "diskio.h" /* Declarations of disk I/O functions */
  19. /*--------------------------------------------------------------------------
  20. Module Private Definitions
  21. ---------------------------------------------------------------------------*/
  22. #if _FATFS != 32020 /* Revision ID */
  23. #error Wrong include file (ff.h).
  24. #endif
  25. /* Reentrancy related */
  26. #if _FS_REENTRANT
  27. #if _USE_LFN == 1
  28. #error Static LFN work area cannot be used at thread-safe configuration
  29. #endif
  30. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  31. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  32. #else
  33. #define ENTER_FF(fs)
  34. #define LEAVE_FF(fs, res) return res
  35. #endif
  36. #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
  37. /* Definitions of sector size */
  38. #if (_MAX_SS < _MIN_SS) || (_MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096) || (_MIN_SS != 512 && _MIN_SS != 1024 && _MIN_SS != 2048 && _MIN_SS != 4096)
  39. #error Wrong sector size configuration
  40. #endif
  41. #if _MAX_SS == _MIN_SS
  42. #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
  43. #else
  44. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  45. #endif
  46. /* Timestamp feature */
  47. #if _FS_NORTC == 1
  48. #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
  49. #error Invalid _FS_NORTC settings
  50. #endif
  51. #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
  52. #else
  53. #define GET_FATTIME() get_fattime()
  54. #endif
  55. /* File access control feature */
  56. #if _FS_LOCK
  57. #if _FS_READONLY
  58. #error _FS_LOCK must be 0 at read-only configuration
  59. #endif
  60. typedef struct {
  61. FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
  62. DWORD clu; /* Object ID 2, directory (0:root) */
  63. WORD idx; /* Object ID 3, directory index */
  64. WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
  65. } FILESEM;
  66. #endif
  67. /* DBCS code ranges and SBCS extend character conversion table */
  68. #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
  69. #define _DF1S 0x81 /* DBC 1st byte range 1 start */
  70. #define _DF1E 0x9F /* DBC 1st byte range 1 end */
  71. #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
  72. #define _DF2E 0xFC /* DBC 1st byte range 2 end */
  73. #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
  74. #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
  75. #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
  76. #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
  77. #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
  78. #define _DF1S 0x81
  79. #define _DF1E 0xFE
  80. #define _DS1S 0x40
  81. #define _DS1E 0x7E
  82. #define _DS2S 0x80
  83. #define _DS2E 0xFE
  84. #elif _CODE_PAGE == 949 /* Korean */
  85. #define _DF1S 0x81
  86. #define _DF1E 0xFE
  87. #define _DS1S 0x41
  88. #define _DS1E 0x5A
  89. #define _DS2S 0x61
  90. #define _DS2E 0x7A
  91. #define _DS3S 0x81
  92. #define _DS3E 0xFE
  93. #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
  94. #define _DF1S 0x81
  95. #define _DF1E 0xFE
  96. #define _DS1S 0x40
  97. #define _DS1E 0x7E
  98. #define _DS2S 0xA1
  99. #define _DS2E 0xFE
  100. #elif _CODE_PAGE == 437 /* U.S. (OEM) */
  101. #define _DF1S 0
  102. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  103. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  104. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  105. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  106. #elif _CODE_PAGE == 720 /* Arabic (OEM) */
  107. #define _DF1S 0
  108. #define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  109. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  110. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  111. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  112. #elif _CODE_PAGE == 737 /* Greek (OEM) */
  113. #define _DF1S 0
  114. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  115. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  116. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  117. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  118. #elif _CODE_PAGE == 775 /* Baltic (OEM) */
  119. #define _DF1S 0
  120. #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  121. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  122. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  123. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  124. #elif _CODE_PAGE == 850 /* Multilingual Latin 1 (OEM) */
  125. #define _DF1S 0
  126. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  127. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  128. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  129. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  130. #elif _CODE_PAGE == 852 /* Latin 2 (OEM) */
  131. #define _DF1S 0
  132. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \
  133. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  134. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  135. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  136. #elif _CODE_PAGE == 855 /* Cyrillic (OEM) */
  137. #define _DF1S 0
  138. #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  139. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  140. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  141. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  142. #elif _CODE_PAGE == 857 /* Turkish (OEM) */
  143. #define _DF1S 0
  144. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  145. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  146. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  147. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  148. #elif _CODE_PAGE == 858 /* Multilingual Latin 1 + Euro (OEM) */
  149. #define _DF1S 0
  150. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  151. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  152. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  153. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  154. #elif _CODE_PAGE == 862 /* Hebrew (OEM) */
  155. #define _DF1S 0
  156. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  157. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  158. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  159. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  160. #elif _CODE_PAGE == 866 /* Russian (OEM) */
  161. #define _DF1S 0
  162. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  163. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  164. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  165. 0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  166. #elif _CODE_PAGE == 874 /* Thai (OEM, Windows) */
  167. #define _DF1S 0
  168. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  169. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  170. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  171. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  172. #elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
  173. #define _DF1S 0
  174. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
  175. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \
  176. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  177. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
  178. #elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */
  179. #define _DF1S 0
  180. #define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
  181. 0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \
  182. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  183. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}
  184. #elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */
  185. #define _DF1S 0
  186. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \
  187. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  188. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  189. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
  190. #elif _CODE_PAGE == 1253 /* Greek (Windows) */
  191. #define _DF1S 0
  192. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  193. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  194. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \
  195. 0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}
  196. #elif _CODE_PAGE == 1254 /* Turkish (Windows) */
  197. #define _DF1S 0
  198. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \
  199. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  200. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  201. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
  202. #elif _CODE_PAGE == 1255 /* Hebrew (Windows) */
  203. #define _DF1S 0
  204. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  205. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  206. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  207. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  208. #elif _CODE_PAGE == 1256 /* Arabic (Windows) */
  209. #define _DF1S 0
  210. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
  211. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  212. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  213. 0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}
  214. #elif _CODE_PAGE == 1257 /* Baltic (Windows) */
  215. #define _DF1S 0
  216. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  217. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \
  218. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  219. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
  220. #elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */
  221. #define _DF1S 0
  222. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \
  223. 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  224. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  225. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}
  226. #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
  227. #if _USE_LFN
  228. #error Cannot use LFN feature without valid code page.
  229. #endif
  230. #define _DF1S 0
  231. #else
  232. #error Unknown code page
  233. #endif
  234. /* Character code support macros */
  235. #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
  236. #define IsLower(c) (((c)>='a')&&((c)<='z'))
  237. #define IsDigit(c) (((c)>='0')&&((c)<='9'))
  238. #if _DF1S /* Code page is DBCS */
  239. #ifdef _DF2S /* Two 1st byte areas */
  240. #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  241. #else /* One 1st byte area */
  242. #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  243. #endif
  244. #ifdef _DS3S /* Three 2nd byte areas */
  245. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  246. #else /* Two 2nd byte areas */
  247. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  248. #endif
  249. #else /* Code page is SBCS */
  250. #define IsDBCS1(c) 0
  251. #define IsDBCS2(c) 0
  252. #endif /* _DF1S */
  253. /* Name status flags */
  254. #define NSFLAG 11 /* Index of name status byte in fn[] */
  255. #define NS_LOSS 0x01 /* Out of 8.3 format */
  256. #define NS_LFN 0x02 /* Force to create LFN entry */
  257. #define NS_LAST 0x04 /* Last segment */
  258. #define NS_BODY 0x08 /* Lower case flag (body) */
  259. #define NS_EXT 0x10 /* Lower case flag (ext) */
  260. #define NS_DOT 0x20 /* Dot entry */
  261. /* FAT sub-type boundaries (Differ from specs but correct for real DOS/Windows) */
  262. #define MIN_FAT16 4086U /* Minimum number of clusters as FAT16 */
  263. #define MIN_FAT32 65526U /* Minimum number of clusters as FAT32 */
  264. /* FatFs refers the members in the FAT structures as byte array instead of
  265. / structure member because the structure is not binary compatible between
  266. / different platforms */
  267. #define BS_jmpBoot 0 /* x86 jump instruction (3) */
  268. #define BS_OEMName 3 /* OEM name (8) */
  269. #define BPB_BytsPerSec 11 /* Sector size [byte] (2) */
  270. #define BPB_SecPerClus 13 /* Cluster size [sector] (1) */
  271. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (2) */
  272. #define BPB_NumFATs 16 /* Number of FAT copies (1) */
  273. #define BPB_RootEntCnt 17 /* Number of root directory entries for FAT12/16 (2) */
  274. #define BPB_TotSec16 19 /* Volume size [sector] (2) */
  275. #define BPB_Media 21 /* Media descriptor (1) */
  276. #define BPB_FATSz16 22 /* FAT size [sector] (2) */
  277. #define BPB_SecPerTrk 24 /* Track size [sector] (2) */
  278. #define BPB_NumHeads 26 /* Number of heads (2) */
  279. #define BPB_HiddSec 28 /* Number of special hidden sectors (4) */
  280. #define BPB_TotSec32 32 /* Volume size [sector] (4) */
  281. #define BS_DrvNum 36 /* Physical drive number (2) */
  282. #define BS_BootSig 38 /* Extended boot signature (1) */
  283. #define BS_VolID 39 /* Volume serial number (4) */
  284. #define BS_VolLab 43 /* Volume label (8) */
  285. #define BS_FilSysType 54 /* File system type (1) */
  286. #define BPB_FATSz32 36 /* FAT size [sector] (4) */
  287. #define BPB_ExtFlags 40 /* Extended flags (2) */
  288. #define BPB_FSVer 42 /* File system version (2) */
  289. #define BPB_RootClus 44 /* Root directory first cluster (4) */
  290. #define BPB_FSInfo 48 /* Offset of FSINFO sector (2) */
  291. #define BPB_BkBootSec 50 /* Offset of backup boot sector (2) */
  292. #define BS_DrvNum32 64 /* Physical drive number (2) */
  293. #define BS_BootSig32 66 /* Extended boot signature (1) */
  294. #define BS_VolID32 67 /* Volume serial number (4) */
  295. #define BS_VolLab32 71 /* Volume label (8) */
  296. #define BS_FilSysType32 82 /* File system type (1) */
  297. #define FSI_LeadSig 0 /* FSI: Leading signature (4) */
  298. #define FSI_StrucSig 484 /* FSI: Structure signature (4) */
  299. #define FSI_Free_Count 488 /* FSI: Number of free clusters (4) */
  300. #define FSI_Nxt_Free 492 /* FSI: Last allocated cluster (4) */
  301. #define MBR_Table 446 /* MBR: Partition table offset (2) */
  302. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  303. #define BS_55AA 510 /* Signature word (2) */
  304. #define DIR_Name 0 /* Short file name (11) */
  305. #define DIR_Attr 11 /* Attribute (1) */
  306. #define DIR_NTres 12 /* Lower case flag (1) */
  307. #define DIR_CrtTimeTenth 13 /* Created time sub-second (1) */
  308. #define DIR_CrtTime 14 /* Created time (2) */
  309. #define DIR_CrtDate 16 /* Created date (2) */
  310. #define DIR_LstAccDate 18 /* Last accessed date (2) */
  311. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (2) */
  312. #define DIR_WrtTime 22 /* Modified time (2) */
  313. #define DIR_WrtDate 24 /* Modified date (2) */
  314. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (2) */
  315. #define DIR_FileSize 28 /* File size (4) */
  316. #define LDIR_Ord 0 /* LFN entry order and LLE flag (1) */
  317. #define LDIR_Attr 11 /* LFN attribute (1) */
  318. #define LDIR_Type 12 /* LFN type (1) */
  319. #define LDIR_Chksum 13 /* Sum of corresponding SFN entry */
  320. #define LDIR_FstClusLO 26 /* Must be zero (0) */
  321. #define SZ_DIRE 32 /* Size of a directory entry */
  322. #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
  323. #define DDEM 0xE5 /* Deleted directory entry mark at DIR_Name[0] */
  324. #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
  325. /*------------------------------------------------------------*/
  326. /* Module private work area */
  327. /*------------------------------------------------------------*/
  328. /* Remark: Uninitialized variables with static duration are
  329. / guaranteed zero/null at start-up. If not, either the linker
  330. / or start-up routine being used is out of ANSI-C standard.
  331. */
  332. #if _VOLUMES < 1 || _VOLUMES > 9
  333. #error Wrong _VOLUMES setting
  334. #endif
  335. static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
  336. static WORD Fsid; /* File system mount ID */
  337. #if _FS_RPATH && _VOLUMES >= 2
  338. static BYTE CurrVol; /* Current drive */
  339. #endif
  340. #if _FS_LOCK
  341. static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
  342. #endif
  343. #if _USE_LFN == 0 /* Non LFN feature */
  344. #define DEFINE_NAMEBUF BYTE sfn[12]
  345. #define INIT_BUF(dobj) (dobj).fn = sfn
  346. #define FREE_BUF()
  347. #else
  348. #if _MAX_LFN < 12 || _MAX_LFN > 255
  349. #error Wrong _MAX_LFN setting
  350. #endif
  351. #if _USE_LFN == 1 /* LFN feature with static working buffer */
  352. static WCHAR LfnBuf[_MAX_LFN + 1];
  353. #define DEFINE_NAMEBUF BYTE sfn[12]
  354. #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }
  355. #define FREE_BUF()
  356. #elif _USE_LFN == 2 /* LFN feature with dynamic working buffer on the stack */
  357. #define DEFINE_NAMEBUF BYTE sfn[12]; WCHAR lbuf[_MAX_LFN + 1]
  358. #define INIT_BUF(dobj) { (dobj).fn = sfn; (dobj).lfn = lbuf; }
  359. #define FREE_BUF()
  360. #elif _USE_LFN == 3 /* LFN feature with dynamic working buffer on the heap */
  361. #define DEFINE_NAMEBUF BYTE sfn[12]; WCHAR *lfn
  362. #define INIT_BUF(dobj) { lfn = ff_memalloc((_MAX_LFN + 1) * 2); if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); (dobj).lfn = lfn; (dobj).fn = sfn; }
  363. #define FREE_BUF() ff_memfree(lfn)
  364. #else
  365. #error Wrong _USE_LFN setting
  366. #endif
  367. #endif
  368. #ifdef _EXCVT
  369. static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for extended characters */
  370. #endif
  371. /*--------------------------------------------------------------------------
  372. Module Private Functions
  373. ---------------------------------------------------------------------------*/
  374. /*-----------------------------------------------------------------------*/
  375. /* String functions */
  376. /*-----------------------------------------------------------------------*/
  377. /* Copy memory to memory */
  378. static
  379. void mem_cpy (void* dst, const void* src, UINT cnt) {
  380. BYTE *d = (BYTE*)dst;
  381. const BYTE *s = (const BYTE*)src;
  382. #if _WORD_ACCESS == 1
  383. while (cnt >= sizeof (int)) {
  384. *(int*)d = *(int*)s;
  385. d += sizeof (int); s += sizeof (int);
  386. cnt -= sizeof (int);
  387. }
  388. #endif
  389. while (cnt--)
  390. *d++ = *s++;
  391. }
  392. /* Fill memory */
  393. static
  394. void mem_set (void* dst, int val, UINT cnt) {
  395. BYTE *d = (BYTE*)dst;
  396. while (cnt--)
  397. *d++ = (BYTE)val;
  398. }
  399. /* Compare memory to memory */
  400. static
  401. int mem_cmp (const void* dst, const void* src, UINT cnt) {
  402. const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
  403. int r = 0;
  404. while (cnt-- && (r = *d++ - *s++) == 0) ;
  405. return r;
  406. }
  407. /* Check if chr is contained in the string */
  408. static
  409. int chk_chr (const char* str, int chr) {
  410. while (*str && *str != chr) str++;
  411. return *str;
  412. }
  413. /*-----------------------------------------------------------------------*/
  414. /* Request/Release grant to access the volume */
  415. /*-----------------------------------------------------------------------*/
  416. #if _FS_REENTRANT
  417. static
  418. int lock_fs (
  419. FATFS* fs /* File system object */
  420. )
  421. {
  422. return ff_req_grant(fs->sobj);
  423. }
  424. static
  425. void unlock_fs (
  426. FATFS* fs, /* File system object */
  427. FRESULT res /* Result code to be returned */
  428. )
  429. {
  430. if (fs &&
  431. res != FR_NOT_ENABLED &&
  432. res != FR_INVALID_DRIVE &&
  433. res != FR_INVALID_OBJECT &&
  434. res != FR_TIMEOUT) {
  435. ff_rel_grant(fs->sobj);
  436. }
  437. }
  438. #endif
  439. /*-----------------------------------------------------------------------*/
  440. /* File lock control functions */
  441. /*-----------------------------------------------------------------------*/
  442. #if _FS_LOCK
  443. static
  444. FRESULT chk_lock ( /* Check if the file can be accessed */
  445. DIR* dp, /* Directory object pointing the file to be checked */
  446. int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
  447. )
  448. {
  449. UINT i, be;
  450. /* Search file semaphore table */
  451. for (i = be = 0; i < _FS_LOCK; i++) {
  452. if (Files[i].fs) { /* Existing entry */
  453. if (Files[i].fs == dp->fs && /* Check if the object matched with an open object */
  454. Files[i].clu == dp->sclust &&
  455. Files[i].idx == dp->index) break;
  456. } else { /* Blank entry */
  457. be = 1;
  458. }
  459. }
  460. if (i == _FS_LOCK) /* The object is not opened */
  461. return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */
  462. /* The object has been opened. Reject any open against writing file and all write mode open */
  463. return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  464. }
  465. static
  466. int enq_lock (void) /* Check if an entry is available for a new object */
  467. {
  468. UINT i;
  469. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  470. return (i == _FS_LOCK) ? 0 : 1;
  471. }
  472. static
  473. UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
  474. DIR* dp, /* Directory object pointing the file to register or increment */
  475. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  476. )
  477. {
  478. UINT i;
  479. for (i = 0; i < _FS_LOCK; i++) { /* Find the object */
  480. if (Files[i].fs == dp->fs &&
  481. Files[i].clu == dp->sclust &&
  482. Files[i].idx == dp->index) break;
  483. }
  484. if (i == _FS_LOCK) { /* Not opened. Register it as new. */
  485. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  486. if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */
  487. Files[i].fs = dp->fs;
  488. Files[i].clu = dp->sclust;
  489. Files[i].idx = dp->index;
  490. Files[i].ctr = 0;
  491. }
  492. if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
  493. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  494. return i + 1;
  495. }
  496. static
  497. FRESULT dec_lock ( /* Decrement object open counter */
  498. UINT i /* Semaphore index (1..) */
  499. )
  500. {
  501. WORD n;
  502. FRESULT res;
  503. if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
  504. n = Files[i].ctr;
  505. if (n == 0x100) n = 0; /* If write mode open, delete the entry */
  506. if (n) n--; /* Decrement read mode open count */
  507. Files[i].ctr = n;
  508. if (!n) Files[i].fs = 0; /* Delete the entry if open count gets zero */
  509. res = FR_OK;
  510. } else {
  511. res = FR_INT_ERR; /* Invalid index nunber */
  512. }
  513. return res;
  514. }
  515. static
  516. void clear_lock ( /* Clear lock entries of the volume */
  517. FATFS *fs
  518. )
  519. {
  520. UINT i;
  521. for (i = 0; i < _FS_LOCK; i++) {
  522. if (Files[i].fs == fs) Files[i].fs = 0;
  523. }
  524. }
  525. #endif
  526. /*-----------------------------------------------------------------------*/
  527. /* Move/Flush disk access window in the file system object */
  528. /*-----------------------------------------------------------------------*/
  529. #if !_FS_READONLY
  530. static
  531. FRESULT sync_window (
  532. FATFS* fs /* File system object */
  533. )
  534. {
  535. DWORD wsect;
  536. UINT nf;
  537. FRESULT res = FR_OK;
  538. if (fs->wflag) { /* Write back the sector if it is dirty */
  539. wsect = fs->winsect; /* Current sector number */
  540. if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) {
  541. res = FR_DISK_ERR;
  542. } else {
  543. fs->wflag = 0;
  544. if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */
  545. for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */
  546. wsect += fs->fsize;
  547. disk_write(fs->drv, fs->win, wsect, 1);
  548. }
  549. }
  550. }
  551. }
  552. return res;
  553. }
  554. #endif
  555. static
  556. FRESULT move_window (
  557. FATFS* fs, /* File system object */
  558. DWORD sector /* Sector number to make appearance in the fs->win[] */
  559. )
  560. {
  561. FRESULT res = FR_OK;
  562. if (sector != fs->winsect) { /* Window offset changed? */
  563. #if !_FS_READONLY
  564. res = sync_window(fs); /* Write-back changes */
  565. #endif
  566. if (res == FR_OK) { /* Fill sector window with new data */
  567. if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) {
  568. sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */
  569. res = FR_DISK_ERR;
  570. }
  571. fs->winsect = sector;
  572. }
  573. }
  574. return res;
  575. }
  576. /*-----------------------------------------------------------------------*/
  577. /* Synchronize file system and strage device */
  578. /*-----------------------------------------------------------------------*/
  579. #if !_FS_READONLY
  580. static
  581. FRESULT sync_fs ( /* FR_OK: successful, FR_DISK_ERR: failed */
  582. FATFS* fs /* File system object */
  583. )
  584. {
  585. FRESULT res;
  586. res = sync_window(fs);
  587. if (res == FR_OK) {
  588. /* Update FSINFO sector if needed */
  589. if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) {
  590. /* Create FSINFO structure */
  591. mem_set(fs->win, 0, SS(fs));
  592. ST_WORD(fs->win + BS_55AA, 0xAA55);
  593. ST_DWORD(fs->win + FSI_LeadSig, 0x41615252);
  594. ST_DWORD(fs->win + FSI_StrucSig, 0x61417272);
  595. ST_DWORD(fs->win + FSI_Free_Count, fs->free_clust);
  596. ST_DWORD(fs->win + FSI_Nxt_Free, fs->last_clust);
  597. /* Write it into the FSINFO sector */
  598. fs->winsect = fs->volbase + 1;
  599. disk_write(fs->drv, fs->win, fs->winsect, 1);
  600. fs->fsi_flag = 0;
  601. }
  602. /* Make sure that no pending write process in the physical drive */
  603. if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK)
  604. res = FR_DISK_ERR;
  605. }
  606. return res;
  607. }
  608. #endif
  609. /*-----------------------------------------------------------------------*/
  610. /* Get sector# from cluster# */
  611. /*-----------------------------------------------------------------------*/
  612. /* Hidden API for hacks and disk tools */
  613. DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */
  614. FATFS* fs, /* File system object */
  615. DWORD clst /* Cluster# to be converted */
  616. )
  617. {
  618. clst -= 2;
  619. if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
  620. return clst * fs->csize + fs->database;
  621. }
  622. /*-----------------------------------------------------------------------*/
  623. /* FAT access - Read value of a FAT entry */
  624. /*-----------------------------------------------------------------------*/
  625. /* Hidden API for hacks and disk tools */
  626. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x0FFFFFFF:Cluster status */
  627. FATFS* fs, /* File system object */
  628. DWORD clst /* FAT index number (cluster number) to get the value */
  629. )
  630. {
  631. UINT wc, bc;
  632. BYTE *p;
  633. DWORD val;
  634. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  635. val = 1; /* Internal error */
  636. } else {
  637. val = 0xFFFFFFFF; /* Default value falls on disk error */
  638. switch (fs->fs_type) {
  639. case FS_FAT12 :
  640. bc = (UINT)clst; bc += bc / 2;
  641. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  642. wc = fs->win[bc++ % SS(fs)];
  643. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  644. wc |= fs->win[bc % SS(fs)] << 8;
  645. val = clst & 1 ? wc >> 4 : (wc & 0xFFF);
  646. break;
  647. case FS_FAT16 :
  648. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
  649. p = &fs->win[clst * 2 % SS(fs)];
  650. val = LD_WORD(p);
  651. break;
  652. case FS_FAT32 :
  653. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  654. p = &fs->win[clst * 4 % SS(fs)];
  655. val = LD_DWORD(p) & 0x0FFFFFFF;
  656. break;
  657. default:
  658. val = 1; /* Internal error */
  659. }
  660. }
  661. return val;
  662. }
  663. /*-----------------------------------------------------------------------*/
  664. /* FAT access - Change value of a FAT entry */
  665. /*-----------------------------------------------------------------------*/
  666. /* Hidden API for hacks and disk tools */
  667. #if !_FS_READONLY
  668. FRESULT put_fat (
  669. FATFS* fs, /* File system object */
  670. DWORD clst, /* FAT index number (cluster number) to be changed */
  671. DWORD val /* New value to be set to the entry */
  672. )
  673. {
  674. UINT bc;
  675. BYTE *p;
  676. FRESULT res;
  677. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  678. res = FR_INT_ERR;
  679. } else {
  680. switch (fs->fs_type) {
  681. case FS_FAT12 :
  682. bc = (UINT)clst; bc += bc / 2;
  683. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  684. if (res != FR_OK) break;
  685. p = &fs->win[bc++ % SS(fs)];
  686. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  687. fs->wflag = 1;
  688. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  689. if (res != FR_OK) break;
  690. p = &fs->win[bc % SS(fs)];
  691. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  692. fs->wflag = 1;
  693. break;
  694. case FS_FAT16 :
  695. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  696. if (res != FR_OK) break;
  697. p = &fs->win[clst * 2 % SS(fs)];
  698. ST_WORD(p, (WORD)val);
  699. fs->wflag = 1;
  700. break;
  701. case FS_FAT32 :
  702. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  703. if (res != FR_OK) break;
  704. p = &fs->win[clst * 4 % SS(fs)];
  705. val |= LD_DWORD(p) & 0xF0000000;
  706. ST_DWORD(p, val);
  707. fs->wflag = 1;
  708. break;
  709. default :
  710. res = FR_INT_ERR;
  711. }
  712. }
  713. return res;
  714. }
  715. #endif /* !_FS_READONLY */
  716. /*-----------------------------------------------------------------------*/
  717. /* FAT handling - Remove a cluster chain */
  718. /*-----------------------------------------------------------------------*/
  719. #if !_FS_READONLY
  720. static
  721. FRESULT remove_chain (
  722. FATFS* fs, /* File system object */
  723. DWORD clst /* Cluster# to remove a chain from */
  724. )
  725. {
  726. FRESULT res;
  727. DWORD nxt;
  728. #if _USE_TRIM
  729. DWORD scl = clst, ecl = clst, rt[2];
  730. #endif
  731. if (clst < 2 || clst >= fs->n_fatent) { /* Check range */
  732. res = FR_INT_ERR;
  733. } else {
  734. res = FR_OK;
  735. while (clst < fs->n_fatent) { /* Not a last link? */
  736. nxt = get_fat(fs, clst); /* Get cluster status */
  737. if (nxt == 0) break; /* Empty cluster? */
  738. if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */
  739. if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */
  740. res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */
  741. if (res != FR_OK) break;
  742. if (fs->free_clust != 0xFFFFFFFF) { /* Update FSINFO */
  743. fs->free_clust++;
  744. fs->fsi_flag |= 1;
  745. }
  746. #if _USE_TRIM
  747. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  748. ecl = nxt;
  749. } else { /* End of contiguous clusters */
  750. rt[0] = clust2sect(fs, scl); /* Start sector */
  751. rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
  752. disk_ioctl(fs->drv, CTRL_TRIM, rt); /* Erase the block */
  753. scl = ecl = nxt;
  754. }
  755. #endif
  756. clst = nxt; /* Next cluster */
  757. }
  758. }
  759. return res;
  760. }
  761. #endif
  762. /*-----------------------------------------------------------------------*/
  763. /* FAT handling - Stretch or Create a cluster chain */
  764. /*-----------------------------------------------------------------------*/
  765. #if !_FS_READONLY
  766. static
  767. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  768. FATFS* fs, /* File system object */
  769. DWORD clst /* Cluster# to stretch. 0 means create a new chain. */
  770. )
  771. {
  772. DWORD cs, ncl, scl;
  773. FRESULT res;
  774. if (clst == 0) { /* Create a new chain */
  775. scl = fs->last_clust; /* Get suggested start point */
  776. if (!scl || scl >= fs->n_fatent) scl = 1;
  777. }
  778. else { /* Stretch the current chain */
  779. cs = get_fat(fs, clst); /* Check the cluster status */
  780. if (cs < 2) return 1; /* Invalid value */
  781. if (cs == 0xFFFFFFFF) return cs; /* A disk error occurred */
  782. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  783. scl = clst;
  784. }
  785. ncl = scl; /* Start cluster */
  786. for (;;) {
  787. ncl++; /* Next cluster */
  788. if (ncl >= fs->n_fatent) { /* Check wrap around */
  789. ncl = 2;
  790. if (ncl > scl) return 0; /* No free cluster */
  791. }
  792. cs = get_fat(fs, ncl); /* Get the cluster status */
  793. if (cs == 0) break; /* Found a free cluster */
  794. if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */
  795. return cs;
  796. if (ncl == scl) return 0; /* No free cluster */
  797. }
  798. res = put_fat(fs, ncl, 0x0FFFFFFF); /* Mark the new cluster "last link" */
  799. if (res == FR_OK && clst != 0) {
  800. res = put_fat(fs, clst, ncl); /* Link it to the previous one if needed */
  801. }
  802. if (res == FR_OK) {
  803. fs->last_clust = ncl; /* Update FSINFO */
  804. if (fs->free_clust != 0xFFFFFFFF) {
  805. fs->free_clust--;
  806. fs->fsi_flag |= 1;
  807. }
  808. } else {
  809. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;
  810. }
  811. return ncl; /* Return new cluster number or error code */
  812. }
  813. #endif /* !_FS_READONLY */
  814. /*-----------------------------------------------------------------------*/
  815. /* FAT handling - Convert offset into cluster with link map table */
  816. /*-----------------------------------------------------------------------*/
  817. #if _USE_FASTSEEK
  818. static
  819. DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  820. FIL* fp, /* Pointer to the file object */
  821. DWORD ofs /* File offset to be converted to cluster# */
  822. )
  823. {
  824. DWORD cl, ncl, *tbl;
  825. tbl = fp->cltbl + 1; /* Top of CLMT */
  826. cl = ofs / SS(fp->fs) / fp->fs->csize; /* Cluster order from top of the file */
  827. for (;;) {
  828. ncl = *tbl++; /* Number of cluters in the fragment */
  829. if (!ncl) return 0; /* End of table? (error) */
  830. if (cl < ncl) break; /* In this fragment? */
  831. cl -= ncl; tbl++; /* Next fragment */
  832. }
  833. return cl + *tbl; /* Return the cluster number */
  834. }
  835. #endif /* _USE_FASTSEEK */
  836. /*-----------------------------------------------------------------------*/
  837. /* Directory handling - Set directory index */
  838. /*-----------------------------------------------------------------------*/
  839. static
  840. FRESULT dir_sdi (
  841. DIR* dp, /* Pointer to directory object */
  842. UINT idx /* Index of directory table */
  843. )
  844. {
  845. DWORD clst, sect;
  846. UINT ic;
  847. dp->index = (WORD)idx; /* Current index */
  848. clst = dp->sclust; /* Table start cluster (0:root) */
  849. if (clst == 1 || clst >= dp->fs->n_fatent) /* Check start cluster range */
  850. return FR_INT_ERR;
  851. if (!clst && dp->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */
  852. clst = dp->fs->dirbase;
  853. if (clst == 0) { /* Static table (root-directory in FAT12/16) */
  854. if (idx >= dp->fs->n_rootdir) /* Is index out of range? */
  855. return FR_INT_ERR;
  856. sect = dp->fs->dirbase;
  857. }
  858. else { /* Dynamic table (root-directory in FAT32 or sub-directory) */
  859. ic = SS(dp->fs) / SZ_DIRE * dp->fs->csize; /* Entries per cluster */
  860. while (idx >= ic) { /* Follow cluster chain */
  861. clst = get_fat(dp->fs, clst); /* Get next cluster */
  862. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  863. if (clst < 2 || clst >= dp->fs->n_fatent) /* Reached to end of table or internal error */
  864. return FR_INT_ERR;
  865. idx -= ic;
  866. }
  867. sect = clust2sect(dp->fs, clst);
  868. }
  869. dp->clust = clst; /* Current cluster# */
  870. if (!sect) return FR_INT_ERR;
  871. dp->sect = sect + idx / (SS(dp->fs) / SZ_DIRE); /* Sector# of the directory entry */
  872. dp->dir = dp->fs->win + (idx % (SS(dp->fs) / SZ_DIRE)) * SZ_DIRE; /* Ptr to the entry in the sector */
  873. return FR_OK;
  874. }
  875. /*-----------------------------------------------------------------------*/
  876. /* Directory handling - Move directory table index next */
  877. /*-----------------------------------------------------------------------*/
  878. static
  879. FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
  880. DIR* dp, /* Pointer to the directory object */
  881. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  882. )
  883. {
  884. DWORD clst;
  885. UINT i;
  886. #if !_FS_READONLY
  887. UINT c;
  888. #endif
  889. i = dp->index + 1;
  890. if (!(i & 0xFFFF) || !dp->sect) /* Report EOT when index has reached 65535 */
  891. return FR_NO_FILE;
  892. if (!(i % (SS(dp->fs) / SZ_DIRE))) { /* Sector changed? */
  893. dp->sect++; /* Next sector */
  894. if (!dp->clust) { /* Static table */
  895. if (i >= dp->fs->n_rootdir) /* Report EOT if it reached end of static table */
  896. return FR_NO_FILE;
  897. }
  898. else { /* Dynamic table */
  899. if (((i / (SS(dp->fs) / SZ_DIRE)) & (dp->fs->csize - 1)) == 0) { /* Cluster changed? */
  900. clst = get_fat(dp->fs, dp->clust); /* Get next cluster */
  901. if (clst <= 1) return FR_INT_ERR;
  902. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  903. if (clst >= dp->fs->n_fatent) { /* If it reached end of dynamic table, */
  904. #if !_FS_READONLY
  905. if (!stretch) return FR_NO_FILE; /* If do not stretch, report EOT */
  906. clst = create_chain(dp->fs, dp->clust); /* Stretch cluster chain */
  907. if (clst == 0) return FR_DENIED; /* No free cluster */
  908. if (clst == 1) return FR_INT_ERR;
  909. if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
  910. /* Clean-up stretched table */
  911. if (sync_window(dp->fs)) return FR_DISK_ERR;/* Flush disk access window */
  912. mem_set(dp->fs->win, 0, SS(dp->fs)); /* Clear window buffer */
  913. dp->fs->winsect = clust2sect(dp->fs, clst); /* Cluster start sector */
  914. for (c = 0; c < dp->fs->csize; c++) { /* Fill the new cluster with 0 */
  915. dp->fs->wflag = 1;
  916. if (sync_window(dp->fs)) return FR_DISK_ERR;
  917. dp->fs->winsect++;
  918. }
  919. dp->fs->winsect -= c; /* Rewind window offset */
  920. #else
  921. if (!stretch) return FR_NO_FILE; /* If do not stretch, report EOT (this is to suppress warning) */
  922. return FR_NO_FILE; /* Report EOT */
  923. #endif
  924. }
  925. dp->clust = clst; /* Initialize data for new cluster */
  926. dp->sect = clust2sect(dp->fs, clst);
  927. }
  928. }
  929. }
  930. dp->index = (WORD)i; /* Current index */
  931. dp->dir = dp->fs->win + (i % (SS(dp->fs) / SZ_DIRE)) * SZ_DIRE; /* Current entry in the window */
  932. return FR_OK;
  933. }
  934. /*-----------------------------------------------------------------------*/
  935. /* Directory handling - Reserve directory entry */
  936. /*-----------------------------------------------------------------------*/
  937. #if !_FS_READONLY
  938. static
  939. FRESULT dir_alloc (
  940. DIR* dp, /* Pointer to the directory object */
  941. UINT nent /* Number of contiguous entries to allocate (1-21) */
  942. )
  943. {
  944. FRESULT res;
  945. UINT n;
  946. res = dir_sdi(dp, 0);
  947. if (res == FR_OK) {
  948. n = 0;
  949. do {
  950. res = move_window(dp->fs, dp->sect);
  951. if (res != FR_OK) break;
  952. if (dp->dir[0] == DDEM || dp->dir[0] == 0) { /* Is it a free entry? */
  953. if (++n == nent) break; /* A block of contiguous free entries is found */
  954. } else {
  955. n = 0; /* Not a blank entry. Restart to search */
  956. }
  957. res = dir_next(dp, 1); /* Next entry with table stretch enabled */
  958. } while (res == FR_OK);
  959. }
  960. if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
  961. return res;
  962. }
  963. #endif
  964. /*-----------------------------------------------------------------------*/
  965. /* Directory handling - Load/Store start cluster number */
  966. /*-----------------------------------------------------------------------*/
  967. static
  968. DWORD ld_clust (
  969. FATFS* fs, /* Pointer to the fs object */
  970. BYTE* dir /* Pointer to the directory entry */
  971. )
  972. {
  973. DWORD cl;
  974. cl = LD_WORD(dir + DIR_FstClusLO);
  975. if (fs->fs_type == FS_FAT32)
  976. cl |= (DWORD)LD_WORD(dir + DIR_FstClusHI) << 16;
  977. return cl;
  978. }
  979. #if !_FS_READONLY
  980. static
  981. void st_clust (
  982. BYTE* dir, /* Pointer to the directory entry */
  983. DWORD cl /* Value to be set */
  984. )
  985. {
  986. ST_WORD(dir + DIR_FstClusLO, cl);
  987. ST_WORD(dir + DIR_FstClusHI, cl >> 16);
  988. }
  989. #endif
  990. /*-----------------------------------------------------------------------*/
  991. /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */
  992. /*-----------------------------------------------------------------------*/
  993. #if _USE_LFN
  994. static
  995. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
  996. static
  997. int cmp_lfn ( /* 1:Matched, 0:Not matched */
  998. WCHAR* lfnbuf, /* Pointer to the LFN to be compared */
  999. BYTE* dir /* Pointer to the directory entry containing a part of LFN */
  1000. )
  1001. {
  1002. UINT i, s;
  1003. WCHAR wc, uc;
  1004. i = ((dir[LDIR_Ord] & ~LLEF) - 1) * 13; /* Get offset in the LFN buffer */
  1005. s = 0; wc = 1;
  1006. do {
  1007. uc = LD_WORD(dir + LfnOfs[s]); /* Pick an LFN character from the entry */
  1008. if (wc) { /* Last character has not been processed */
  1009. wc = ff_wtoupper(uc); /* Convert it to upper case */
  1010. if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it */
  1011. return 0; /* Not matched */
  1012. } else {
  1013. if (uc != 0xFFFF) return 0; /* Check filler */
  1014. }
  1015. } while (++s < 13); /* Repeat until all characters in the entry are checked */
  1016. if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) /* Last segment matched but different length */
  1017. return 0;
  1018. return 1; /* The part of LFN matched */
  1019. }
  1020. static
  1021. int pick_lfn ( /* 1:Succeeded, 0:Buffer overflow */
  1022. WCHAR* lfnbuf, /* Pointer to the Unicode-LFN buffer */
  1023. BYTE* dir /* Pointer to the directory entry */
  1024. )
  1025. {
  1026. UINT i, s;
  1027. WCHAR wc, uc;
  1028. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1029. s = 0; wc = 1;
  1030. do {
  1031. uc = LD_WORD(dir + LfnOfs[s]); /* Pick an LFN character from the entry */
  1032. if (wc) { /* Last character has not been processed */
  1033. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1034. lfnbuf[i++] = wc = uc; /* Store it */
  1035. } else {
  1036. if (uc != 0xFFFF) return 0; /* Check filler */
  1037. }
  1038. } while (++s < 13); /* Read all character in the entry */
  1039. if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */
  1040. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1041. lfnbuf[i] = 0;
  1042. }
  1043. return 1;
  1044. }
  1045. #if !_FS_READONLY
  1046. static
  1047. void fit_lfn (
  1048. const WCHAR* lfnbuf, /* Pointer to the LFN buffer */
  1049. BYTE* dir, /* Pointer to the directory entry */
  1050. BYTE ord, /* LFN order (1-20) */
  1051. BYTE sum /* SFN sum */
  1052. )
  1053. {
  1054. UINT i, s;
  1055. WCHAR wc;
  1056. dir[LDIR_Chksum] = sum; /* Set check sum */
  1057. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  1058. dir[LDIR_Type] = 0;
  1059. ST_WORD(dir + LDIR_FstClusLO, 0);
  1060. i = (ord - 1) * 13; /* Get offset in the LFN buffer */
  1061. s = wc = 0;
  1062. do {
  1063. if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective character */
  1064. ST_WORD(dir+LfnOfs[s], wc); /* Put it */
  1065. if (!wc) wc = 0xFFFF; /* Padding characters following last character */
  1066. } while (++s < 13);
  1067. if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLEF; /* Bottom LFN part is the start of LFN sequence */
  1068. dir[LDIR_Ord] = ord; /* Set the LFN order */
  1069. }
  1070. #endif
  1071. #endif
  1072. /*-----------------------------------------------------------------------*/
  1073. /* Create numbered name */
  1074. /*-----------------------------------------------------------------------*/
  1075. #if _USE_LFN
  1076. static
  1077. void gen_numname (
  1078. BYTE* dst, /* Pointer to the buffer to store numbered SFN */
  1079. const BYTE* src, /* Pointer to SFN */
  1080. const WCHAR* lfn, /* Pointer to LFN */
  1081. UINT seq /* Sequence number */
  1082. )
  1083. {
  1084. BYTE ns[8], c;
  1085. UINT i, j;
  1086. WCHAR wc;
  1087. DWORD sr;
  1088. mem_cpy(dst, src, 11);
  1089. if (seq > 5) { /* On many collisions, generate a hash number instead of sequential number */
  1090. sr = seq;
  1091. while (*lfn) { /* Create a CRC */
  1092. wc = *lfn++;
  1093. for (i = 0; i < 16; i++) {
  1094. sr = (sr << 1) + (wc & 1);
  1095. wc >>= 1;
  1096. if (sr & 0x10000) sr ^= 0x11021;
  1097. }
  1098. }
  1099. seq = (UINT)sr;
  1100. }
  1101. /* itoa (hexdecimal) */
  1102. i = 7;
  1103. do {
  1104. c = (seq % 16) + '0';
  1105. if (c > '9') c += 7;
  1106. ns[i--] = c;
  1107. seq /= 16;
  1108. } while (seq);
  1109. ns[i] = '~';
  1110. /* Append the number */
  1111. for (j = 0; j < i && dst[j] != ' '; j++) {
  1112. if (IsDBCS1(dst[j])) {
  1113. if (j == i - 1) break;
  1114. j++;
  1115. }
  1116. }
  1117. do {
  1118. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1119. } while (j < 8);
  1120. }
  1121. #endif
  1122. /*-----------------------------------------------------------------------*/
  1123. /* Calculate sum of an SFN */
  1124. /*-----------------------------------------------------------------------*/
  1125. #if _USE_LFN
  1126. static
  1127. BYTE sum_sfn (
  1128. const BYTE* dir /* Pointer to the SFN entry */
  1129. )
  1130. {
  1131. BYTE sum = 0;
  1132. UINT n = 11;
  1133. do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  1134. return sum;
  1135. }
  1136. #endif
  1137. /*-----------------------------------------------------------------------*/
  1138. /* Directory handling - Find an object in the directory */
  1139. /*-----------------------------------------------------------------------*/
  1140. static
  1141. FRESULT dir_find (
  1142. DIR* dp /* Pointer to the directory object linked to the file name */
  1143. )
  1144. {
  1145. FRESULT res;
  1146. BYTE c, *dir;
  1147. #if _USE_LFN
  1148. BYTE a, ord, sum;
  1149. #endif
  1150. res = dir_sdi(dp, 0); /* Rewind directory object */
  1151. if (res != FR_OK) return res;
  1152. #if _USE_LFN
  1153. ord = sum = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */
  1154. #endif
  1155. do {
  1156. res = move_window(dp->fs, dp->sect);
  1157. if (res != FR_OK) break;
  1158. dir = dp->dir; /* Ptr to the directory entry of current index */
  1159. c = dir[DIR_Name];
  1160. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1161. #if _USE_LFN /* LFN configuration */
  1162. a = dir[DIR_Attr] & AM_MASK;
  1163. if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  1164. ord = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */
  1165. } else {
  1166. if (a == AM_LFN) { /* An LFN entry is found */
  1167. if (dp->lfn) {
  1168. if (c & LLEF) { /* Is it start of LFN sequence? */
  1169. sum = dir[LDIR_Chksum];
  1170. c &= ~LLEF; ord = c; /* LFN start order */
  1171. dp->lfn_idx = dp->index; /* Start index of LFN */
  1172. }
  1173. /* Check validity of the LFN entry and compare it with given name */
  1174. ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dp->lfn, dir)) ? ord - 1 : 0xFF;
  1175. }
  1176. } else { /* An SFN entry is found */
  1177. if (!ord && sum == sum_sfn(dir)) break; /* LFN matched? */
  1178. if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dir, dp->fn, 11)) break; /* SFN matched? */
  1179. ord = 0xFF; dp->lfn_idx = 0xFFFF; /* Reset LFN sequence */
  1180. }
  1181. }
  1182. #else /* Non LFN configuration */
  1183. if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dp->fn, 11)) /* Is it a valid entry? */
  1184. break;
  1185. #endif
  1186. res = dir_next(dp, 0); /* Next entry */
  1187. } while (res == FR_OK);
  1188. return res;
  1189. }
  1190. /*-----------------------------------------------------------------------*/
  1191. /* Read an object from the directory */
  1192. /*-----------------------------------------------------------------------*/
  1193. #if _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2
  1194. static
  1195. FRESULT dir_read (
  1196. DIR* dp, /* Pointer to the directory object */
  1197. int vol /* Filtered by 0:file/directory or 1:volume label */
  1198. )
  1199. {
  1200. FRESULT res;
  1201. BYTE a, c, *dir;
  1202. #if _USE_LFN
  1203. BYTE ord = 0xFF, sum = 0xFF;
  1204. #endif
  1205. res = FR_NO_FILE;
  1206. while (dp->sect) {
  1207. res = move_window(dp->fs, dp->sect);
  1208. if (res != FR_OK) break;
  1209. dir = dp->dir; /* Ptr to the directory entry of current index */
  1210. c = dir[DIR_Name];
  1211. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1212. a = dir[DIR_Attr] & AM_MASK;
  1213. #if _USE_LFN /* LFN configuration */
  1214. if (c == DDEM || (!_FS_RPATH && c == '.') || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
  1215. ord = 0xFF;
  1216. } else {
  1217. if (a == AM_LFN) { /* An LFN entry is found */
  1218. if (c & LLEF) { /* Is it start of LFN sequence? */
  1219. sum = dir[LDIR_Chksum];
  1220. c &= ~LLEF; ord = c;
  1221. dp->lfn_idx = dp->index;
  1222. }
  1223. /* Check LFN validity and capture it */
  1224. ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dp->lfn, dir)) ? ord - 1 : 0xFF;
  1225. } else { /* An SFN entry is found */
  1226. if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN? */
  1227. dp->lfn_idx = 0xFFFF; /* It has no LFN. */
  1228. break;
  1229. }
  1230. }
  1231. #else /* Non LFN configuration */
  1232. if (c != DDEM && (_FS_RPATH || c != '.') && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) /* Is it a valid entry? */
  1233. break;
  1234. #endif
  1235. res = dir_next(dp, 0); /* Next entry */
  1236. if (res != FR_OK) break;
  1237. }
  1238. if (res != FR_OK) dp->sect = 0;
  1239. return res;
  1240. }
  1241. #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
  1242. /*-----------------------------------------------------------------------*/
  1243. /* Register an object to the directory */
  1244. /*-----------------------------------------------------------------------*/
  1245. #if !_FS_READONLY
  1246. static
  1247. FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
  1248. DIR* dp /* Target directory with object name to be created */
  1249. )
  1250. {
  1251. FRESULT res;
  1252. #if _USE_LFN /* LFN configuration */
  1253. UINT n, nent;
  1254. BYTE sn[12], *fn, sum;
  1255. WCHAR *lfn;
  1256. fn = dp->fn; lfn = dp->lfn;
  1257. mem_cpy(sn, fn, 12);
  1258. if (_FS_RPATH && (sn[NSFLAG] & NS_DOT)) /* Cannot create dot entry */
  1259. return FR_INVALID_NAME;
  1260. if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  1261. fn[NSFLAG] = 0; dp->lfn = 0; /* Find only SFN */
  1262. for (n = 1; n < 100; n++) {
  1263. gen_numname(fn, sn, lfn, n); /* Generate a numbered name */
  1264. res = dir_find(dp); /* Check if the name collides with existing SFN */
  1265. if (res != FR_OK) break;
  1266. }
  1267. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  1268. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  1269. fn[NSFLAG] = sn[NSFLAG]; dp->lfn = lfn;
  1270. }
  1271. if (sn[NSFLAG] & NS_LFN) { /* When LFN is to be created, allocate entries for an SFN + LFNs. */
  1272. for (n = 0; lfn[n]; n++) ;
  1273. nent = (n + 25) / 13;
  1274. } else { /* Otherwise allocate an entry for an SFN */
  1275. nent = 1;
  1276. }
  1277. res = dir_alloc(dp, nent); /* Allocate entries */
  1278. if (res == FR_OK && --nent) { /* Set LFN entry if needed */
  1279. res = dir_sdi(dp, dp->index - nent);
  1280. if (res == FR_OK) {
  1281. sum = sum_sfn(dp->fn); /* Sum value of the SFN tied to the LFN */
  1282. do { /* Store LFN entries in bottom first */
  1283. res = move_window(dp->fs, dp->sect);
  1284. if (res != FR_OK) break;
  1285. fit_lfn(dp->lfn, dp->dir, (BYTE)nent, sum);
  1286. dp->fs->wflag = 1;
  1287. res = dir_next(dp, 0); /* Next entry */
  1288. } while (res == FR_OK && --nent);
  1289. }
  1290. }
  1291. #else /* Non LFN configuration */
  1292. res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
  1293. #endif
  1294. if (res == FR_OK) { /* Set SFN entry */
  1295. res = move_window(dp->fs, dp->sect);
  1296. if (res == FR_OK) {
  1297. mem_set(dp->dir, 0, SZ_DIRE); /* Clean the entry */
  1298. mem_cpy(dp->dir, dp->fn, 11); /* Put SFN */
  1299. #if _USE_LFN
  1300. dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
  1301. #endif
  1302. dp->fs->wflag = 1;
  1303. }
  1304. }
  1305. return res;
  1306. }
  1307. #endif /* !_FS_READONLY */
  1308. /*-----------------------------------------------------------------------*/
  1309. /* Remove an object from the directory */
  1310. /*-----------------------------------------------------------------------*/
  1311. #if !_FS_READONLY && !_FS_MINIMIZE
  1312. static
  1313. FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */
  1314. DIR* dp /* Directory object pointing the entry to be removed */
  1315. )
  1316. {
  1317. FRESULT res;
  1318. #if _USE_LFN /* LFN configuration */
  1319. UINT i;
  1320. i = dp->index; /* SFN index */
  1321. res = dir_sdi(dp, (dp->lfn_idx == 0xFFFF) ? i : dp->lfn_idx); /* Goto the SFN or top of the LFN entries */
  1322. if (res == FR_OK) {
  1323. do {
  1324. res = move_window(dp->fs, dp->sect);
  1325. if (res != FR_OK) break;
  1326. mem_set(dp->dir, 0, SZ_DIRE); /* Clear and mark the entry "deleted" */
  1327. *dp->dir = DDEM;
  1328. dp->fs->wflag = 1;
  1329. if (dp->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */
  1330. res = dir_next(dp, 0); /* Next entry */
  1331. } while (res == FR_OK);
  1332. if (res == FR_NO_FILE) res = FR_INT_ERR;
  1333. }
  1334. #else /* Non LFN configuration */
  1335. res = dir_sdi(dp, dp->index);
  1336. if (res == FR_OK) {
  1337. res = move_window(dp->fs, dp->sect);
  1338. if (res == FR_OK) {
  1339. mem_set(dp->dir, 0, SZ_DIRE); /* Clear and mark the entry "deleted" */
  1340. *dp->dir = DDEM;
  1341. dp->fs->wflag = 1;
  1342. }
  1343. }
  1344. #endif
  1345. return res;
  1346. }
  1347. #endif /* !_FS_READONLY */
  1348. /*-----------------------------------------------------------------------*/
  1349. /* Get file information from directory entry */
  1350. /*-----------------------------------------------------------------------*/
  1351. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  1352. static
  1353. void get_fileinfo ( /* No return code */
  1354. DIR* dp, /* Pointer to the directory object */
  1355. FILINFO* fno /* Pointer to the file information to be filled */
  1356. )
  1357. {
  1358. UINT i;
  1359. TCHAR *p, c;
  1360. BYTE *dir;
  1361. #if _USE_LFN
  1362. WCHAR w, *lfn;
  1363. #endif
  1364. p = fno->fname;
  1365. if (dp->sect) { /* Get SFN */
  1366. dir = dp->dir;
  1367. i = 0;
  1368. while (i < 11) { /* Copy name body and extension */
  1369. c = (TCHAR)dir[i++];
  1370. if (c == ' ') continue; /* Skip padding spaces */
  1371. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  1372. if (i == 9) *p++ = '.'; /* Insert a . if extension is exist */
  1373. #if _USE_LFN
  1374. if (IsUpper(c) && (dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY)))
  1375. c += 0x20; /* To lower */
  1376. #if _LFN_UNICODE
  1377. if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dir[i]))
  1378. c = c << 8 | dir[i++];
  1379. c = ff_convert(c, 1); /* OEM -> Unicode */
  1380. if (!c) c = '?';
  1381. #endif
  1382. #endif
  1383. *p++ = c;
  1384. }
  1385. fno->fattrib = dir[DIR_Attr]; /* Attribute */
  1386. fno->fsize = LD_DWORD(dir + DIR_FileSize); /* Size */
  1387. fno->fdate = LD_WORD(dir + DIR_WrtDate); /* Date */
  1388. fno->ftime = LD_WORD(dir + DIR_WrtTime); /* Time */
  1389. }
  1390. *p = 0; /* Terminate SFN string by a \0 */
  1391. #if _USE_LFN
  1392. if (fno->lfname) {
  1393. i = 0; p = fno->lfname;
  1394. if (dp->sect && fno->lfsize && dp->lfn_idx != 0xFFFF) { /* Get LFN if available */
  1395. lfn = dp->lfn;
  1396. while ((w = *lfn++) != 0) { /* Get an LFN character */
  1397. #if !_LFN_UNICODE
  1398. w = ff_convert(w, 0); /* Unicode -> OEM */
  1399. if (!w) { i = 0; break; } /* No LFN if it could not be converted */
  1400. if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC (always false on SBCS cfg) */
  1401. p[i++] = (TCHAR)(w >> 8);
  1402. #endif
  1403. if (i >= fno->lfsize - 1) { i = 0; break; } /* No LFN if buffer overflow */
  1404. p[i++] = (TCHAR)w;
  1405. }
  1406. }
  1407. p[i] = 0; /* Terminate LFN string by a \0 */
  1408. }
  1409. #endif
  1410. }
  1411. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  1412. /*-----------------------------------------------------------------------*/
  1413. /* Pattern matching */
  1414. /*-----------------------------------------------------------------------*/
  1415. #if _USE_FIND && _FS_MINIMIZE <= 1
  1416. static
  1417. WCHAR get_achar ( /* Get a character and advances ptr 1 or 2 */
  1418. const TCHAR** ptr /* Pointer to pointer to the SBCS/DBCS/Unicode string */
  1419. )
  1420. {
  1421. WCHAR chr;
  1422. #if !_LFN_UNICODE
  1423. chr = (BYTE)*(*ptr)++; /* Get a byte */
  1424. if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
  1425. if (IsDBCS1(chr) && IsDBCS2(**ptr)) /* Get DBC 2nd byte if needed */
  1426. chr = chr << 8 | (BYTE)*(*ptr)++;
  1427. #ifdef _EXCVT
  1428. if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
  1429. #endif
  1430. #else
  1431. chr = ff_wtoupper(*(*ptr)++); /* Get a word and to upper */
  1432. #endif
  1433. return chr;
  1434. }
  1435. static
  1436. int pattern_matching ( /* Return value: 0:mismatched, 1:matched */
  1437. const TCHAR* pat, /* Matching pattern */
  1438. const TCHAR* nam, /* String to be tested */
  1439. int skip, /* Number of pre-skip chars (number of ?s) */
  1440. int inf /* Infinite search (* specified) */
  1441. )
  1442. {
  1443. const TCHAR *pp, *np;
  1444. WCHAR pc, nc;
  1445. int nm, nx;
  1446. while (skip--) { /* Pre-skip name chars */
  1447. if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
  1448. }
  1449. if (!*pat && inf) return 1; /* (short circuit) */
  1450. do {
  1451. pp = pat; np = nam; /* Top of pattern and name to match */
  1452. for (;;) {
  1453. if (*pp == '?' || *pp == '*') { /* Wildcard? */
  1454. nm = nx = 0;
  1455. do { /* Analyze the wildcard chars */
  1456. if (*pp++ == '?') nm++; else nx = 1;
  1457. } while (*pp == '?' || *pp == '*');
  1458. if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
  1459. nc = *np; break; /* Branch mismatched */
  1460. }
  1461. pc = get_achar(&pp); /* Get a pattern char */
  1462. nc = get_achar(&np); /* Get a name char */
  1463. if (pc != nc) break; /* Branch mismatched? */
  1464. if (!pc) return 1; /* Branch matched? (matched at end of both strings) */
  1465. }
  1466. get_achar(&nam); /* nam++ */
  1467. } while (inf && nc); /* Retry until end of name if infinite search is specified */
  1468. return 0;
  1469. }
  1470. #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
  1471. /*-----------------------------------------------------------------------*/
  1472. /* Pick a segment and create the object name in directory form */
  1473. /*-----------------------------------------------------------------------*/
  1474. static
  1475. FRESULT create_name (
  1476. DIR* dp, /* Pointer to the directory object */
  1477. const TCHAR** path /* Pointer to pointer to the segment in the path string */
  1478. )
  1479. {
  1480. #if _USE_LFN /* LFN configuration */
  1481. BYTE b, cf;
  1482. WCHAR w, *lfn;
  1483. UINT i, ni, si, di;
  1484. const TCHAR *p;
  1485. /* Create LFN in Unicode */
  1486. for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */
  1487. lfn = dp->lfn;
  1488. si = di = 0;
  1489. for (;;) {
  1490. w = p[si++]; /* Get a character */
  1491. if (w < ' ' || w == '/' || w == '\\') break; /* Break on end of segment */
  1492. if (di >= _MAX_LFN) /* Reject too long name */
  1493. return FR_INVALID_NAME;
  1494. #if !_LFN_UNICODE
  1495. w &= 0xFF;
  1496. if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1497. b = (BYTE)p[si++]; /* Get 2nd byte */
  1498. w = (w << 8) + b; /* Create a DBC */
  1499. if (!IsDBCS2(b))
  1500. return FR_INVALID_NAME; /* Reject invalid sequence */
  1501. }
  1502. w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
  1503. if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  1504. #endif
  1505. if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal characters for LFN */
  1506. return FR_INVALID_NAME;
  1507. lfn[di++] = w; /* Store the Unicode character */
  1508. }
  1509. *path = &p[si]; /* Return pointer to the next segment */
  1510. cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
  1511. #if _FS_RPATH
  1512. if ((di == 1 && lfn[di - 1] == '.') || /* Is this a dot entry? */
  1513. (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) {
  1514. lfn[di] = 0;
  1515. for (i = 0; i < 11; i++)
  1516. dp->fn[i] = (i < di) ? '.' : ' ';
  1517. dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
  1518. return FR_OK;
  1519. }
  1520. #endif
  1521. while (di) { /* Strip trailing spaces and dots */
  1522. w = lfn[di - 1];
  1523. if (w != ' ' && w != '.') break;
  1524. di--;
  1525. }
  1526. if (!di) return FR_INVALID_NAME; /* Reject nul string */
  1527. lfn[di] = 0; /* LFN is created */
  1528. /* Create SFN in directory form */
  1529. mem_set(dp->fn, ' ', 11);
  1530. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  1531. if (si) cf |= NS_LOSS | NS_LFN;
  1532. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  1533. b = i = 0; ni = 8;
  1534. for (;;) {
  1535. w = lfn[si++]; /* Get an LFN character */
  1536. if (!w) break; /* Break on end of the LFN */
  1537. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  1538. cf |= NS_LOSS | NS_LFN; continue;
  1539. }
  1540. if (i >= ni || si == di) { /* Extension or end of SFN */
  1541. if (ni == 11) { /* Long extension */
  1542. cf |= NS_LOSS | NS_LFN; break;
  1543. }
  1544. if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
  1545. if (si > di) break; /* No extension */
  1546. si = di; i = 8; ni = 11; /* Enter extension section */
  1547. b <<= 2; continue;
  1548. }
  1549. if (w >= 0x80) { /* Non ASCII character */
  1550. #ifdef _EXCVT
  1551. w = ff_convert(w, 0); /* Unicode -> OEM code */
  1552. if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */
  1553. #else
  1554. w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
  1555. #endif
  1556. cf |= NS_LFN; /* Force create LFN entry */
  1557. }
  1558. if (_DF1S && w >= 0x100) { /* DBC (always false at SBCS cfg) */
  1559. if (i >= ni - 1) {
  1560. cf |= NS_LOSS | NS_LFN; i = ni; continue;
  1561. }
  1562. dp->fn[i++] = (BYTE)(w >> 8);
  1563. } else { /* SBC */
  1564. if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */
  1565. w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  1566. } else {
  1567. if (IsUpper(w)) { /* ASCII large capital */
  1568. b |= 2;
  1569. } else {
  1570. if (IsLower(w)) { /* ASCII small capital */
  1571. b |= 1; w -= 0x20;
  1572. }
  1573. }
  1574. }
  1575. }
  1576. dp->fn[i++] = (BYTE)w;
  1577. }
  1578. if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with deleted mark, replace it with RDDEM */
  1579. if (ni == 8) b <<= 2;
  1580. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */
  1581. cf |= NS_LFN;
  1582. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
  1583. if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
  1584. if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
  1585. }
  1586. dp->fn[NSFLAG] = cf; /* SFN is created */
  1587. return FR_OK;
  1588. #else /* Non-LFN configuration */
  1589. BYTE b, c, d, *sfn;
  1590. UINT ni, si, i;
  1591. const char *p;
  1592. /* Create file name in directory form */
  1593. for (p = *path; *p == '/' || *p == '\\'; p++) ; /* Strip duplicated separator */
  1594. sfn = dp->fn;
  1595. mem_set(sfn, ' ', 11);
  1596. si = i = b = 0; ni = 8;
  1597. #if _FS_RPATH
  1598. if (p[si] == '.') { /* Is this a dot entry? */
  1599. for (;;) {
  1600. c = (BYTE)p[si++];
  1601. if (c != '.' || si >= 3) break;
  1602. sfn[i++] = c;
  1603. }
  1604. if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  1605. *path = &p[si]; /* Return pointer to the next segment */
  1606. sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of path */
  1607. return FR_OK;
  1608. }
  1609. #endif
  1610. for (;;) {
  1611. c = (BYTE)p[si++];
  1612. if (c <= ' ' || c == '/' || c == '\\') break; /* Break on end of segment */
  1613. if (c == '.' || i >= ni) {
  1614. if (ni != 8 || c != '.') return FR_INVALID_NAME;
  1615. i = 8; ni = 11;
  1616. b <<= 2; continue;
  1617. }
  1618. if (c >= 0x80) { /* Extended character? */
  1619. b |= 3; /* Eliminate NT flag */
  1620. #ifdef _EXCVT
  1621. c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */
  1622. #else
  1623. #if !_DF1S
  1624. return FR_INVALID_NAME; /* Reject extended characters (ASCII cfg) */
  1625. #endif
  1626. #endif
  1627. }
  1628. if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  1629. d = (BYTE)p[si++]; /* Get 2nd byte */
  1630. if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */
  1631. return FR_INVALID_NAME;
  1632. sfn[i++] = c;
  1633. sfn[i++] = d;
  1634. } else { /* SBC */
  1635. if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) /* Reject illegal chrs for SFN */
  1636. return FR_INVALID_NAME;
  1637. if (IsUpper(c)) { /* ASCII large capital? */
  1638. b |= 2;
  1639. } else {
  1640. if (IsLower(c)) { /* ASCII small capital? */
  1641. b |= 1; c -= 0x20;
  1642. }
  1643. }
  1644. sfn[i++] = c;
  1645. }
  1646. }
  1647. *path = &p[si]; /* Return pointer to the next segment */
  1648. c = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */
  1649. if (!i) return FR_INVALID_NAME; /* Reject nul string */
  1650. if (sfn[0] == DDEM) sfn[0] = RDDEM; /* When first character collides with DDEM, replace it with RDDEM */
  1651. if (ni == 8) b <<= 2;
  1652. if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Name extension has only small capital) */
  1653. if ((b & 0x0C) == 0x04) c |= NS_BODY; /* NT flag (Name body has only small capital) */
  1654. sfn[NSFLAG] = c; /* Store NT flag, File name is created */
  1655. return FR_OK;
  1656. #endif
  1657. }
  1658. /*-----------------------------------------------------------------------*/
  1659. /* Follow a file path */
  1660. /*-----------------------------------------------------------------------*/
  1661. static
  1662. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  1663. DIR* dp, /* Directory object to return last directory and found object */
  1664. const TCHAR* path /* Full-path string to find a file or directory */
  1665. )
  1666. {
  1667. FRESULT res;
  1668. BYTE *dir, ns;
  1669. #if _FS_RPATH
  1670. if (*path == '/' || *path == '\\') { /* There is a heading separator */
  1671. path++; dp->sclust = 0; /* Strip it and start from the root directory */
  1672. } else { /* No heading separator */
  1673. dp->sclust = dp->fs->cdir; /* Start from the current directory */
  1674. }
  1675. #else
  1676. if (*path == '/' || *path == '\\') /* Strip heading separator if exist */
  1677. path++;
  1678. dp->sclust = 0; /* Always start from the root directory */
  1679. #endif
  1680. if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
  1681. res = dir_sdi(dp, 0);
  1682. dp->dir = 0;
  1683. } else { /* Follow path */
  1684. for (;;) {
  1685. res = create_name(dp, &path); /* Get a segment name of the path */
  1686. if (res != FR_OK) break;
  1687. res = dir_find(dp); /* Find an object with the sagment name */
  1688. ns = dp->fn[NSFLAG];
  1689. if (res != FR_OK) { /* Failed to find the object */
  1690. if (res == FR_NO_FILE) { /* Object is not found */
  1691. if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, */
  1692. dp->sclust = 0; dp->dir = 0; /* it is the root directory and stay there */
  1693. if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
  1694. res = FR_OK; /* Ended at the root directroy. Function completed. */
  1695. } else { /* Could not find the object */
  1696. if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
  1697. }
  1698. }
  1699. break;
  1700. }
  1701. if (ns & NS_LAST) break; /* Last segment matched. Function completed. */
  1702. dir = dp->dir; /* Follow the sub-directory */
  1703. if (!(dir[DIR_Attr] & AM_DIR)) { /* It is not a sub-directory and cannot follow */
  1704. res = FR_NO_PATH; break;
  1705. }
  1706. dp->sclust = ld_clust(dp->fs, dir);
  1707. }
  1708. }
  1709. return res;
  1710. }
  1711. /*-----------------------------------------------------------------------*/
  1712. /* Get logical drive number from path name */
  1713. /*-----------------------------------------------------------------------*/
  1714. static
  1715. int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
  1716. const TCHAR** path /* Pointer to pointer to the path name */
  1717. )
  1718. {
  1719. const TCHAR *tp, *tt;
  1720. UINT i;
  1721. int vol = -1;
  1722. #if _STR_VOLUME_ID /* Find string drive id */
  1723. static const char* const str[] = {_VOLUME_STRS};
  1724. const char *sp;
  1725. char c;
  1726. TCHAR tc;
  1727. #endif
  1728. if (*path) { /* If the pointer is not a null */
  1729. for (tt = *path; (UINT)*tt >= (_USE_LFN ? ' ' : '!') && *tt != ':'; tt++) ; /* Find ':' in the path */
  1730. if (*tt == ':') { /* If a ':' is exist in the path name */
  1731. tp = *path;
  1732. i = *tp++ - '0';
  1733. if (i < 10 && tp == tt) { /* Is there a numeric drive id? */
  1734. if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
  1735. vol = (int)i;
  1736. *path = ++tt;
  1737. }
  1738. }
  1739. #if _STR_VOLUME_ID
  1740. else { /* No numeric drive number, find string drive id */
  1741. i = 0; tt++;
  1742. do {
  1743. sp = str[i]; tp = *path;
  1744. do { /* Compare a string drive id with path name */
  1745. c = *sp++; tc = *tp++;
  1746. if (IsLower(tc)) tc -= 0x20;
  1747. } while (c && (TCHAR)c == tc);
  1748. } while ((c || tp != tt) && ++i < _VOLUMES); /* Repeat for each id until pattern match */
  1749. if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
  1750. vol = (int)i;
  1751. *path = tt;
  1752. }
  1753. }
  1754. #endif
  1755. return vol;
  1756. }
  1757. #if _FS_RPATH && _VOLUMES >= 2
  1758. vol = CurrVol; /* Current drive */
  1759. #else
  1760. vol = 0; /* Drive 0 */
  1761. #endif
  1762. }
  1763. return vol;
  1764. }
  1765. /*-----------------------------------------------------------------------*/
  1766. /* Load a sector and check if it is an FAT boot sector */
  1767. /*-----------------------------------------------------------------------*/
  1768. static
  1769. BYTE check_fs ( /* 0:FAT boor sector, 1:Valid boor sector but not FAT, 2:Not a boot sector, 3:Disk error */
  1770. FATFS* fs, /* File system object */
  1771. DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */
  1772. )
  1773. {
  1774. fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */
  1775. if (move_window(fs, sect) != FR_OK) /* Load boot record */
  1776. return 3;
  1777. if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */
  1778. return 2;
  1779. if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
  1780. return 0;
  1781. if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146) /* Check "FAT" string */
  1782. return 0;
  1783. return 1;
  1784. }
  1785. /*-----------------------------------------------------------------------*/
  1786. /* Find logical drive and check if the volume is mounted */
  1787. /*-----------------------------------------------------------------------*/
  1788. static
  1789. FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
  1790. FATFS** rfs, /* Pointer to pointer to the found file system object */
  1791. const TCHAR** path, /* Pointer to pointer to the path name (drive number) */
  1792. BYTE wmode /* !=0: Check write protection for write access */
  1793. )
  1794. {
  1795. BYTE fmt, *pt;
  1796. int vol;
  1797. DSTATUS stat;
  1798. DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];
  1799. WORD nrsv;
  1800. FATFS *fs;
  1801. UINT i;
  1802. /* Get logical drive number from the path name */
  1803. *rfs = 0;
  1804. vol = get_ldnumber(path);
  1805. if (vol < 0) return FR_INVALID_DRIVE;
  1806. /* Check if the file system object is valid or not */
  1807. fs = FatFs[vol]; /* Get pointer to the file system object */
  1808. if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
  1809. ENTER_FF(fs); /* Lock the volume */
  1810. *rfs = fs; /* Return pointer to the file system object */
  1811. if (fs->fs_type) { /* If the volume has been mounted */
  1812. stat = disk_status(fs->drv);
  1813. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
  1814. if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check write protection if needed */
  1815. return FR_WRITE_PROTECTED;
  1816. return FR_OK; /* The file system object is valid */
  1817. }
  1818. }
  1819. /* The file system object is not valid. */
  1820. /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
  1821. fs->fs_type = 0; /* Clear the file system object */
  1822. fs->drv = LD2PD(vol); /* Bind the logical drive and a physical drive */
  1823. stat = disk_initialize(fs->drv); /* Initialize the physical drive */
  1824. if (stat & STA_NOINIT) /* Check if the initialization succeeded */
  1825. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  1826. if (!_FS_READONLY && wmode && (stat & STA_PROTECT)) /* Check disk write protection if needed */
  1827. return FR_WRITE_PROTECTED;
  1828. #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
  1829. if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK
  1830. || SS(fs) < _MIN_SS || SS(fs) > _MAX_SS) return FR_DISK_ERR;
  1831. #endif
  1832. /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
  1833. bsect = 0;
  1834. fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT boot sector as SFD */
  1835. if (fmt == 1 || (!fmt && (LD2PT(vol)))) { /* Not an FAT boot sector or forced partition number */
  1836. for (i = 0; i < 4; i++) { /* Get partition offset */
  1837. pt = fs->win + MBR_Table + i * SZ_PTE;
  1838. br[i] = pt[4] ? LD_DWORD(&pt[8]) : 0;
  1839. }
  1840. i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */
  1841. if (i) i--;
  1842. do { /* Find an FAT volume */
  1843. bsect = br[i];
  1844. fmt = bsect ? check_fs(fs, bsect) : 2; /* Check the partition */
  1845. } while (!LD2PT(vol) && fmt && ++i < 4);
  1846. }
  1847. if (fmt == 3) return FR_DISK_ERR; /* An error occured in the disk I/O layer */
  1848. if (fmt) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  1849. /* An FAT volume is found. Following code initializes the file system object */
  1850. if (LD_WORD(fs->win + BPB_BytsPerSec) != SS(fs)) /* (BPB_BytsPerSec must be equal to the physical sector size) */
  1851. return FR_NO_FILESYSTEM;
  1852. fasize = LD_WORD(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
  1853. if (!fasize) fasize = LD_DWORD(fs->win + BPB_FATSz32);
  1854. fs->fsize = fasize;
  1855. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */
  1856. if (fs->n_fats != 1 && fs->n_fats != 2) /* (Must be 1 or 2) */
  1857. return FR_NO_FILESYSTEM;
  1858. fasize *= fs->n_fats; /* Number of sectors for FAT area */
  1859. fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */
  1860. if (!fs->csize || (fs->csize & (fs->csize - 1))) /* (Must be power of 2) */
  1861. return FR_NO_FILESYSTEM;
  1862. fs->n_rootdir = LD_WORD(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
  1863. if (fs->n_rootdir % (SS(fs) / SZ_DIRE)) /* (Must be sector aligned) */
  1864. return FR_NO_FILESYSTEM;
  1865. tsect = LD_WORD(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
  1866. if (!tsect) tsect = LD_DWORD(fs->win + BPB_TotSec32);
  1867. nrsv = LD_WORD(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
  1868. if (!nrsv) return FR_NO_FILESYSTEM; /* (Must not be 0) */
  1869. /* Determine the FAT sub type */
  1870. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIRE); /* RSV + FAT + DIR */
  1871. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  1872. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  1873. if (!nclst) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  1874. fmt = FS_FAT12;
  1875. if (nclst >= MIN_FAT16) fmt = FS_FAT16;
  1876. if (nclst >= MIN_FAT32) fmt = FS_FAT32;
  1877. /* Boundaries and Limits */
  1878. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  1879. fs->volbase = bsect; /* Volume start sector */
  1880. fs->fatbase = bsect + nrsv; /* FAT start sector */
  1881. fs->database = bsect + sysect; /* Data start sector */
  1882. if (fmt == FS_FAT32) {
  1883. if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  1884. fs->dirbase = LD_DWORD(fs->win + BPB_RootClus); /* Root directory start cluster */
  1885. szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
  1886. } else {
  1887. if (!fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */
  1888. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  1889. szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
  1890. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  1891. }
  1892. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) /* (BPB_FATSz must not be less than the size needed) */
  1893. return FR_NO_FILESYSTEM;
  1894. #if !_FS_READONLY
  1895. /* Initialize cluster allocation information */
  1896. fs->last_clust = fs->free_clust = 0xFFFFFFFF;
  1897. /* Get fsinfo if available */
  1898. fs->fsi_flag = 0x80;
  1899. #if (_FS_NOFSINFO & 3) != 3
  1900. if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo is 1 */
  1901. && LD_WORD(fs->win + BPB_FSInfo) == 1
  1902. && move_window(fs, bsect + 1) == FR_OK)
  1903. {
  1904. fs->fsi_flag = 0;
  1905. if (LD_WORD(fs->win + BS_55AA) == 0xAA55 /* Load FSINFO data if available */
  1906. && LD_DWORD(fs->win + FSI_LeadSig) == 0x41615252
  1907. && LD_DWORD(fs->win + FSI_StrucSig) == 0x61417272)
  1908. {
  1909. #if (_FS_NOFSINFO & 1) == 0
  1910. fs->free_clust = LD_DWORD(fs->win + FSI_Free_Count);
  1911. #endif
  1912. #if (_FS_NOFSINFO & 2) == 0
  1913. fs->last_clust = LD_DWORD(fs->win + FSI_Nxt_Free);
  1914. #endif
  1915. }
  1916. }
  1917. #endif
  1918. #endif
  1919. fs->fs_type = fmt; /* FAT sub-type */
  1920. fs->id = ++Fsid; /* File system mount ID */
  1921. #if _FS_RPATH
  1922. fs->cdir = 0; /* Set current directory to root */
  1923. #endif
  1924. #if _FS_LOCK /* Clear file lock semaphores */
  1925. clear_lock(fs);
  1926. #endif
  1927. return FR_OK;
  1928. }
  1929. /*-----------------------------------------------------------------------*/
  1930. /* Check if the file/directory object is valid or not */
  1931. /*-----------------------------------------------------------------------*/
  1932. static
  1933. FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */
  1934. void* obj /* Pointer to the object FIL/DIR to check validity */
  1935. )
  1936. {
  1937. FIL *fil = (FIL*)obj; /* Assuming offset of .fs and .id in the FIL/DIR structure is identical */
  1938. if (!fil || !fil->fs || !fil->fs->fs_type || fil->fs->id != fil->id)
  1939. return FR_INVALID_OBJECT;
  1940. ENTER_FF(fil->fs); /* Lock file system */
  1941. if (disk_status(fil->fs->drv) & STA_NOINIT)
  1942. return FR_NOT_READY;
  1943. return FR_OK;
  1944. }
  1945. /*--------------------------------------------------------------------------
  1946. Public Functions
  1947. --------------------------------------------------------------------------*/
  1948. /*-----------------------------------------------------------------------*/
  1949. /* Mount/Unmount a Logical Drive */
  1950. /*-----------------------------------------------------------------------*/
  1951. FRESULT f_mount (
  1952. FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/
  1953. const TCHAR* path, /* Logical drive number to be mounted/unmounted */
  1954. BYTE opt /* 0:Do not mount (delayed mount), 1:Mount immediately */
  1955. )
  1956. {
  1957. FATFS *cfs;
  1958. int vol;
  1959. FRESULT res;
  1960. const TCHAR *rp = path;
  1961. vol = get_ldnumber(&rp);
  1962. if (vol < 0) return FR_INVALID_DRIVE;
  1963. cfs = FatFs[vol]; /* Pointer to fs object */
  1964. if (cfs) {
  1965. #if _FS_LOCK
  1966. clear_lock(cfs);
  1967. #endif
  1968. #if _FS_REENTRANT /* Discard sync object of the current volume */
  1969. if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
  1970. #endif
  1971. cfs->fs_type = 0; /* Clear old fs object */
  1972. }
  1973. if (fs) {
  1974. fs->fs_type = 0; /* Clear new fs object */
  1975. #if _FS_REENTRANT /* Create sync object for the new volume */
  1976. if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
  1977. #endif
  1978. }
  1979. FatFs[vol] = fs; /* Register new fs object */
  1980. if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
  1981. res = find_volume(&fs, &path, 0); /* Force mounted the volume */
  1982. LEAVE_FF(fs, res);
  1983. }
  1984. /*-----------------------------------------------------------------------*/
  1985. /* Open or Create a File */
  1986. /*-----------------------------------------------------------------------*/
  1987. FRESULT f_open (
  1988. FIL* fp, /* Pointer to the blank file object */
  1989. const TCHAR* path, /* Pointer to the file name */
  1990. BYTE mode /* Access mode and file open mode flags */
  1991. )
  1992. {
  1993. FRESULT res;
  1994. DIR dj;
  1995. BYTE *dir;
  1996. DEFINE_NAMEBUF;
  1997. #if !_FS_READONLY
  1998. DWORD dw, cl;
  1999. #endif
  2000. if (!fp) return FR_INVALID_OBJECT;
  2001. fp->fs = 0; /* Clear file object */
  2002. /* Get logical drive number */
  2003. #if !_FS_READONLY
  2004. mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;
  2005. res = find_volume(&dj.fs, &path, (BYTE)(mode & ~FA_READ));
  2006. #else
  2007. mode &= FA_READ;
  2008. res = find_volume(&dj.fs, &path, 0);
  2009. #endif
  2010. if (res == FR_OK) {
  2011. INIT_BUF(dj);
  2012. res = follow_path(&dj, path); /* Follow the file path */
  2013. dir = dj.dir;
  2014. #if !_FS_READONLY /* R/W configuration */
  2015. if (res == FR_OK) {
  2016. if (!dir) /* Default directory itself */
  2017. res = FR_INVALID_NAME;
  2018. #if _FS_LOCK
  2019. else
  2020. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2021. #endif
  2022. }
  2023. /* Create or Open a file */
  2024. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  2025. if (res != FR_OK) { /* No file, create new */
  2026. if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
  2027. #if _FS_LOCK
  2028. res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  2029. #else
  2030. res = dir_register(&dj);
  2031. #endif
  2032. mode |= FA_CREATE_ALWAYS; /* File is created */
  2033. dir = dj.dir; /* New entry */
  2034. }
  2035. else { /* Any object is already existing */
  2036. if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
  2037. res = FR_DENIED;
  2038. } else {
  2039. if (mode & FA_CREATE_NEW) /* Cannot create as new file */
  2040. res = FR_EXIST;
  2041. }
  2042. }
  2043. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
  2044. dw = GET_FATTIME(); /* Created time */
  2045. ST_DWORD(dir + DIR_CrtTime, dw);
  2046. dir[DIR_Attr] = 0; /* Reset attribute */
  2047. ST_DWORD(dir + DIR_FileSize, 0);/* size = 0 */
  2048. cl = ld_clust(dj.fs, dir); /* Get start cluster */
  2049. st_clust(dir, 0); /* cluster = 0 */
  2050. dj.fs->wflag = 1;
  2051. if (cl) { /* Remove the cluster chain if exist */
  2052. dw = dj.fs->winsect;
  2053. res = remove_chain(dj.fs, cl);
  2054. if (res == FR_OK) {
  2055. dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */
  2056. res = move_window(dj.fs, dw);
  2057. }
  2058. }
  2059. }
  2060. }
  2061. else { /* Open an existing file */
  2062. if (res == FR_OK) { /* Follow succeeded */
  2063. if (dir[DIR_Attr] & AM_DIR) { /* It is a directory */
  2064. res = FR_NO_FILE;
  2065. } else {
  2066. if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
  2067. res = FR_DENIED;
  2068. }
  2069. }
  2070. }
  2071. if (res == FR_OK) {
  2072. if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
  2073. mode |= FA__WRITTEN;
  2074. fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */
  2075. fp->dir_ptr = dir;
  2076. #if _FS_LOCK
  2077. fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2078. if (!fp->lockid) res = FR_INT_ERR;
  2079. #endif
  2080. }
  2081. #else /* R/O configuration */
  2082. if (res == FR_OK) { /* Follow succeeded */
  2083. dir = dj.dir;
  2084. if (!dir) { /* Current directory itself */
  2085. res = FR_INVALID_NAME;
  2086. } else {
  2087. if (dir[DIR_Attr] & AM_DIR) /* It is a directory */
  2088. res = FR_NO_FILE;
  2089. }
  2090. }
  2091. #endif
  2092. FREE_BUF();
  2093. if (res == FR_OK) {
  2094. fp->flag = mode; /* File access mode */
  2095. fp->err = 0; /* Clear error flag */
  2096. fp->sclust = ld_clust(dj.fs, dir); /* File start cluster */
  2097. fp->fsize = LD_DWORD(dir + DIR_FileSize); /* File size */
  2098. fp->fptr = 0; /* File pointer */
  2099. fp->dsect = 0;
  2100. #if _USE_FASTSEEK
  2101. fp->cltbl = 0; /* Normal seek mode */
  2102. #endif
  2103. fp->fs = dj.fs; /* Validate file object */
  2104. fp->id = fp->fs->id;
  2105. }
  2106. }
  2107. LEAVE_FF(dj.fs, res);
  2108. }
  2109. /*-----------------------------------------------------------------------*/
  2110. /* Read File */
  2111. /*-----------------------------------------------------------------------*/
  2112. FRESULT f_read (
  2113. FIL* fp, /* Pointer to the file object */
  2114. void* buff, /* Pointer to data buffer */
  2115. UINT btr, /* Number of bytes to read */
  2116. UINT* br /* Pointer to number of bytes read */
  2117. )
  2118. {
  2119. FRESULT res;
  2120. DWORD clst, sect, remain;
  2121. UINT rcnt, cc;
  2122. BYTE csect, *rbuff = (BYTE*)buff;
  2123. *br = 0; /* Clear read byte counter */
  2124. res = validate(fp); /* Check validity */
  2125. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2126. if (fp->err) /* Check error */
  2127. LEAVE_FF(fp->fs, (FRESULT)fp->err);
  2128. if (!(fp->flag & FA_READ)) /* Check access mode */
  2129. LEAVE_FF(fp->fs, FR_DENIED);
  2130. remain = fp->fsize - fp->fptr;
  2131. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2132. for ( ; btr; /* Repeat until all data read */
  2133. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  2134. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  2135. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  2136. if (!csect) { /* On the cluster boundary? */
  2137. if (fp->fptr == 0) { /* On the top of the file? */
  2138. clst = fp->sclust; /* Follow from the origin */
  2139. } else { /* Middle or end of the file */
  2140. #if _USE_FASTSEEK
  2141. if (fp->cltbl)
  2142. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2143. else
  2144. #endif
  2145. clst = get_fat(fp->fs, fp->clust); /* Follow cluster chain on the FAT */
  2146. }
  2147. if (clst < 2) ABORT(fp->fs, FR_INT_ERR);
  2148. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2149. fp->clust = clst; /* Update current cluster */
  2150. }
  2151. sect = clust2sect(fp->fs, fp->clust); /* Get current sector */
  2152. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2153. sect += csect;
  2154. cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */
  2155. if (cc) { /* Read maximum contiguous sectors directly */
  2156. if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  2157. cc = fp->fs->csize - csect;
  2158. if (disk_read(fp->fs->drv, rbuff, sect, cc) != RES_OK)
  2159. ABORT(fp->fs, FR_DISK_ERR);
  2160. #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  2161. #if _FS_TINY
  2162. if (fp->fs->wflag && fp->fs->winsect - sect < cc)
  2163. mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));
  2164. #else
  2165. if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)
  2166. mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));
  2167. #endif
  2168. #endif
  2169. rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  2170. continue;
  2171. }
  2172. #if !_FS_TINY
  2173. if (fp->dsect != sect) { /* Load data sector if not in cache */
  2174. #if !_FS_READONLY
  2175. if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */
  2176. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2177. ABORT(fp->fs, FR_DISK_ERR);
  2178. fp->flag &= ~FA__DIRTY;
  2179. }
  2180. #endif
  2181. if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK) /* Fill sector cache */
  2182. ABORT(fp->fs, FR_DISK_ERR);
  2183. }
  2184. #endif
  2185. fp->dsect = sect;
  2186. }
  2187. rcnt = SS(fp->fs) - ((UINT)fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */
  2188. if (rcnt > btr) rcnt = btr;
  2189. #if _FS_TINY
  2190. if (move_window(fp->fs, fp->dsect) != FR_OK) /* Move sector window */
  2191. ABORT(fp->fs, FR_DISK_ERR);
  2192. mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  2193. #else
  2194. mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */
  2195. #endif
  2196. }
  2197. LEAVE_FF(fp->fs, FR_OK);
  2198. }
  2199. #if !_FS_READONLY
  2200. /*-----------------------------------------------------------------------*/
  2201. /* Write File */
  2202. /*-----------------------------------------------------------------------*/
  2203. FRESULT f_write (
  2204. FIL* fp, /* Pointer to the file object */
  2205. const void *buff, /* Pointer to the data to be written */
  2206. UINT btw, /* Number of bytes to write */
  2207. UINT* bw /* Pointer to number of bytes written */
  2208. )
  2209. {
  2210. FRESULT res;
  2211. DWORD clst, sect;
  2212. UINT wcnt, cc;
  2213. const BYTE *wbuff = (const BYTE*)buff;
  2214. BYTE csect;
  2215. *bw = 0; /* Clear write byte counter */
  2216. res = validate(fp); /* Check validity */
  2217. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2218. if (fp->err) /* Check error */
  2219. LEAVE_FF(fp->fs, (FRESULT)fp->err);
  2220. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  2221. LEAVE_FF(fp->fs, FR_DENIED);
  2222. if (fp->fptr + btw < fp->fptr) btw = 0; /* File size cannot reach 4GB */
  2223. for ( ; btw; /* Repeat until all data written */
  2224. wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
  2225. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  2226. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  2227. if (!csect) { /* On the cluster boundary? */
  2228. if (fp->fptr == 0) { /* On the top of the file? */
  2229. clst = fp->sclust; /* Follow from the origin */
  2230. if (clst == 0) /* When no cluster is allocated, */
  2231. clst = create_chain(fp->fs, 0); /* Create a new cluster chain */
  2232. } else { /* Middle or end of the file */
  2233. #if _USE_FASTSEEK
  2234. if (fp->cltbl)
  2235. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2236. else
  2237. #endif
  2238. clst = create_chain(fp->fs, fp->clust); /* Follow or stretch cluster chain on the FAT */
  2239. }
  2240. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  2241. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2242. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2243. fp->clust = clst; /* Update current cluster */
  2244. if (fp->sclust == 0) fp->sclust = clst; /* Set start cluster if the first write */
  2245. }
  2246. #if _FS_TINY
  2247. if (fp->fs->winsect == fp->dsect && sync_window(fp->fs)) /* Write-back sector cache */
  2248. ABORT(fp->fs, FR_DISK_ERR);
  2249. #else
  2250. if (fp->flag & FA__DIRTY) { /* Write-back sector cache */
  2251. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2252. ABORT(fp->fs, FR_DISK_ERR);
  2253. fp->flag &= ~FA__DIRTY;
  2254. }
  2255. #endif
  2256. sect = clust2sect(fp->fs, fp->clust); /* Get current sector */
  2257. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  2258. sect += csect;
  2259. cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */
  2260. if (cc) { /* Write maximum contiguous sectors directly */
  2261. if (csect + cc > fp->fs->csize) /* Clip at cluster boundary */
  2262. cc = fp->fs->csize - csect;
  2263. if (disk_write(fp->fs->drv, wbuff, sect, cc) != RES_OK)
  2264. ABORT(fp->fs, FR_DISK_ERR);
  2265. #if _FS_MINIMIZE <= 2
  2266. #if _FS_TINY
  2267. if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2268. mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));
  2269. fp->fs->wflag = 0;
  2270. }
  2271. #else
  2272. if (fp->dsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  2273. mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
  2274. fp->flag &= ~FA__DIRTY;
  2275. }
  2276. #endif
  2277. #endif
  2278. wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */
  2279. continue;
  2280. }
  2281. #if _FS_TINY
  2282. if (fp->fptr >= fp->fsize) { /* Avoid silly cache filling at growing edge */
  2283. if (sync_window(fp->fs)) ABORT(fp->fs, FR_DISK_ERR);
  2284. fp->fs->winsect = sect;
  2285. }
  2286. #else
  2287. if (fp->dsect != sect) { /* Fill sector cache with file data */
  2288. if (fp->fptr < fp->fsize &&
  2289. disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)
  2290. ABORT(fp->fs, FR_DISK_ERR);
  2291. }
  2292. #endif
  2293. fp->dsect = sect;
  2294. }
  2295. wcnt = SS(fp->fs) - ((UINT)fp->fptr % SS(fp->fs));/* Put partial sector into file I/O buffer */
  2296. if (wcnt > btw) wcnt = btw;
  2297. #if _FS_TINY
  2298. if (move_window(fp->fs, fp->dsect) != FR_OK) /* Move sector window */
  2299. ABORT(fp->fs, FR_DISK_ERR);
  2300. mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  2301. fp->fs->wflag = 1;
  2302. #else
  2303. mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */
  2304. fp->flag |= FA__DIRTY;
  2305. #endif
  2306. }
  2307. if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */
  2308. fp->flag |= FA__WRITTEN; /* Set file change flag */
  2309. LEAVE_FF(fp->fs, FR_OK);
  2310. }
  2311. /*-----------------------------------------------------------------------*/
  2312. /* Synchronize the File */
  2313. /*-----------------------------------------------------------------------*/
  2314. FRESULT f_sync (
  2315. FIL* fp /* Pointer to the file object */
  2316. )
  2317. {
  2318. FRESULT res;
  2319. DWORD tm;
  2320. BYTE *dir;
  2321. res = validate(fp); /* Check validity of the object */
  2322. if (res == FR_OK) {
  2323. if (fp->flag & FA__WRITTEN) { /* Has the file been written? */
  2324. /* Write-back dirty buffer */
  2325. #if !_FS_TINY
  2326. if (fp->flag & FA__DIRTY) {
  2327. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2328. LEAVE_FF(fp->fs, FR_DISK_ERR);
  2329. fp->flag &= ~FA__DIRTY;
  2330. }
  2331. #endif
  2332. /* Update the directory entry */
  2333. res = move_window(fp->fs, fp->dir_sect);
  2334. if (res == FR_OK) {
  2335. dir = fp->dir_ptr;
  2336. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  2337. ST_DWORD(dir + DIR_FileSize, fp->fsize); /* Update file size */
  2338. st_clust(dir, fp->sclust); /* Update start cluster */
  2339. tm = GET_FATTIME(); /* Update updated time */
  2340. ST_DWORD(dir + DIR_WrtTime, tm);
  2341. ST_WORD(dir + DIR_LstAccDate, 0);
  2342. fp->flag &= ~FA__WRITTEN;
  2343. fp->fs->wflag = 1;
  2344. res = sync_fs(fp->fs);
  2345. }
  2346. }
  2347. }
  2348. LEAVE_FF(fp->fs, res);
  2349. }
  2350. #endif /* !_FS_READONLY */
  2351. /*-----------------------------------------------------------------------*/
  2352. /* Close File */
  2353. /*-----------------------------------------------------------------------*/
  2354. FRESULT f_close (
  2355. FIL *fp /* Pointer to the file object to be closed */
  2356. )
  2357. {
  2358. FRESULT res;
  2359. #if !_FS_READONLY
  2360. res = f_sync(fp); /* Flush cached data */
  2361. if (res == FR_OK)
  2362. #endif
  2363. {
  2364. res = validate(fp); /* Lock volume */
  2365. if (res == FR_OK) {
  2366. #if _FS_REENTRANT
  2367. FATFS *fs = fp->fs;
  2368. #endif
  2369. #if _FS_LOCK
  2370. res = dec_lock(fp->lockid); /* Decrement file open counter */
  2371. if (res == FR_OK)
  2372. #endif
  2373. fp->fs = 0; /* Invalidate file object */
  2374. #if _FS_REENTRANT
  2375. unlock_fs(fs, FR_OK); /* Unlock volume */
  2376. #endif
  2377. }
  2378. }
  2379. return res;
  2380. }
  2381. /*-----------------------------------------------------------------------*/
  2382. /* Change Current Directory or Current Drive, Get Current Directory */
  2383. /*-----------------------------------------------------------------------*/
  2384. #if _FS_RPATH >= 1
  2385. #if _VOLUMES >= 2
  2386. FRESULT f_chdrive (
  2387. const TCHAR* path /* Drive number */
  2388. )
  2389. {
  2390. int vol;
  2391. vol = get_ldnumber(&path);
  2392. if (vol < 0) return FR_INVALID_DRIVE;
  2393. CurrVol = (BYTE)vol;
  2394. return FR_OK;
  2395. }
  2396. #endif
  2397. FRESULT f_chdir (
  2398. const TCHAR* path /* Pointer to the directory path */
  2399. )
  2400. {
  2401. FRESULT res;
  2402. DIR dj;
  2403. DEFINE_NAMEBUF;
  2404. /* Get logical drive number */
  2405. res = find_volume(&dj.fs, &path, 0);
  2406. if (res == FR_OK) {
  2407. INIT_BUF(dj);
  2408. res = follow_path(&dj, path); /* Follow the path */
  2409. FREE_BUF();
  2410. if (res == FR_OK) { /* Follow completed */
  2411. if (!dj.dir) {
  2412. dj.fs->cdir = dj.sclust; /* Start directory itself */
  2413. } else {
  2414. if (dj.dir[DIR_Attr] & AM_DIR) /* Reached to the directory */
  2415. dj.fs->cdir = ld_clust(dj.fs, dj.dir);
  2416. else
  2417. res = FR_NO_PATH; /* Reached but a file */
  2418. }
  2419. }
  2420. if (res == FR_NO_FILE) res = FR_NO_PATH;
  2421. }
  2422. LEAVE_FF(dj.fs, res);
  2423. }
  2424. #if _FS_RPATH >= 2
  2425. FRESULT f_getcwd (
  2426. TCHAR* buff, /* Pointer to the directory path */
  2427. UINT len /* Size of path */
  2428. )
  2429. {
  2430. FRESULT res;
  2431. DIR dj;
  2432. UINT i, n;
  2433. DWORD ccl;
  2434. TCHAR *tp;
  2435. FILINFO fno;
  2436. DEFINE_NAMEBUF;
  2437. *buff = 0;
  2438. /* Get logical drive number */
  2439. res = find_volume(&dj.fs, (const TCHAR**)&buff, 0); /* Get current volume */
  2440. if (res == FR_OK) {
  2441. INIT_BUF(dj);
  2442. i = len; /* Bottom of buffer (directory stack base) */
  2443. dj.sclust = dj.fs->cdir; /* Start to follow upper directory from current directory */
  2444. while ((ccl = dj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
  2445. res = dir_sdi(&dj, 1); /* Get parent directory */
  2446. if (res != FR_OK) break;
  2447. res = dir_read(&dj, 0);
  2448. if (res != FR_OK) break;
  2449. dj.sclust = ld_clust(dj.fs, dj.dir); /* Goto parent directory */
  2450. res = dir_sdi(&dj, 0);
  2451. if (res != FR_OK) break;
  2452. do { /* Find the entry links to the child directory */
  2453. res = dir_read(&dj, 0);
  2454. if (res != FR_OK) break;
  2455. if (ccl == ld_clust(dj.fs, dj.dir)) break; /* Found the entry */
  2456. res = dir_next(&dj, 0);
  2457. } while (res == FR_OK);
  2458. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  2459. if (res != FR_OK) break;
  2460. #if _USE_LFN
  2461. fno.lfname = buff;
  2462. fno.lfsize = i;
  2463. #endif
  2464. get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
  2465. tp = fno.fname;
  2466. #if _USE_LFN
  2467. if (*buff) tp = buff;
  2468. #endif
  2469. for (n = 0; tp[n]; n++) ;
  2470. if (i < n + 3) {
  2471. res = FR_NOT_ENOUGH_CORE; break;
  2472. }
  2473. while (n) buff[--i] = tp[--n];
  2474. buff[--i] = '/';
  2475. }
  2476. tp = buff;
  2477. if (res == FR_OK) {
  2478. #if _VOLUMES >= 2
  2479. *tp++ = '0' + CurrVol; /* Put drive number */
  2480. *tp++ = ':';
  2481. #endif
  2482. if (i == len) { /* Root-directory */
  2483. *tp++ = '/';
  2484. } else { /* Sub-directroy */
  2485. do /* Add stacked path str */
  2486. *tp++ = buff[i++];
  2487. while (i < len);
  2488. }
  2489. }
  2490. *tp = 0;
  2491. FREE_BUF();
  2492. }
  2493. LEAVE_FF(dj.fs, res);
  2494. }
  2495. #endif /* _FS_RPATH >= 2 */
  2496. #endif /* _FS_RPATH >= 1 */
  2497. #if _FS_MINIMIZE <= 2
  2498. /*-----------------------------------------------------------------------*/
  2499. /* Seek File R/W Pointer */
  2500. /*-----------------------------------------------------------------------*/
  2501. FRESULT f_lseek (
  2502. FIL* fp, /* Pointer to the file object */
  2503. DWORD ofs /* File pointer from top of file */
  2504. )
  2505. {
  2506. FRESULT res;
  2507. DWORD clst, bcs, nsect, ifptr;
  2508. #if _USE_FASTSEEK
  2509. DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
  2510. #endif
  2511. res = validate(fp); /* Check validity of the object */
  2512. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  2513. if (fp->err) /* Check error */
  2514. LEAVE_FF(fp->fs, (FRESULT)fp->err);
  2515. #if _USE_FASTSEEK
  2516. if (fp->cltbl) { /* Fast seek */
  2517. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  2518. tbl = fp->cltbl;
  2519. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  2520. cl = fp->sclust; /* Top of the chain */
  2521. if (cl) {
  2522. do {
  2523. /* Get a fragment */
  2524. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  2525. do {
  2526. pcl = cl; ncl++;
  2527. cl = get_fat(fp->fs, cl);
  2528. if (cl <= 1) ABORT(fp->fs, FR_INT_ERR);
  2529. if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2530. } while (cl == pcl + 1);
  2531. if (ulen <= tlen) { /* Store the length and top of the fragment */
  2532. *tbl++ = ncl; *tbl++ = tcl;
  2533. }
  2534. } while (cl < fp->fs->n_fatent); /* Repeat until end of chain */
  2535. }
  2536. *fp->cltbl = ulen; /* Number of items used */
  2537. if (ulen <= tlen)
  2538. *tbl = 0; /* Terminate table */
  2539. else
  2540. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  2541. } else { /* Fast seek */
  2542. if (ofs > fp->fsize) /* Clip offset at the file size */
  2543. ofs = fp->fsize;
  2544. fp->fptr = ofs; /* Set file pointer */
  2545. if (ofs) {
  2546. fp->clust = clmt_clust(fp, ofs - 1);
  2547. dsc = clust2sect(fp->fs, fp->clust);
  2548. if (!dsc) ABORT(fp->fs, FR_INT_ERR);
  2549. dsc += (ofs - 1) / SS(fp->fs) & (fp->fs->csize - 1);
  2550. if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) { /* Refill sector cache if needed */
  2551. #if !_FS_TINY
  2552. #if !_FS_READONLY
  2553. if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */
  2554. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2555. ABORT(fp->fs, FR_DISK_ERR);
  2556. fp->flag &= ~FA__DIRTY;
  2557. }
  2558. #endif
  2559. if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK) /* Load current sector */
  2560. ABORT(fp->fs, FR_DISK_ERR);
  2561. #endif
  2562. fp->dsect = dsc;
  2563. }
  2564. }
  2565. }
  2566. } else
  2567. #endif
  2568. /* Normal Seek */
  2569. {
  2570. if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */
  2571. #if !_FS_READONLY
  2572. && !(fp->flag & FA_WRITE)
  2573. #endif
  2574. ) ofs = fp->fsize;
  2575. ifptr = fp->fptr;
  2576. fp->fptr = nsect = 0;
  2577. if (ofs) {
  2578. bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */
  2579. if (ifptr > 0 &&
  2580. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  2581. fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */
  2582. ofs -= fp->fptr;
  2583. clst = fp->clust;
  2584. } else { /* When seek to back cluster, */
  2585. clst = fp->sclust; /* start from the first cluster */
  2586. #if !_FS_READONLY
  2587. if (clst == 0) { /* If no cluster chain, create a new chain */
  2588. clst = create_chain(fp->fs, 0);
  2589. if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
  2590. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2591. fp->sclust = clst;
  2592. }
  2593. #endif
  2594. fp->clust = clst;
  2595. }
  2596. if (clst != 0) {
  2597. while (ofs > bcs) { /* Cluster following loop */
  2598. #if !_FS_READONLY
  2599. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  2600. clst = create_chain(fp->fs, clst); /* Force stretch if in write mode */
  2601. if (clst == 0) { /* When disk gets full, clip file size */
  2602. ofs = bcs; break;
  2603. }
  2604. } else
  2605. #endif
  2606. clst = get_fat(fp->fs, clst); /* Follow cluster chain if not in write mode */
  2607. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  2608. if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR);
  2609. fp->clust = clst;
  2610. fp->fptr += bcs;
  2611. ofs -= bcs;
  2612. }
  2613. fp->fptr += ofs;
  2614. if (ofs % SS(fp->fs)) {
  2615. nsect = clust2sect(fp->fs, clst); /* Current sector */
  2616. if (!nsect) ABORT(fp->fs, FR_INT_ERR);
  2617. nsect += ofs / SS(fp->fs);
  2618. }
  2619. }
  2620. }
  2621. if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) { /* Fill sector cache if needed */
  2622. #if !_FS_TINY
  2623. #if !_FS_READONLY
  2624. if (fp->flag & FA__DIRTY) { /* Write-back dirty sector cache */
  2625. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2626. ABORT(fp->fs, FR_DISK_ERR);
  2627. fp->flag &= ~FA__DIRTY;
  2628. }
  2629. #endif
  2630. if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK) /* Fill sector cache */
  2631. ABORT(fp->fs, FR_DISK_ERR);
  2632. #endif
  2633. fp->dsect = nsect;
  2634. }
  2635. #if !_FS_READONLY
  2636. if (fp->fptr > fp->fsize) { /* Set file change flag if the file size is extended */
  2637. fp->fsize = fp->fptr;
  2638. fp->flag |= FA__WRITTEN;
  2639. }
  2640. #endif
  2641. }
  2642. LEAVE_FF(fp->fs, res);
  2643. }
  2644. #if _FS_MINIMIZE <= 1
  2645. /*-----------------------------------------------------------------------*/
  2646. /* Create a Directory Object */
  2647. /*-----------------------------------------------------------------------*/
  2648. FRESULT f_opendir (
  2649. DIR* dp, /* Pointer to directory object to create */
  2650. const TCHAR* path /* Pointer to the directory path */
  2651. )
  2652. {
  2653. FRESULT res;
  2654. FATFS* fs;
  2655. DEFINE_NAMEBUF;
  2656. if (!dp) return FR_INVALID_OBJECT;
  2657. /* Get logical drive number */
  2658. res = find_volume(&fs, &path, 0);
  2659. if (res == FR_OK) {
  2660. dp->fs = fs;
  2661. INIT_BUF(*dp);
  2662. res = follow_path(dp, path); /* Follow the path to the directory */
  2663. FREE_BUF();
  2664. if (res == FR_OK) { /* Follow completed */
  2665. if (dp->dir) { /* It is not the origin directory itself */
  2666. if (dp->dir[DIR_Attr] & AM_DIR) /* The object is a sub directory */
  2667. dp->sclust = ld_clust(fs, dp->dir);
  2668. else /* The object is a file */
  2669. res = FR_NO_PATH;
  2670. }
  2671. if (res == FR_OK) {
  2672. dp->id = fs->id;
  2673. res = dir_sdi(dp, 0); /* Rewind directory */
  2674. #if _FS_LOCK
  2675. if (res == FR_OK) {
  2676. if (dp->sclust) {
  2677. dp->lockid = inc_lock(dp, 0); /* Lock the sub directory */
  2678. if (!dp->lockid)
  2679. res = FR_TOO_MANY_OPEN_FILES;
  2680. } else {
  2681. dp->lockid = 0; /* Root directory need not to be locked */
  2682. }
  2683. }
  2684. #endif
  2685. }
  2686. }
  2687. if (res == FR_NO_FILE) res = FR_NO_PATH;
  2688. }
  2689. if (res != FR_OK) dp->fs = 0; /* Invalidate the directory object if function faild */
  2690. LEAVE_FF(fs, res);
  2691. }
  2692. /*-----------------------------------------------------------------------*/
  2693. /* Close Directory */
  2694. /*-----------------------------------------------------------------------*/
  2695. FRESULT f_closedir (
  2696. DIR *dp /* Pointer to the directory object to be closed */
  2697. )
  2698. {
  2699. FRESULT res;
  2700. res = validate(dp);
  2701. if (res == FR_OK) {
  2702. #if _FS_REENTRANT
  2703. FATFS *fs = dp->fs;
  2704. #endif
  2705. #if _FS_LOCK
  2706. if (dp->lockid) /* Decrement sub-directory open counter */
  2707. res = dec_lock(dp->lockid);
  2708. if (res == FR_OK)
  2709. #endif
  2710. dp->fs = 0; /* Invalidate directory object */
  2711. #if _FS_REENTRANT
  2712. unlock_fs(fs, FR_OK); /* Unlock volume */
  2713. #endif
  2714. }
  2715. return res;
  2716. }
  2717. /*-----------------------------------------------------------------------*/
  2718. /* Read Directory Entries in Sequence */
  2719. /*-----------------------------------------------------------------------*/
  2720. FRESULT f_readdir (
  2721. DIR* dp, /* Pointer to the open directory object */
  2722. FILINFO* fno /* Pointer to file information to return */
  2723. )
  2724. {
  2725. FRESULT res;
  2726. DEFINE_NAMEBUF;
  2727. res = validate(dp); /* Check validity of the object */
  2728. if (res == FR_OK) {
  2729. if (!fno) {
  2730. res = dir_sdi(dp, 0); /* Rewind the directory object */
  2731. } else {
  2732. INIT_BUF(*dp);
  2733. res = dir_read(dp, 0); /* Read an item */
  2734. if (res == FR_NO_FILE) { /* Reached end of directory */
  2735. dp->sect = 0;
  2736. res = FR_OK;
  2737. }
  2738. if (res == FR_OK) { /* A valid entry is found */
  2739. get_fileinfo(dp, fno); /* Get the object information */
  2740. res = dir_next(dp, 0); /* Increment index for next */
  2741. if (res == FR_NO_FILE) {
  2742. dp->sect = 0;
  2743. res = FR_OK;
  2744. }
  2745. }
  2746. FREE_BUF();
  2747. }
  2748. }
  2749. LEAVE_FF(dp->fs, res);
  2750. }
  2751. #if _USE_FIND
  2752. /*-----------------------------------------------------------------------*/
  2753. /* Find next file */
  2754. /*-----------------------------------------------------------------------*/
  2755. FRESULT f_findnext (
  2756. DIR* dp, /* Pointer to the open directory object */
  2757. FILINFO* fno /* Pointer to the file information structure */
  2758. )
  2759. {
  2760. FRESULT res;
  2761. for (;;) {
  2762. res = f_readdir(dp, fno); /* Get a directory item */
  2763. if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
  2764. #if _USE_LFN
  2765. if (fno->lfname && pattern_matching(dp->pat, fno->lfname, 0, 0)) break; /* Test for LFN if exist */
  2766. #endif
  2767. if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for SFN */
  2768. }
  2769. return res;
  2770. }
  2771. /*-----------------------------------------------------------------------*/
  2772. /* Find first file */
  2773. /*-----------------------------------------------------------------------*/
  2774. FRESULT f_findfirst (
  2775. DIR* dp, /* Pointer to the blank directory object */
  2776. FILINFO* fno, /* Pointer to the file information structure */
  2777. const TCHAR* path, /* Pointer to the directory to open */
  2778. const TCHAR* pattern /* Pointer to the matching pattern */
  2779. )
  2780. {
  2781. FRESULT res;
  2782. dp->pat = pattern; /* Save pointer to pattern string */
  2783. res = f_opendir(dp, path); /* Open the target directory */
  2784. if (res == FR_OK)
  2785. res = f_findnext(dp, fno); /* Find the first item */
  2786. return res;
  2787. }
  2788. #endif /* _USE_FIND */
  2789. #if _FS_MINIMIZE == 0
  2790. /*-----------------------------------------------------------------------*/
  2791. /* Get File Status */
  2792. /*-----------------------------------------------------------------------*/
  2793. FRESULT f_stat (
  2794. const TCHAR* path, /* Pointer to the file path */
  2795. FILINFO* fno /* Pointer to file information to return */
  2796. )
  2797. {
  2798. FRESULT res;
  2799. DIR dj;
  2800. DEFINE_NAMEBUF;
  2801. /* Get logical drive number */
  2802. res = find_volume(&dj.fs, &path, 0);
  2803. if (res == FR_OK) {
  2804. INIT_BUF(dj);
  2805. res = follow_path(&dj, path); /* Follow the file path */
  2806. if (res == FR_OK) { /* Follow completed */
  2807. if (dj.dir) { /* Found an object */
  2808. if (fno) get_fileinfo(&dj, fno);
  2809. } else { /* It is root directory */
  2810. res = FR_INVALID_NAME;
  2811. }
  2812. }
  2813. FREE_BUF();
  2814. }
  2815. LEAVE_FF(dj.fs, res);
  2816. }
  2817. #if !_FS_READONLY
  2818. /*-----------------------------------------------------------------------*/
  2819. /* Get Number of Free Clusters */
  2820. /*-----------------------------------------------------------------------*/
  2821. FRESULT f_getfree (
  2822. const TCHAR* path, /* Path name of the logical drive number */
  2823. DWORD* nclst, /* Pointer to a variable to return number of free clusters */
  2824. FATFS** fatfs /* Pointer to return pointer to corresponding file system object */
  2825. )
  2826. {
  2827. FRESULT res;
  2828. FATFS *fs;
  2829. DWORD n, clst, sect, stat;
  2830. UINT i;
  2831. BYTE fat, *p;
  2832. /* Get logical drive number */
  2833. res = find_volume(fatfs, &path, 0);
  2834. fs = *fatfs;
  2835. if (res == FR_OK) {
  2836. /* If free_clust is valid, return it without full cluster scan */
  2837. if (fs->free_clust <= fs->n_fatent - 2) {
  2838. *nclst = fs->free_clust;
  2839. } else {
  2840. /* Get number of free clusters */
  2841. fat = fs->fs_type;
  2842. n = 0;
  2843. if (fat == FS_FAT12) {
  2844. clst = 2;
  2845. do {
  2846. stat = get_fat(fs, clst);
  2847. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  2848. if (stat == 1) { res = FR_INT_ERR; break; }
  2849. if (stat == 0) n++;
  2850. } while (++clst < fs->n_fatent);
  2851. } else {
  2852. clst = fs->n_fatent;
  2853. sect = fs->fatbase;
  2854. i = 0; p = 0;
  2855. do {
  2856. if (!i) {
  2857. res = move_window(fs, sect++);
  2858. if (res != FR_OK) break;
  2859. p = fs->win;
  2860. i = SS(fs);
  2861. }
  2862. if (fat == FS_FAT16) {
  2863. if (LD_WORD(p) == 0) n++;
  2864. p += 2; i -= 2;
  2865. } else {
  2866. if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;
  2867. p += 4; i -= 4;
  2868. }
  2869. } while (--clst);
  2870. }
  2871. fs->free_clust = n;
  2872. fs->fsi_flag |= 1;
  2873. *nclst = n;
  2874. }
  2875. }
  2876. LEAVE_FF(fs, res);
  2877. }
  2878. /*-----------------------------------------------------------------------*/
  2879. /* Truncate File */
  2880. /*-----------------------------------------------------------------------*/
  2881. FRESULT f_truncate (
  2882. FIL* fp /* Pointer to the file object */
  2883. )
  2884. {
  2885. FRESULT res;
  2886. DWORD ncl;
  2887. res = validate(fp); /* Check validity of the object */
  2888. if (res == FR_OK) {
  2889. if (fp->err) { /* Check error */
  2890. res = (FRESULT)fp->err;
  2891. } else {
  2892. if (!(fp->flag & FA_WRITE)) /* Check access mode */
  2893. res = FR_DENIED;
  2894. }
  2895. }
  2896. if (res == FR_OK) {
  2897. if (fp->fsize > fp->fptr) {
  2898. fp->fsize = fp->fptr; /* Set file size to current R/W point */
  2899. fp->flag |= FA__WRITTEN;
  2900. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  2901. res = remove_chain(fp->fs, fp->sclust);
  2902. fp->sclust = 0;
  2903. } else { /* When truncate a part of the file, remove remaining clusters */
  2904. ncl = get_fat(fp->fs, fp->clust);
  2905. res = FR_OK;
  2906. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  2907. if (ncl == 1) res = FR_INT_ERR;
  2908. if (res == FR_OK && ncl < fp->fs->n_fatent) {
  2909. res = put_fat(fp->fs, fp->clust, 0x0FFFFFFF);
  2910. if (res == FR_OK) res = remove_chain(fp->fs, ncl);
  2911. }
  2912. }
  2913. #if !_FS_TINY
  2914. if (res == FR_OK && (fp->flag & FA__DIRTY)) {
  2915. if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
  2916. res = FR_DISK_ERR;
  2917. else
  2918. fp->flag &= ~FA__DIRTY;
  2919. }
  2920. #endif
  2921. }
  2922. if (res != FR_OK) fp->err = (FRESULT)res;
  2923. }
  2924. LEAVE_FF(fp->fs, res);
  2925. }
  2926. /*-----------------------------------------------------------------------*/
  2927. /* Delete a File or Directory */
  2928. /*-----------------------------------------------------------------------*/
  2929. FRESULT f_unlink (
  2930. const TCHAR* path /* Pointer to the file or directory path */
  2931. )
  2932. {
  2933. FRESULT res;
  2934. DIR dj, sdj;
  2935. BYTE *dir;
  2936. DWORD dclst = 0;
  2937. DEFINE_NAMEBUF;
  2938. /* Get logical drive number */
  2939. res = find_volume(&dj.fs, &path, 1);
  2940. if (res == FR_OK) {
  2941. INIT_BUF(dj);
  2942. res = follow_path(&dj, path); /* Follow the file path */
  2943. if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT))
  2944. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  2945. #if _FS_LOCK
  2946. if (res == FR_OK) res = chk_lock(&dj, 2); /* Cannot remove open object */
  2947. #endif
  2948. if (res == FR_OK) { /* The object is accessible */
  2949. dir = dj.dir;
  2950. if (!dir) {
  2951. res = FR_INVALID_NAME; /* Cannot remove the origin directory */
  2952. } else {
  2953. if (dir[DIR_Attr] & AM_RDO)
  2954. res = FR_DENIED; /* Cannot remove R/O object */
  2955. }
  2956. if (res == FR_OK) {
  2957. dclst = ld_clust(dj.fs, dir);
  2958. if (dclst && (dir[DIR_Attr] & AM_DIR)) { /* Is it a sub-directory ? */
  2959. #if _FS_RPATH
  2960. if (dclst == dj.fs->cdir) { /* Is it the current directory? */
  2961. res = FR_DENIED;
  2962. } else
  2963. #endif
  2964. {
  2965. mem_cpy(&sdj, &dj, sizeof (DIR)); /* Open the sub-directory */
  2966. sdj.sclust = dclst;
  2967. res = dir_sdi(&sdj, 2);
  2968. if (res == FR_OK) {
  2969. res = dir_read(&sdj, 0); /* Read an item (excluding dot entries) */
  2970. if (res == FR_OK) res = FR_DENIED; /* Not empty? (cannot remove) */
  2971. if (res == FR_NO_FILE) res = FR_OK; /* Empty? (can remove) */
  2972. }
  2973. }
  2974. }
  2975. }
  2976. if (res == FR_OK) {
  2977. res = dir_remove(&dj); /* Remove the directory entry */
  2978. if (res == FR_OK && dclst) /* Remove the cluster chain if exist */
  2979. res = remove_chain(dj.fs, dclst);
  2980. if (res == FR_OK) res = sync_fs(dj.fs);
  2981. }
  2982. }
  2983. FREE_BUF();
  2984. }
  2985. LEAVE_FF(dj.fs, res);
  2986. }
  2987. /*-----------------------------------------------------------------------*/
  2988. /* Create a Directory */
  2989. /*-----------------------------------------------------------------------*/
  2990. FRESULT f_mkdir (
  2991. const TCHAR* path /* Pointer to the directory path */
  2992. )
  2993. {
  2994. FRESULT res;
  2995. DIR dj;
  2996. BYTE *dir, n;
  2997. DWORD dsc, dcl, pcl, tm = GET_FATTIME();
  2998. DEFINE_NAMEBUF;
  2999. /* Get logical drive number */
  3000. res = find_volume(&dj.fs, &path, 1);
  3001. if (res == FR_OK) {
  3002. INIT_BUF(dj);
  3003. res = follow_path(&dj, path); /* Follow the file path */
  3004. if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
  3005. if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT))
  3006. res = FR_INVALID_NAME;
  3007. if (res == FR_NO_FILE) { /* Can create a new directory */
  3008. dcl = create_chain(dj.fs, 0); /* Allocate a cluster for the new directory table */
  3009. res = FR_OK;
  3010. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
  3011. if (dcl == 1) res = FR_INT_ERR;
  3012. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3013. if (res == FR_OK) /* Flush FAT */
  3014. res = sync_window(dj.fs);
  3015. if (res == FR_OK) { /* Initialize the new directory table */
  3016. dsc = clust2sect(dj.fs, dcl);
  3017. dir = dj.fs->win;
  3018. mem_set(dir, 0, SS(dj.fs));
  3019. mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
  3020. dir[DIR_Name] = '.';
  3021. dir[DIR_Attr] = AM_DIR;
  3022. ST_DWORD(dir + DIR_WrtTime, tm);
  3023. st_clust(dir, dcl);
  3024. mem_cpy(dir + SZ_DIRE, dir, SZ_DIRE); /* Create ".." entry */
  3025. dir[SZ_DIRE + 1] = '.'; pcl = dj.sclust;
  3026. if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase)
  3027. pcl = 0;
  3028. st_clust(dir + SZ_DIRE, pcl);
  3029. for (n = dj.fs->csize; n; n--) { /* Write dot entries and clear following sectors */
  3030. dj.fs->winsect = dsc++;
  3031. dj.fs->wflag = 1;
  3032. res = sync_window(dj.fs);
  3033. if (res != FR_OK) break;
  3034. mem_set(dir, 0, SS(dj.fs));
  3035. }
  3036. }
  3037. if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
  3038. if (res != FR_OK) {
  3039. remove_chain(dj.fs, dcl); /* Could not register, remove cluster chain */
  3040. } else {
  3041. dir = dj.dir;
  3042. dir[DIR_Attr] = AM_DIR; /* Attribute */
  3043. ST_DWORD(dir + DIR_WrtTime, tm); /* Created time */
  3044. st_clust(dir, dcl); /* Table start cluster */
  3045. dj.fs->wflag = 1;
  3046. res = sync_fs(dj.fs);
  3047. }
  3048. }
  3049. FREE_BUF();
  3050. }
  3051. LEAVE_FF(dj.fs, res);
  3052. }
  3053. /*-----------------------------------------------------------------------*/
  3054. /* Change Attribute */
  3055. /*-----------------------------------------------------------------------*/
  3056. FRESULT f_chmod (
  3057. const TCHAR* path, /* Pointer to the file path */
  3058. BYTE attr, /* Attribute bits */
  3059. BYTE mask /* Attribute mask to change */
  3060. )
  3061. {
  3062. FRESULT res;
  3063. DIR dj;
  3064. BYTE *dir;
  3065. DEFINE_NAMEBUF;
  3066. /* Get logical drive number */
  3067. res = find_volume(&dj.fs, &path, 1);
  3068. if (res == FR_OK) {
  3069. INIT_BUF(dj);
  3070. res = follow_path(&dj, path); /* Follow the file path */
  3071. FREE_BUF();
  3072. if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT))
  3073. res = FR_INVALID_NAME;
  3074. if (res == FR_OK) {
  3075. dir = dj.dir;
  3076. if (!dir) { /* Is it a root directory? */
  3077. res = FR_INVALID_NAME;
  3078. } else { /* File or sub directory */
  3079. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  3080. dir[DIR_Attr] = (attr & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  3081. dj.fs->wflag = 1;
  3082. res = sync_fs(dj.fs);
  3083. }
  3084. }
  3085. }
  3086. LEAVE_FF(dj.fs, res);
  3087. }
  3088. /*-----------------------------------------------------------------------*/
  3089. /* Rename File/Directory */
  3090. /*-----------------------------------------------------------------------*/
  3091. FRESULT f_rename (
  3092. const TCHAR* path_old, /* Pointer to the object to be renamed */
  3093. const TCHAR* path_new /* Pointer to the new name */
  3094. )
  3095. {
  3096. FRESULT res;
  3097. DIR djo, djn;
  3098. BYTE buf[21], *dir;
  3099. DWORD dw;
  3100. DEFINE_NAMEBUF;
  3101. /* Get logical drive number of the source object */
  3102. res = find_volume(&djo.fs, &path_old, 1);
  3103. if (res == FR_OK) {
  3104. djn.fs = djo.fs;
  3105. INIT_BUF(djo);
  3106. res = follow_path(&djo, path_old); /* Check old object */
  3107. if (_FS_RPATH && res == FR_OK && (djo.fn[NSFLAG] & NS_DOT))
  3108. res = FR_INVALID_NAME;
  3109. #if _FS_LOCK
  3110. if (res == FR_OK) res = chk_lock(&djo, 2);
  3111. #endif
  3112. if (res == FR_OK) { /* Old object is found */
  3113. if (!djo.dir) { /* Is root dir? */
  3114. res = FR_NO_FILE;
  3115. } else {
  3116. mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about object except name */
  3117. mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
  3118. if (get_ldnumber(&path_new) >= 0) /* Snip drive number off and ignore it */
  3119. res = follow_path(&djn, path_new); /* and make sure if new object name is not conflicting */
  3120. else
  3121. res = FR_INVALID_DRIVE;
  3122. if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */
  3123. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  3124. res = dir_register(&djn); /* Register the new entry */
  3125. if (res == FR_OK) {
  3126. /* Start of critical section where any interruption can cause a cross-link */
  3127. dir = djn.dir; /* Copy information about object except name */
  3128. mem_cpy(dir + 13, buf + 2, 19);
  3129. dir[DIR_Attr] = buf[0] | AM_ARC;
  3130. djo.fs->wflag = 1;
  3131. if ((dir[DIR_Attr] & AM_DIR) && djo.sclust != djn.sclust) { /* Update .. entry in the sub-directory if needed */
  3132. dw = clust2sect(djo.fs, ld_clust(djo.fs, dir));
  3133. if (!dw) {
  3134. res = FR_INT_ERR;
  3135. } else {
  3136. res = move_window(djo.fs, dw);
  3137. dir = djo.fs->win + SZ_DIRE * 1; /* Ptr to .. entry */
  3138. if (res == FR_OK && dir[1] == '.') {
  3139. st_clust(dir, djn.sclust);
  3140. djo.fs->wflag = 1;
  3141. }
  3142. }
  3143. }
  3144. if (res == FR_OK) {
  3145. res = dir_remove(&djo); /* Remove old entry */
  3146. if (res == FR_OK)
  3147. res = sync_fs(djo.fs);
  3148. }
  3149. /* End of critical section */
  3150. }
  3151. }
  3152. }
  3153. }
  3154. FREE_BUF();
  3155. }
  3156. LEAVE_FF(djo.fs, res);
  3157. }
  3158. /*-----------------------------------------------------------------------*/
  3159. /* Change Timestamp */
  3160. /*-----------------------------------------------------------------------*/
  3161. FRESULT f_utime (
  3162. const TCHAR* path, /* Pointer to the file/directory name */
  3163. const FILINFO* fno /* Pointer to the time stamp to be set */
  3164. )
  3165. {
  3166. FRESULT res;
  3167. DIR dj;
  3168. BYTE *dir;
  3169. DEFINE_NAMEBUF;
  3170. /* Get logical drive number */
  3171. res = find_volume(&dj.fs, &path, 1);
  3172. if (res == FR_OK) {
  3173. INIT_BUF(dj);
  3174. res = follow_path(&dj, path); /* Follow the file path */
  3175. FREE_BUF();
  3176. if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT))
  3177. res = FR_INVALID_NAME;
  3178. if (res == FR_OK) {
  3179. dir = dj.dir;
  3180. if (!dir) { /* Root directory */
  3181. res = FR_INVALID_NAME;
  3182. } else { /* File or sub-directory */
  3183. ST_WORD(dir + DIR_WrtTime, fno->ftime);
  3184. ST_WORD(dir + DIR_WrtDate, fno->fdate);
  3185. dj.fs->wflag = 1;
  3186. res = sync_fs(dj.fs);
  3187. }
  3188. }
  3189. }
  3190. LEAVE_FF(dj.fs, res);
  3191. }
  3192. #endif /* !_FS_READONLY */
  3193. #endif /* _FS_MINIMIZE == 0 */
  3194. #endif /* _FS_MINIMIZE <= 1 */
  3195. #endif /* _FS_MINIMIZE <= 2 */
  3196. #if _USE_LABEL
  3197. /*-----------------------------------------------------------------------*/
  3198. /* Get volume label */
  3199. /*-----------------------------------------------------------------------*/
  3200. FRESULT f_getlabel (
  3201. const TCHAR* path, /* Path name of the logical drive number */
  3202. TCHAR* label, /* Pointer to a buffer to return the volume label */
  3203. DWORD* vsn /* Pointer to a variable to return the volume serial number */
  3204. )
  3205. {
  3206. FRESULT res;
  3207. DIR dj;
  3208. UINT i, j;
  3209. #if _USE_LFN && _LFN_UNICODE
  3210. WCHAR w;
  3211. #endif
  3212. /* Get logical drive number */
  3213. res = find_volume(&dj.fs, &path, 0);
  3214. /* Get volume label */
  3215. if (res == FR_OK && label) {
  3216. dj.sclust = 0; /* Open root directory */
  3217. res = dir_sdi(&dj, 0);
  3218. if (res == FR_OK) {
  3219. res = dir_read(&dj, 1); /* Get an entry with AM_VOL */
  3220. if (res == FR_OK) { /* A volume label is exist */
  3221. #if _USE_LFN && _LFN_UNICODE
  3222. i = j = 0;
  3223. do {
  3224. w = (i < 11) ? dj.dir[i++] : ' ';
  3225. if (IsDBCS1(w) && i < 11 && IsDBCS2(dj.dir[i]))
  3226. w = w << 8 | dj.dir[i++];
  3227. label[j++] = ff_convert(w, 1); /* OEM -> Unicode */
  3228. } while (j < 11);
  3229. #else
  3230. mem_cpy(label, dj.dir, 11);
  3231. #endif
  3232. j = 11;
  3233. do {
  3234. label[j] = 0;
  3235. if (!j) break;
  3236. } while (label[--j] == ' ');
  3237. }
  3238. if (res == FR_NO_FILE) { /* No label, return nul string */
  3239. label[0] = 0;
  3240. res = FR_OK;
  3241. }
  3242. }
  3243. }
  3244. /* Get volume serial number */
  3245. if (res == FR_OK && vsn) {
  3246. res = move_window(dj.fs, dj.fs->volbase);
  3247. if (res == FR_OK) {
  3248. i = dj.fs->fs_type == FS_FAT32 ? BS_VolID32 : BS_VolID;
  3249. *vsn = LD_DWORD(&dj.fs->win[i]);
  3250. }
  3251. }
  3252. LEAVE_FF(dj.fs, res);
  3253. }
  3254. #if !_FS_READONLY
  3255. /*-----------------------------------------------------------------------*/
  3256. /* Set volume label */
  3257. /*-----------------------------------------------------------------------*/
  3258. FRESULT f_setlabel (
  3259. const TCHAR* label /* Pointer to the volume label to set */
  3260. )
  3261. {
  3262. FRESULT res;
  3263. DIR dj;
  3264. BYTE vn[11];
  3265. UINT i, j, sl;
  3266. WCHAR w;
  3267. DWORD tm;
  3268. /* Get logical drive number */
  3269. res = find_volume(&dj.fs, &label, 1);
  3270. if (res) LEAVE_FF(dj.fs, res);
  3271. /* Create a volume label in directory form */
  3272. vn[0] = 0;
  3273. for (sl = 0; label[sl]; sl++) ; /* Get name length */
  3274. for ( ; sl && label[sl - 1] == ' '; sl--) ; /* Remove trailing spaces */
  3275. if (sl) { /* Create volume label in directory form */
  3276. i = j = 0;
  3277. do {
  3278. #if _USE_LFN && _LFN_UNICODE
  3279. w = ff_convert(ff_wtoupper(label[i++]), 0);
  3280. #else
  3281. w = (BYTE)label[i++];
  3282. if (IsDBCS1(w))
  3283. w = (j < 10 && i < sl && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  3284. #if _USE_LFN
  3285. w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
  3286. #else
  3287. if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
  3288. #ifdef _EXCVT
  3289. if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
  3290. #else
  3291. if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
  3292. #endif
  3293. #endif
  3294. #endif
  3295. if (!w || chk_chr("\"*+,.:;<=>\?[]|\x7F", w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) /* Reject invalid characters for volume label */
  3296. LEAVE_FF(dj.fs, FR_INVALID_NAME);
  3297. if (w >= 0x100) vn[j++] = (BYTE)(w >> 8);
  3298. vn[j++] = (BYTE)w;
  3299. } while (i < sl);
  3300. while (j < 11) vn[j++] = ' '; /* Fill remaining name field */
  3301. if (vn[0] == DDEM) LEAVE_FF(dj.fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
  3302. }
  3303. /* Set volume label */
  3304. dj.sclust = 0; /* Open root directory */
  3305. res = dir_sdi(&dj, 0);
  3306. if (res == FR_OK) {
  3307. res = dir_read(&dj, 1); /* Get an entry with AM_VOL */
  3308. if (res == FR_OK) { /* A volume label is found */
  3309. if (vn[0]) {
  3310. mem_cpy(dj.dir, vn, 11); /* Change the volume label name */
  3311. tm = GET_FATTIME();
  3312. ST_DWORD(dj.dir + DIR_WrtTime, tm);
  3313. } else {
  3314. dj.dir[0] = DDEM; /* Remove the volume label */
  3315. }
  3316. dj.fs->wflag = 1;
  3317. res = sync_fs(dj.fs);
  3318. } else { /* No volume label is found or error */
  3319. if (res == FR_NO_FILE) {
  3320. res = FR_OK;
  3321. if (vn[0]) { /* Create volume label as new */
  3322. res = dir_alloc(&dj, 1); /* Allocate an entry for volume label */
  3323. if (res == FR_OK) {
  3324. mem_set(dj.dir, 0, SZ_DIRE); /* Set volume label */
  3325. mem_cpy(dj.dir, vn, 11);
  3326. dj.dir[DIR_Attr] = AM_VOL;
  3327. tm = GET_FATTIME();
  3328. ST_DWORD(dj.dir + DIR_WrtTime, tm);
  3329. dj.fs->wflag = 1;
  3330. res = sync_fs(dj.fs);
  3331. }
  3332. }
  3333. }
  3334. }
  3335. }
  3336. LEAVE_FF(dj.fs, res);
  3337. }
  3338. #endif /* !_FS_READONLY */
  3339. #endif /* _USE_LABEL */
  3340. /*-----------------------------------------------------------------------*/
  3341. /* Forward data to the stream directly (available on only tiny cfg) */
  3342. /*-----------------------------------------------------------------------*/
  3343. #if _USE_FORWARD && _FS_TINY
  3344. FRESULT f_forward (
  3345. FIL* fp, /* Pointer to the file object */
  3346. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  3347. UINT btf, /* Number of bytes to forward */
  3348. UINT* bf /* Pointer to number of bytes forwarded */
  3349. )
  3350. {
  3351. FRESULT res;
  3352. DWORD remain, clst, sect;
  3353. UINT rcnt;
  3354. BYTE csect;
  3355. *bf = 0; /* Clear transfer byte counter */
  3356. res = validate(fp); /* Check validity of the object */
  3357. if (res != FR_OK) LEAVE_FF(fp->fs, res);
  3358. if (fp->err) /* Check error */
  3359. LEAVE_FF(fp->fs, (FRESULT)fp->err);
  3360. if (!(fp->flag & FA_READ)) /* Check access mode */
  3361. LEAVE_FF(fp->fs, FR_DENIED);
  3362. remain = fp->fsize - fp->fptr;
  3363. if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
  3364. for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream becomes busy */
  3365. fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
  3366. csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1)); /* Sector offset in the cluster */
  3367. if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */
  3368. if (!csect) { /* On the cluster boundary? */
  3369. clst = (fp->fptr == 0) ? /* On the top of the file? */
  3370. fp->sclust : get_fat(fp->fs, fp->clust);
  3371. if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
  3372. if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
  3373. fp->clust = clst; /* Update current cluster */
  3374. }
  3375. }
  3376. sect = clust2sect(fp->fs, fp->clust); /* Get current data sector */
  3377. if (!sect) ABORT(fp->fs, FR_INT_ERR);
  3378. sect += csect;
  3379. if (move_window(fp->fs, sect) != FR_OK) /* Move sector window */
  3380. ABORT(fp->fs, FR_DISK_ERR);
  3381. fp->dsect = sect;
  3382. rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */
  3383. if (rcnt > btf) rcnt = btf;
  3384. rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
  3385. if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
  3386. }
  3387. LEAVE_FF(fp->fs, FR_OK);
  3388. }
  3389. #endif /* _USE_FORWARD */
  3390. #if _USE_MKFS && !_FS_READONLY
  3391. /*-----------------------------------------------------------------------*/
  3392. /* Create file system on the logical drive */
  3393. /*-----------------------------------------------------------------------*/
  3394. #define N_ROOTDIR 512 /* Number of root directory entries for FAT12/16 */
  3395. #define N_FATS 1 /* Number of FATs (1 or 2) */
  3396. FRESULT f_mkfs (
  3397. const TCHAR* path, /* Logical drive number */
  3398. BYTE sfd, /* Partitioning rule 0:FDISK, 1:SFD */
  3399. UINT au /* Size of allocation unit in unit of byte or sector */
  3400. )
  3401. {
  3402. static const WORD vst[] = { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0};
  3403. static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
  3404. int vol;
  3405. BYTE fmt, md, sys, *tbl, pdrv, part;
  3406. DWORD n_clst, vs, n, wsect;
  3407. UINT i;
  3408. DWORD b_vol, b_fat, b_dir, b_data; /* LBA */
  3409. DWORD n_vol, n_rsv, n_fat, n_dir; /* Size */
  3410. FATFS *fs;
  3411. DSTATUS stat;
  3412. #if _USE_TRIM
  3413. DWORD eb[2];
  3414. #endif
  3415. /* Check mounted drive and clear work area */
  3416. if (sfd > 1) return FR_INVALID_PARAMETER;
  3417. vol = get_ldnumber(&path);
  3418. if (vol < 0) return FR_INVALID_DRIVE;
  3419. fs = FatFs[vol];
  3420. if (!fs) return FR_NOT_ENABLED;
  3421. fs->fs_type = 0;
  3422. pdrv = LD2PD(vol); /* Physical drive */
  3423. part = LD2PT(vol); /* Partition (0:auto detect, 1-4:get from partition table)*/
  3424. /* Get disk statics */
  3425. stat = disk_initialize(pdrv);
  3426. if (stat & STA_NOINIT) return FR_NOT_READY;
  3427. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  3428. #if _MAX_SS != _MIN_SS /* Get disk sector size */
  3429. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS || SS(fs) < _MIN_SS)
  3430. return FR_DISK_ERR;
  3431. #endif
  3432. if (_MULTI_PARTITION && part) {
  3433. /* Get partition information from partition table in the MBR */
  3434. if (disk_read(pdrv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR;
  3435. if (LD_WORD(fs->win + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED;
  3436. tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE];
  3437. if (!tbl[4]) return FR_MKFS_ABORTED; /* No partition? */
  3438. b_vol = LD_DWORD(tbl + 8); /* Volume start sector */
  3439. n_vol = LD_DWORD(tbl + 12); /* Volume size */
  3440. } else {
  3441. /* Create a partition in this function */
  3442. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128)
  3443. return FR_DISK_ERR;
  3444. b_vol = (sfd) ? 0 : 63; /* Volume start sector */
  3445. n_vol -= b_vol; /* Volume size */
  3446. }
  3447. if (au & (au - 1)) au = 0;
  3448. if (!au) { /* AU auto selection */
  3449. vs = n_vol / (2000 / (SS(fs) / 512));
  3450. for (i = 0; vs < vst[i]; i++) ;
  3451. au = cst[i];
  3452. }
  3453. if (au >= _MIN_SS) au /= SS(fs); /* Number of sectors per cluster */
  3454. if (!au) au = 1;
  3455. if (au > 128) au = 128;
  3456. /* Pre-compute number of clusters and FAT sub-type */
  3457. n_clst = n_vol / au;
  3458. fmt = FS_FAT12;
  3459. if (n_clst >= MIN_FAT16) fmt = FS_FAT16;
  3460. if (n_clst >= MIN_FAT32) fmt = FS_FAT32;
  3461. /* Determine offset and size of FAT structure */
  3462. if (fmt == FS_FAT32) {
  3463. n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
  3464. n_rsv = 32;
  3465. n_dir = 0;
  3466. } else {
  3467. n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4;
  3468. n_fat = (n_fat + SS(fs) - 1) / SS(fs);
  3469. n_rsv = 1;
  3470. n_dir = (DWORD)N_ROOTDIR * SZ_DIRE / SS(fs);
  3471. }
  3472. b_fat = b_vol + n_rsv; /* FAT area start sector */
  3473. b_dir = b_fat + n_fat * N_FATS; /* Directory area start sector */
  3474. b_data = b_dir + n_dir; /* Data area start sector */
  3475. if (n_vol < b_data + au - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
  3476. /* Align data start sector to erase block boundary (for flash memory media) */
  3477. if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;
  3478. n = (b_data + n - 1) & ~(n - 1); /* Next nearest erase block from current data start */
  3479. n = (n - b_data) / N_FATS;
  3480. if (fmt == FS_FAT32) { /* FAT32: Move FAT offset */
  3481. n_rsv += n;
  3482. b_fat += n;
  3483. } else { /* FAT12/16: Expand FAT size */
  3484. n_fat += n;
  3485. }
  3486. /* Determine number of clusters and final check of validity of the FAT sub-type */
  3487. n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au;
  3488. if ( (fmt == FS_FAT16 && n_clst < MIN_FAT16)
  3489. || (fmt == FS_FAT32 && n_clst < MIN_FAT32))
  3490. return FR_MKFS_ABORTED;
  3491. /* Determine system ID in the partition table */
  3492. if (fmt == FS_FAT32) {
  3493. sys = 0x0C; /* FAT32X */
  3494. } else {
  3495. if (fmt == FS_FAT12 && n_vol < 0x10000) {
  3496. sys = 0x01; /* FAT12(<65536) */
  3497. } else {
  3498. sys = (n_vol < 0x10000) ? 0x04 : 0x06; /* FAT16(<65536) : FAT12/16(>=65536) */
  3499. }
  3500. }
  3501. if (_MULTI_PARTITION && part) {
  3502. /* Update system ID in the partition table */
  3503. tbl = &fs->win[MBR_Table + (part - 1) * SZ_PTE];
  3504. tbl[4] = sys;
  3505. if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) /* Write it to teh MBR */
  3506. return FR_DISK_ERR;
  3507. md = 0xF8;
  3508. } else {
  3509. if (sfd) { /* No partition table (SFD) */
  3510. md = 0xF0;
  3511. } else { /* Create partition table (FDISK) */
  3512. mem_set(fs->win, 0, SS(fs));
  3513. tbl = fs->win + MBR_Table; /* Create partition table for single partition in the drive */
  3514. tbl[1] = 1; /* Partition start head */
  3515. tbl[2] = 1; /* Partition start sector */
  3516. tbl[3] = 0; /* Partition start cylinder */
  3517. tbl[4] = sys; /* System type */
  3518. tbl[5] = 254; /* Partition end head */
  3519. n = (b_vol + n_vol) / 63 / 255;
  3520. tbl[6] = (BYTE)(n >> 2 | 63); /* Partition end sector */
  3521. tbl[7] = (BYTE)n; /* End cylinder */
  3522. ST_DWORD(tbl + 8, 63); /* Partition start in LBA */
  3523. ST_DWORD(tbl + 12, n_vol); /* Partition size in LBA */
  3524. ST_WORD(fs->win + BS_55AA, 0xAA55); /* MBR signature */
  3525. if (disk_write(pdrv, fs->win, 0, 1) != RES_OK) /* Write it to the MBR */
  3526. return FR_DISK_ERR;
  3527. md = 0xF8;
  3528. }
  3529. }
  3530. /* Create BPB in the VBR */
  3531. tbl = fs->win; /* Clear sector */
  3532. mem_set(tbl, 0, SS(fs));
  3533. mem_cpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */
  3534. i = SS(fs); /* Sector size */
  3535. ST_WORD(tbl + BPB_BytsPerSec, i);
  3536. tbl[BPB_SecPerClus] = (BYTE)au; /* Sectors per cluster */
  3537. ST_WORD(tbl + BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */
  3538. tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */
  3539. i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR; /* Number of root directory entries */
  3540. ST_WORD(tbl + BPB_RootEntCnt, i);
  3541. if (n_vol < 0x10000) { /* Number of total sectors */
  3542. ST_WORD(tbl + BPB_TotSec16, n_vol);
  3543. } else {
  3544. ST_DWORD(tbl + BPB_TotSec32, n_vol);
  3545. }
  3546. tbl[BPB_Media] = md; /* Media descriptor */
  3547. ST_WORD(tbl + BPB_SecPerTrk, 63); /* Number of sectors per track */
  3548. ST_WORD(tbl + BPB_NumHeads, 255); /* Number of heads */
  3549. ST_DWORD(tbl + BPB_HiddSec, b_vol); /* Hidden sectors */
  3550. n = GET_FATTIME(); /* Use current time as VSN */
  3551. if (fmt == FS_FAT32) {
  3552. ST_DWORD(tbl + BS_VolID32, n); /* VSN */
  3553. ST_DWORD(tbl + BPB_FATSz32, n_fat); /* Number of sectors per FAT */
  3554. ST_DWORD(tbl + BPB_RootClus, 2); /* Root directory start cluster (2) */
  3555. ST_WORD(tbl + BPB_FSInfo, 1); /* FSINFO record offset (VBR + 1) */
  3556. ST_WORD(tbl + BPB_BkBootSec, 6); /* Backup boot record offset (VBR + 6) */
  3557. tbl[BS_DrvNum32] = 0x80; /* Drive number */
  3558. tbl[BS_BootSig32] = 0x29; /* Extended boot signature */
  3559. mem_cpy(tbl + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  3560. } else {
  3561. ST_DWORD(tbl + BS_VolID, n); /* VSN */
  3562. ST_WORD(tbl + BPB_FATSz16, n_fat); /* Number of sectors per FAT */
  3563. tbl[BS_DrvNum] = 0x80; /* Drive number */
  3564. tbl[BS_BootSig] = 0x29; /* Extended boot signature */
  3565. mem_cpy(tbl + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  3566. }
  3567. ST_WORD(tbl + BS_55AA, 0xAA55); /* Signature (Offset is fixed here regardless of sector size) */
  3568. if (disk_write(pdrv, tbl, b_vol, 1) != RES_OK) /* Write it to the VBR sector */
  3569. return FR_DISK_ERR;
  3570. if (fmt == FS_FAT32) /* Write backup VBR if needed (VBR + 6) */
  3571. disk_write(pdrv, tbl, b_vol + 6, 1);
  3572. /* Initialize FAT area */
  3573. wsect = b_fat;
  3574. for (i = 0; i < N_FATS; i++) { /* Initialize each FAT copy */
  3575. mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */
  3576. n = md; /* Media descriptor byte */
  3577. if (fmt != FS_FAT32) {
  3578. n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
  3579. ST_DWORD(tbl + 0, n); /* Reserve cluster #0-1 (FAT12/16) */
  3580. } else {
  3581. n |= 0xFFFFFF00;
  3582. ST_DWORD(tbl + 0, n); /* Reserve cluster #0-1 (FAT32) */
  3583. ST_DWORD(tbl + 4, 0xFFFFFFFF);
  3584. ST_DWORD(tbl + 8, 0x0FFFFFFF); /* Reserve cluster #2 for root directory */
  3585. }
  3586. if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK)
  3587. return FR_DISK_ERR;
  3588. mem_set(tbl, 0, SS(fs)); /* Fill following FAT entries with zero */
  3589. for (n = 1; n < n_fat; n++) { /* This loop may take a time on FAT32 volume due to many single sector writes */
  3590. if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK)
  3591. return FR_DISK_ERR;
  3592. }
  3593. }
  3594. /* Initialize root directory */
  3595. i = (fmt == FS_FAT32) ? au : (UINT)n_dir;
  3596. do {
  3597. if (disk_write(pdrv, tbl, wsect++, 1) != RES_OK)
  3598. return FR_DISK_ERR;
  3599. } while (--i);
  3600. #if _USE_TRIM /* Erase data area if needed */
  3601. {
  3602. eb[0] = wsect; eb[1] = wsect + (n_clst - ((fmt == FS_FAT32) ? 1 : 0)) * au - 1;
  3603. disk_ioctl(pdrv, CTRL_TRIM, eb);
  3604. }
  3605. #endif
  3606. /* Create FSINFO if needed */
  3607. if (fmt == FS_FAT32) {
  3608. ST_DWORD(tbl + FSI_LeadSig, 0x41615252);
  3609. ST_DWORD(tbl + FSI_StrucSig, 0x61417272);
  3610. ST_DWORD(tbl + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  3611. ST_DWORD(tbl + FSI_Nxt_Free, 2); /* Last allocated cluster# */
  3612. ST_WORD(tbl + BS_55AA, 0xAA55);
  3613. disk_write(pdrv, tbl, b_vol + 1, 1); /* Write original (VBR + 1) */
  3614. disk_write(pdrv, tbl, b_vol + 7, 1); /* Write backup (VBR + 7) */
  3615. }
  3616. return (disk_ioctl(pdrv, CTRL_SYNC, 0) == RES_OK) ? FR_OK : FR_DISK_ERR;
  3617. }
  3618. #if _MULTI_PARTITION
  3619. /*-----------------------------------------------------------------------*/
  3620. /* Create partition table on the physical drive */
  3621. /*-----------------------------------------------------------------------*/
  3622. FRESULT f_fdisk (
  3623. BYTE pdrv, /* Physical drive number */
  3624. const DWORD szt[], /* Pointer to the size table for each partitions */
  3625. void* work /* Pointer to the working buffer */
  3626. )
  3627. {
  3628. UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
  3629. BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
  3630. DSTATUS stat;
  3631. DWORD sz_disk, sz_part, s_part;
  3632. stat = disk_initialize(pdrv);
  3633. if (stat & STA_NOINIT) return FR_NOT_READY;
  3634. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  3635. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
  3636. /* Determine CHS in the table regardless of the drive geometry */
  3637. for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
  3638. if (n == 256) n--;
  3639. e_hd = n - 1;
  3640. sz_cyl = 63 * n;
  3641. tot_cyl = sz_disk / sz_cyl;
  3642. /* Create partition table */
  3643. mem_set(buf, 0, _MAX_SS);
  3644. p = buf + MBR_Table; b_cyl = 0;
  3645. for (i = 0; i < 4; i++, p += SZ_PTE) {
  3646. p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
  3647. if (!p_cyl) continue;
  3648. s_part = (DWORD)sz_cyl * b_cyl;
  3649. sz_part = (DWORD)sz_cyl * p_cyl;
  3650. if (i == 0) { /* Exclude first track of cylinder 0 */
  3651. s_hd = 1;
  3652. s_part += 63; sz_part -= 63;
  3653. } else {
  3654. s_hd = 0;
  3655. }
  3656. e_cyl = b_cyl + p_cyl - 1;
  3657. if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
  3658. /* Set partition table */
  3659. p[1] = s_hd; /* Start head */
  3660. p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
  3661. p[3] = (BYTE)b_cyl; /* Start cylinder */
  3662. p[4] = 0x06; /* System type (temporary setting) */
  3663. p[5] = e_hd; /* End head */
  3664. p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
  3665. p[7] = (BYTE)e_cyl; /* End cylinder */
  3666. ST_DWORD(p + 8, s_part); /* Start sector in LBA */
  3667. ST_DWORD(p + 12, sz_part); /* Partition size */
  3668. /* Next partition */
  3669. b_cyl += p_cyl;
  3670. }
  3671. ST_WORD(p, 0xAA55);
  3672. /* Write it to the MBR */
  3673. return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
  3674. }
  3675. #endif /* _MULTI_PARTITION */
  3676. #endif /* _USE_MKFS && !_FS_READONLY */
  3677. #if _USE_STRFUNC
  3678. /*-----------------------------------------------------------------------*/
  3679. /* Get a string from the file */
  3680. /*-----------------------------------------------------------------------*/
  3681. TCHAR* f_gets (
  3682. TCHAR* buff, /* Pointer to the string buffer to read */
  3683. int len, /* Size of string buffer (characters) */
  3684. FIL* fp /* Pointer to the file object */
  3685. )
  3686. {
  3687. int n = 0;
  3688. TCHAR c, *p = buff;
  3689. BYTE s[2];
  3690. UINT rc;
  3691. while (n < len - 1) { /* Read characters until buffer gets filled */
  3692. #if _USE_LFN && _LFN_UNICODE
  3693. #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
  3694. f_read(fp, s, 1, &rc);
  3695. if (rc != 1) break;
  3696. c = s[0];
  3697. if (c >= 0x80) {
  3698. if (c < 0xC0) continue; /* Skip stray trailer */
  3699. if (c < 0xE0) { /* Two-byte sequence */
  3700. f_read(fp, s, 1, &rc);
  3701. if (rc != 1) break;
  3702. c = (c & 0x1F) << 6 | (s[0] & 0x3F);
  3703. if (c < 0x80) c = '?';
  3704. } else {
  3705. if (c < 0xF0) { /* Three-byte sequence */
  3706. f_read(fp, s, 2, &rc);
  3707. if (rc != 2) break;
  3708. c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F);
  3709. if (c < 0x800) c = '?';
  3710. } else { /* Reject four-byte sequence */
  3711. c = '?';
  3712. }
  3713. }
  3714. }
  3715. #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
  3716. f_read(fp, s, 2, &rc);
  3717. if (rc != 2) break;
  3718. c = s[1] + (s[0] << 8);
  3719. #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
  3720. f_read(fp, s, 2, &rc);
  3721. if (rc != 2) break;
  3722. c = s[0] + (s[1] << 8);
  3723. #else /* Read a character in ANSI/OEM */
  3724. f_read(fp, s, 1, &rc);
  3725. if (rc != 1) break;
  3726. c = s[0];
  3727. if (IsDBCS1(c)) {
  3728. f_read(fp, s, 1, &rc);
  3729. if (rc != 1) break;
  3730. c = (c << 8) + s[0];
  3731. }
  3732. c = ff_convert(c, 1); /* OEM -> Unicode */
  3733. if (!c) c = '?';
  3734. #endif
  3735. #else /* Read a character without conversion */
  3736. f_read(fp, s, 1, &rc);
  3737. if (rc != 1) break;
  3738. c = s[0];
  3739. #endif
  3740. if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */
  3741. *p++ = c;
  3742. n++;
  3743. if (c == '\n') break; /* Break on EOL */
  3744. }
  3745. *p = 0;
  3746. return n ? buff : 0; /* When no data read (eof or error), return with error. */
  3747. }
  3748. #if !_FS_READONLY
  3749. #include <stdarg.h>
  3750. /*-----------------------------------------------------------------------*/
  3751. /* Put a character to the file */
  3752. /*-----------------------------------------------------------------------*/
  3753. typedef struct {
  3754. FIL* fp;
  3755. int idx, nchr;
  3756. BYTE buf[64];
  3757. } putbuff;
  3758. static
  3759. void putc_bfd (
  3760. putbuff* pb,
  3761. TCHAR c
  3762. )
  3763. {
  3764. UINT bw;
  3765. int i;
  3766. if (_USE_STRFUNC == 2 && c == '\n') /* LF -> CRLF conversion */
  3767. putc_bfd(pb, '\r');
  3768. i = pb->idx; /* Buffer write index (-1:error) */
  3769. if (i < 0) return;
  3770. #if _USE_LFN && _LFN_UNICODE
  3771. #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
  3772. if (c < 0x80) { /* 7-bit */
  3773. pb->buf[i++] = (BYTE)c;
  3774. } else {
  3775. if (c < 0x800) { /* 11-bit */
  3776. pb->buf[i++] = (BYTE)(0xC0 | c >> 6);
  3777. } else { /* 16-bit */
  3778. pb->buf[i++] = (BYTE)(0xE0 | c >> 12);
  3779. pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F));
  3780. }
  3781. pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F));
  3782. }
  3783. #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
  3784. pb->buf[i++] = (BYTE)(c >> 8);
  3785. pb->buf[i++] = (BYTE)c;
  3786. #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
  3787. pb->buf[i++] = (BYTE)c;
  3788. pb->buf[i++] = (BYTE)(c >> 8);
  3789. #else /* Write a character in ANSI/OEM */
  3790. c = ff_convert(c, 0); /* Unicode -> OEM */
  3791. if (!c) c = '?';
  3792. if (c >= 0x100)
  3793. pb->buf[i++] = (BYTE)(c >> 8);
  3794. pb->buf[i++] = (BYTE)c;
  3795. #endif
  3796. #else /* Write a character without conversion */
  3797. pb->buf[i++] = (BYTE)c;
  3798. #endif
  3799. if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */
  3800. f_write(pb->fp, pb->buf, (UINT)i, &bw);
  3801. i = (bw == (UINT)i) ? 0 : -1;
  3802. }
  3803. pb->idx = i;
  3804. pb->nchr++;
  3805. }
  3806. int f_putc (
  3807. TCHAR c, /* A character to be output */
  3808. FIL* fp /* Pointer to the file object */
  3809. )
  3810. {
  3811. putbuff pb;
  3812. UINT nw;
  3813. pb.fp = fp; /* Initialize output buffer */
  3814. pb.nchr = pb.idx = 0;
  3815. putc_bfd(&pb, c); /* Put a character */
  3816. if ( pb.idx >= 0 /* Flush buffered characters to the file */
  3817. && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK
  3818. && (UINT)pb.idx == nw) return pb.nchr;
  3819. return EOF;
  3820. }
  3821. /*-----------------------------------------------------------------------*/
  3822. /* Put a string to the file */
  3823. /*-----------------------------------------------------------------------*/
  3824. int f_puts (
  3825. const TCHAR* str, /* Pointer to the string to be output */
  3826. FIL* fp /* Pointer to the file object */
  3827. )
  3828. {
  3829. putbuff pb;
  3830. UINT nw;
  3831. pb.fp = fp; /* Initialize output buffer */
  3832. pb.nchr = pb.idx = 0;
  3833. while (*str) /* Put the string */
  3834. putc_bfd(&pb, *str++);
  3835. if ( pb.idx >= 0 /* Flush buffered characters to the file */
  3836. && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK
  3837. && (UINT)pb.idx == nw) return pb.nchr;
  3838. return EOF;
  3839. }
  3840. /*-----------------------------------------------------------------------*/
  3841. /* Put a formatted string to the file */
  3842. /*-----------------------------------------------------------------------*/
  3843. int f_printf (
  3844. FIL* fp, /* Pointer to the file object */
  3845. const TCHAR* fmt, /* Pointer to the format string */
  3846. ... /* Optional arguments... */
  3847. )
  3848. {
  3849. va_list arp;
  3850. BYTE f, r;
  3851. UINT nw, i, j, w;
  3852. DWORD v;
  3853. TCHAR c, d, s[16], *p;
  3854. putbuff pb;
  3855. pb.fp = fp; /* Initialize output buffer */
  3856. pb.nchr = pb.idx = 0;
  3857. va_start(arp, fmt);
  3858. for (;;) {
  3859. c = *fmt++;
  3860. if (c == 0) break; /* End of string */
  3861. if (c != '%') { /* Non escape character */
  3862. putc_bfd(&pb, c);
  3863. continue;
  3864. }
  3865. w = f = 0;
  3866. c = *fmt++;
  3867. if (c == '0') { /* Flag: '0' padding */
  3868. f = 1; c = *fmt++;
  3869. } else {
  3870. if (c == '-') { /* Flag: left justified */
  3871. f = 2; c = *fmt++;
  3872. }
  3873. }
  3874. while (IsDigit(c)) { /* Precision */
  3875. w = w * 10 + c - '0';
  3876. c = *fmt++;
  3877. }
  3878. if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
  3879. f |= 4; c = *fmt++;
  3880. }
  3881. if (!c) break;
  3882. d = c;
  3883. if (IsLower(d)) d -= 0x20;
  3884. switch (d) { /* Type is... */
  3885. case 'S' : /* String */
  3886. p = va_arg(arp, TCHAR*);
  3887. for (j = 0; p[j]; j++) ;
  3888. if (!(f & 2)) {
  3889. while (j++ < w) putc_bfd(&pb, ' ');
  3890. }
  3891. while (*p) putc_bfd(&pb, *p++);
  3892. while (j++ < w) putc_bfd(&pb, ' ');
  3893. continue;
  3894. case 'C' : /* Character */
  3895. putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;
  3896. case 'B' : /* Binary */
  3897. r = 2; break;
  3898. case 'O' : /* Octal */
  3899. r = 8; break;
  3900. case 'D' : /* Signed decimal */
  3901. case 'U' : /* Unsigned decimal */
  3902. r = 10; break;
  3903. case 'X' : /* Hexdecimal */
  3904. r = 16; break;
  3905. default: /* Unknown type (pass-through) */
  3906. putc_bfd(&pb, c); continue;
  3907. }
  3908. /* Get an argument and put it in numeral */
  3909. v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));
  3910. if (d == 'D' && (v & 0x80000000)) {
  3911. v = 0 - v;
  3912. f |= 8;
  3913. }
  3914. i = 0;
  3915. do {
  3916. d = (TCHAR)(v % r); v /= r;
  3917. if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  3918. s[i++] = d + '0';
  3919. } while (v && i < sizeof s / sizeof s[0]);
  3920. if (f & 8) s[i++] = '-';
  3921. j = i; d = (f & 1) ? '0' : ' ';
  3922. while (!(f & 2) && j++ < w) putc_bfd(&pb, d);
  3923. do putc_bfd(&pb, s[--i]); while (i);
  3924. while (j++ < w) putc_bfd(&pb, d);
  3925. }
  3926. va_end(arp);
  3927. if ( pb.idx >= 0 /* Flush buffered characters to the file */
  3928. && f_write(pb.fp, pb.buf, (UINT)pb.idx, &nw) == FR_OK
  3929. && (UINT)pb.idx == nw) return pb.nchr;
  3930. return EOF;
  3931. }
  3932. #endif /* !_FS_READONLY */
  3933. #endif /* _USE_STRFUNC */