ff.c 198 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - Generic FAT file system module R0.12b /
  3. /-----------------------------------------------------------------------------/
  4. /
  5. / Copyright (C) 2016, ChaN, all right reserved.
  6. /
  7. / FatFs module is an open source software. Redistribution and use of FatFs in
  8. / source and binary forms, with or without modification, are permitted provided
  9. / that the following condition is met:
  10. / 1. Redistributions of source code must retain the above copyright notice,
  11. / this condition and the following disclaimer.
  12. /
  13. / This software is provided by the copyright holder and contributors "AS IS"
  14. / and any warranties related to this software are DISCLAIMED.
  15. / The copyright owner or contributors be NOT LIABLE for any damages caused
  16. / by use of this software.
  17. /----------------------------------------------------------------------------*/
  18. #include "ff.h" /* Declarations of FatFs API */
  19. #include "diskio.h" /* Declarations of device I/O functions */
  20. /*--------------------------------------------------------------------------
  21. Module Private Definitions
  22. ---------------------------------------------------------------------------*/
  23. #if _FATFS != 68020 /* Revision ID */
  24. #error Wrong include file (ff.h).
  25. #endif
  26. #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
  27. /* Reentrancy related */
  28. #if _FS_REENTRANT
  29. #if _USE_LFN == 1
  30. #error Static LFN work area cannot be used at thread-safe configuration
  31. #endif
  32. #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; }
  33. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  34. #else
  35. #define ENTER_FF(fs)
  36. #define LEAVE_FF(fs, res) return res
  37. #endif
  38. /* Definitions of sector size */
  39. #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)
  40. #error Wrong sector size configuration
  41. #endif
  42. #if _MAX_SS == _MIN_SS
  43. #define SS(fs) ((UINT)_MAX_SS) /* Fixed sector size */
  44. #else
  45. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  46. #endif
  47. /* Timestamp */
  48. #if _FS_NORTC == 1
  49. #if _NORTC_YEAR < 1980 || _NORTC_YEAR > 2107 || _NORTC_MON < 1 || _NORTC_MON > 12 || _NORTC_MDAY < 1 || _NORTC_MDAY > 31
  50. #error Invalid _FS_NORTC settings
  51. #endif
  52. #define GET_FATTIME() ((DWORD)(_NORTC_YEAR - 1980) << 25 | (DWORD)_NORTC_MON << 21 | (DWORD)_NORTC_MDAY << 16)
  53. #else
  54. #define GET_FATTIME() get_fattime()
  55. #endif
  56. /* File lock controls */
  57. #if _FS_LOCK != 0
  58. #if _FS_READONLY
  59. #error _FS_LOCK must be 0 at read-only configuration
  60. #endif
  61. typedef struct {
  62. FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
  63. DWORD clu; /* Object ID 2, directory (0:root) */
  64. DWORD ofs; /* Object ID 3, directory offset */
  65. WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
  66. } FILESEM;
  67. #endif
  68. /* DBCS code ranges and SBCS upper conversion tables */
  69. #if _CODE_PAGE == 932 /* Japanese Shift-JIS */
  70. #define _DF1S 0x81 /* DBC 1st byte range 1 start */
  71. #define _DF1E 0x9F /* DBC 1st byte range 1 end */
  72. #define _DF2S 0xE0 /* DBC 1st byte range 2 start */
  73. #define _DF2E 0xFC /* DBC 1st byte range 2 end */
  74. #define _DS1S 0x40 /* DBC 2nd byte range 1 start */
  75. #define _DS1E 0x7E /* DBC 2nd byte range 1 end */
  76. #define _DS2S 0x80 /* DBC 2nd byte range 2 start */
  77. #define _DS2E 0xFC /* DBC 2nd byte range 2 end */
  78. #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */
  79. #define _DF1S 0x81
  80. #define _DF1E 0xFE
  81. #define _DS1S 0x40
  82. #define _DS1E 0x7E
  83. #define _DS2S 0x80
  84. #define _DS2E 0xFE
  85. #elif _CODE_PAGE == 949 /* Korean */
  86. #define _DF1S 0x81
  87. #define _DF1E 0xFE
  88. #define _DS1S 0x41
  89. #define _DS1E 0x5A
  90. #define _DS2S 0x61
  91. #define _DS2E 0x7A
  92. #define _DS3S 0x81
  93. #define _DS3E 0xFE
  94. #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */
  95. #define _DF1S 0x81
  96. #define _DF1E 0xFE
  97. #define _DS1S 0x40
  98. #define _DS1E 0x7E
  99. #define _DS2S 0xA1
  100. #define _DS2E 0xFE
  101. #elif _CODE_PAGE == 437 /* U.S. */
  102. #define _DF1S 0
  103. #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  104. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  105. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  106. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  107. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  108. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  109. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  110. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  111. #elif _CODE_PAGE == 720 /* Arabic */
  112. #define _DF1S 0
  113. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  114. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  115. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  116. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  117. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  118. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  119. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  120. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  121. #elif _CODE_PAGE == 737 /* Greek */
  122. #define _DF1S 0
  123. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  124. 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  125. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
  126. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  127. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  128. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  129. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  130. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  131. #elif _CODE_PAGE == 771 /* KBL */
  132. #define _DF1S 0
  133. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  134. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  135. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  136. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  137. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  138. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
  139. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  140. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
  141. #elif _CODE_PAGE == 775 /* Baltic */
  142. #define _DF1S 0
  143. #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
  144. 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  145. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  146. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  147. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  148. 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  149. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
  150. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  151. #elif _CODE_PAGE == 850 /* Latin 1 */
  152. #define _DF1S 0
  153. #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
  154. 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
  155. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  156. 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  157. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  158. 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
  159. 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
  160. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  161. #elif _CODE_PAGE == 852 /* Latin 2 */
  162. #define _DF1S 0
  163. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
  164. 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
  165. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
  166. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  167. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  168. 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  169. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
  170. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  171. #elif _CODE_PAGE == 855 /* Cyrillic */
  172. #define _DF1S 0
  173. #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
  174. 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  175. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
  176. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  177. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  178. 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  179. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
  180. 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  181. #elif _CODE_PAGE == 857 /* Turkish */
  182. #define _DF1S 0
  183. #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
  184. 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  185. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  186. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  187. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  188. 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  189. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
  190. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  191. #elif _CODE_PAGE == 860 /* Portuguese */
  192. #define _DF1S 0
  193. #define _EXCVT {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
  194. 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  195. 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  196. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  197. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  198. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  199. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  200. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  201. #elif _CODE_PAGE == 861 /* Icelandic */
  202. #define _DF1S 0
  203. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
  204. 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  205. 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  206. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  207. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  208. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  209. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  210. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  211. #elif _CODE_PAGE == 862 /* Hebrew */
  212. #define _DF1S 0
  213. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  214. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  215. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  216. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  217. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  218. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  219. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  220. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  221. #elif _CODE_PAGE == 863 /* Canadian-French */
  222. #define _DF1S 0
  223. #define _EXCVT {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
  224. 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
  225. 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  226. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  227. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  228. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  229. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  230. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  231. #elif _CODE_PAGE == 864 /* Arabic */
  232. #define _DF1S 0
  233. #define _EXCVT {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  234. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  235. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  236. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  237. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  238. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  239. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  240. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  241. #elif _CODE_PAGE == 865 /* Nordic */
  242. #define _DF1S 0
  243. #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  244. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  245. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  246. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  247. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  248. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  249. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  250. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  251. #elif _CODE_PAGE == 866 /* Russian */
  252. #define _DF1S 0
  253. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  254. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  255. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  256. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  257. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  258. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  259. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  260. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  261. #elif _CODE_PAGE == 869 /* Greek 2 */
  262. #define _DF1S 0
  263. #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  264. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
  265. 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  266. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  267. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  268. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
  269. 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
  270. 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
  271. #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */
  272. #if _USE_LFN != 0
  273. #error Cannot enable LFN without valid code page.
  274. #endif
  275. #define _DF1S 0
  276. #else
  277. #error Unknown code page
  278. #endif
  279. /* Character code support macros */
  280. #define IsUpper(c) (((c)>='A')&&((c)<='Z'))
  281. #define IsLower(c) (((c)>='a')&&((c)<='z'))
  282. #define IsDigit(c) (((c)>='0')&&((c)<='9'))
  283. #if _DF1S != 0 /* Code page is DBCS */
  284. #ifdef _DF2S /* Two 1st byte areas */
  285. #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
  286. #else /* One 1st byte area */
  287. #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
  288. #endif
  289. #ifdef _DS3S /* Three 2nd byte areas */
  290. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
  291. #else /* Two 2nd byte areas */
  292. #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
  293. #endif
  294. #else /* Code page is SBCS */
  295. #define IsDBCS1(c) 0
  296. #define IsDBCS2(c) 0
  297. #endif /* _DF1S */
  298. /* File attribute bits (internal use) */
  299. #define AM_VOL 0x08 /* Volume label */
  300. #define AM_LFN 0x0F /* LFN entry */
  301. #define AM_MASK 0x3F /* Mask of defined bits */
  302. /* File access control and file status flags (internal use) */
  303. #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
  304. #define FA_MODIFIED 0x40 /* File has been modified */
  305. #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
  306. /* Name status flags */
  307. #define NSFLAG 11 /* Index of name status byte in fn[] */
  308. #define NS_LOSS 0x01 /* Out of 8.3 format */
  309. #define NS_LFN 0x02 /* Force to create LFN entry */
  310. #define NS_LAST 0x04 /* Last segment */
  311. #define NS_BODY 0x08 /* Lower case flag (body) */
  312. #define NS_EXT 0x10 /* Lower case flag (ext) */
  313. #define NS_DOT 0x20 /* Dot entry */
  314. #define NS_NOLFN 0x40 /* Do not find LFN */
  315. #define NS_NONAME 0x80 /* Not followed */
  316. /* Limits and boundaries (differ from specs but correct for real DOS/Windows) */
  317. #define MAX_FAT12 0xFF5 /* Maximum number of FAT12 clusters */
  318. #define MAX_FAT16 0xFFF5 /* Maximum number of FAT16 clusters */
  319. #define MAX_FAT32 0xFFFFFF5 /* Maximum number of FAT32 clusters */
  320. #define MAX_EXFAT 0x7FFFFFFD /* Maximum number of exFAT clusters (limited by implementation) */
  321. #define MAX_DIR 0x200000 /* Maximum size of FAT directory */
  322. #define MAX_DIR_EX 0x10000000 /* Maximum size of exFAT directory */
  323. /* FatFs refers the members in the FAT structures as byte array instead of
  324. / structure members because the structure is not binary compatible between
  325. / different platforms */
  326. #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
  327. #define BS_OEMName 3 /* OEM name (8-byte) */
  328. #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
  329. #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
  330. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
  331. #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
  332. #define BPB_RootEntCnt 17 /* Size of root directory area for FAT12/16 [entry] (WORD) */
  333. #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
  334. #define BPB_Media 21 /* Media descriptor byte (BYTE) */
  335. #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
  336. #define BPB_SecPerTrk 24 /* Track size for int13h [sector] (WORD) */
  337. #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
  338. #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
  339. #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
  340. #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
  341. #define BS_NTres 37 /* Error flag (BYTE) */
  342. #define BS_BootSig 38 /* Extended boot signature (BYTE) */
  343. #define BS_VolID 39 /* Volume serial number (DWORD) */
  344. #define BS_VolLab 43 /* Volume label string (8-byte) */
  345. #define BS_FilSysType 54 /* File system type string (8-byte) */
  346. #define BS_BootCode 62 /* Boot code (448-byte) */
  347. #define BS_55AA 510 /* Signature word (WORD) */
  348. #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
  349. #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
  350. #define BPB_FSVer32 42 /* FAT32: File system version (WORD) */
  351. #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
  352. #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
  353. #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
  354. #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
  355. #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
  356. #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
  357. #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
  358. #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
  359. #define BS_FilSysType32 82 /* FAT32: File system type string (8-byte) */
  360. #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
  361. #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
  362. #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
  363. #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
  364. #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
  365. #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
  366. #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
  367. #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
  368. #define BPB_RootClusEx 96 /* exFAT: Root directory cluster (DWORD) */
  369. #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
  370. #define BPB_FSVerEx 104 /* exFAT: File system version (WORD) */
  371. #define BPB_VolFlagEx 106 /* exFAT: Volume flags (BYTE) */
  372. #define BPB_ActFatEx 107 /* exFAT: Active FAT flags (BYTE) */
  373. #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in byte (BYTE) */
  374. #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in sector (BYTE) */
  375. #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
  376. #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
  377. #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
  378. #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
  379. #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
  380. #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
  381. #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
  382. #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
  383. #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
  384. #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
  385. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  386. #define PTE_Boot 0 /* MBR PTE: Boot indicator */
  387. #define PTE_StHead 1 /* MBR PTE: Start head */
  388. #define PTE_StSec 2 /* MBR PTE: Start sector */
  389. #define PTE_StCyl 3 /* MBR PTE: Start cylinder */
  390. #define PTE_System 4 /* MBR PTE: System ID */
  391. #define PTE_EdHead 5 /* MBR PTE: End head */
  392. #define PTE_EdSec 6 /* MBR PTE: End sector */
  393. #define PTE_EdCyl 7 /* MBR PTE: End cylinder */
  394. #define PTE_StLba 8 /* MBR PTE: Start in LBA */
  395. #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
  396. #define DIR_Name 0 /* Short file name (11-byte) */
  397. #define DIR_Attr 11 /* Attribute (BYTE) */
  398. #define DIR_NTres 12 /* Lower case flag (BYTE) */
  399. #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
  400. #define DIR_CrtTime 14 /* Created time (DWORD) */
  401. #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
  402. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
  403. #define DIR_ModTime 22 /* Modified time (DWORD) */
  404. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
  405. #define DIR_FileSize 28 /* File size (DWORD) */
  406. #define LDIR_Ord 0 /* LFN entry order and LLE flag (BYTE) */
  407. #define LDIR_Attr 11 /* LFN attribute (BYTE) */
  408. #define LDIR_Type 12 /* LFN type (BYTE) */
  409. #define LDIR_Chksum 13 /* Checksum of the SFN entry (BYTE) */
  410. #define LDIR_FstClusLO 26 /* Must be zero (WORD) */
  411. #define XDIR_Type 0 /* Type of exFAT directory entry (BYTE) */
  412. #define XDIR_NumLabel 1 /* Number of volume label characters (BYTE) */
  413. #define XDIR_Label 2 /* Volume label (11-WORD) */
  414. #define XDIR_CaseSum 4 /* Sum of case conversion table (DWORD) */
  415. #define XDIR_NumSec 1 /* Number of secondary entries (BYTE) */
  416. #define XDIR_SetSum 2 /* Sum of the set of directory entries (WORD) */
  417. #define XDIR_Attr 4 /* File attribute (WORD) */
  418. #define XDIR_CrtTime 8 /* Created time (DWORD) */
  419. #define XDIR_ModTime 12 /* Modified time (DWORD) */
  420. #define XDIR_AccTime 16 /* Last accessed time (DWORD) */
  421. #define XDIR_CrtTime10 20 /* Created time subsecond (BYTE) */
  422. #define XDIR_ModTime10 21 /* Modified time subsecond (BYTE) */
  423. #define XDIR_CrtTZ 22 /* Created timezone (BYTE) */
  424. #define XDIR_ModTZ 23 /* Modified timezone (BYTE) */
  425. #define XDIR_AccTZ 24 /* Last accessed timezone (BYTE) */
  426. #define XDIR_GenFlags 33 /* Gneral secondary flags (WORD) */
  427. #define XDIR_NumName 35 /* Number of file name characters (BYTE) */
  428. #define XDIR_NameHash 36 /* Hash of file name (WORD) */
  429. #define XDIR_ValidFileSize 40 /* Valid file size (QWORD) */
  430. #define XDIR_FstClus 52 /* First cluster of the file data (DWORD) */
  431. #define XDIR_FileSize 56 /* File/Directory size (QWORD) */
  432. #define SZDIRE 32 /* Size of a directory entry */
  433. #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
  434. #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
  435. #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
  436. /*--------------------------------------------------------------------------
  437. Module Private Work Area
  438. ---------------------------------------------------------------------------*/
  439. /* Remark: Variables here without initial value shall be guaranteed zero/null
  440. / at start-up. If not, either the linker or start-up routine being used is
  441. / not compliance with C standard. */
  442. #if _VOLUMES < 1 || _VOLUMES > 9
  443. #error Wrong _VOLUMES setting
  444. #endif
  445. static FATFS *FatFs[_VOLUMES]; /* Pointer to the file system objects (logical drives) */
  446. static WORD Fsid; /* File system mount ID */
  447. #if _FS_RPATH != 0 && _VOLUMES >= 2
  448. static BYTE CurrVol; /* Current drive */
  449. #endif
  450. #if _FS_LOCK != 0
  451. static FILESEM Files[_FS_LOCK]; /* Open object lock semaphores */
  452. #endif
  453. #if _USE_LFN == 0 /* Non-LFN configuration */
  454. #define DEF_NAMBUF
  455. #define INIT_NAMBUF(fs)
  456. #define FREE_NAMBUF()
  457. #else
  458. #if _MAX_LFN < 12 || _MAX_LFN > 255
  459. #error Wrong _MAX_LFN setting
  460. #endif
  461. #if _USE_LFN == 1 /* LFN enabled with static working buffer */
  462. #if _FS_EXFAT
  463. static BYTE DirBuf[SZDIRE*19]; /* Directory entry block scratchpad buffer (19 entries in size) */
  464. #endif
  465. static WCHAR LfnBuf[_MAX_LFN+1]; /* LFN enabled with static working buffer */
  466. #define DEF_NAMBUF
  467. #define INIT_NAMBUF(fs)
  468. #define FREE_NAMBUF()
  469. #elif _USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
  470. #if _FS_EXFAT
  471. #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1]; BYTE dbuf[SZDIRE*19];
  472. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
  473. #define FREE_NAMBUF()
  474. #else
  475. #define DEF_NAMBUF WCHAR lbuf[_MAX_LFN+1];
  476. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
  477. #define FREE_NAMBUF()
  478. #endif
  479. #elif _USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
  480. #if _FS_EXFAT
  481. #define DEF_NAMBUF WCHAR *lfn;
  482. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((_MAX_LFN+1)*2 + SZDIRE*19); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+_MAX_LFN+1); }
  483. #define FREE_NAMBUF() ff_memfree(lfn)
  484. #else
  485. #define DEF_NAMBUF WCHAR *lfn;
  486. #define INIT_NAMBUF(fs) { lfn = (WCHAR *)ff_memalloc((_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
  487. #define FREE_NAMBUF() ff_memfree(lfn)
  488. #endif
  489. #else
  490. #error Wrong _USE_LFN setting
  491. #endif
  492. #endif
  493. #ifdef _EXCVT
  494. static const BYTE ExCvt[] = _EXCVT; /* Upper conversion table for SBCS extended characters */
  495. #endif
  496. /*--------------------------------------------------------------------------
  497. Module Private Functions
  498. ---------------------------------------------------------------------------*/
  499. /*-----------------------------------------------------------------------*/
  500. /* Load/Store multi-byte word in the FAT structure */
  501. /*-----------------------------------------------------------------------*/
  502. static
  503. WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
  504. {
  505. WORD rv;
  506. rv = ptr[1];
  507. rv = rv << 8 | ptr[0];
  508. return rv;
  509. }
  510. static
  511. DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
  512. {
  513. DWORD rv;
  514. rv = ptr[3];
  515. rv = rv << 8 | ptr[2];
  516. rv = rv << 8 | ptr[1];
  517. rv = rv << 8 | ptr[0];
  518. return rv;
  519. }
  520. #if _FS_EXFAT
  521. static
  522. QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
  523. {
  524. QWORD rv;
  525. rv = ptr[7];
  526. rv = rv << 8 | ptr[6];
  527. rv = rv << 8 | ptr[5];
  528. rv = rv << 8 | ptr[4];
  529. rv = rv << 8 | ptr[3];
  530. rv = rv << 8 | ptr[2];
  531. rv = rv << 8 | ptr[1];
  532. rv = rv << 8 | ptr[0];
  533. return rv;
  534. }
  535. #endif
  536. #if !_FS_READONLY
  537. static
  538. void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
  539. {
  540. *ptr++ = (BYTE)val; val >>= 8;
  541. *ptr++ = (BYTE)val;
  542. }
  543. static
  544. void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
  545. {
  546. *ptr++ = (BYTE)val; val >>= 8;
  547. *ptr++ = (BYTE)val; val >>= 8;
  548. *ptr++ = (BYTE)val; val >>= 8;
  549. *ptr++ = (BYTE)val;
  550. }
  551. #if _FS_EXFAT
  552. static
  553. void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
  554. {
  555. *ptr++ = (BYTE)val; val >>= 8;
  556. *ptr++ = (BYTE)val; val >>= 8;
  557. *ptr++ = (BYTE)val; val >>= 8;
  558. *ptr++ = (BYTE)val; val >>= 8;
  559. *ptr++ = (BYTE)val; val >>= 8;
  560. *ptr++ = (BYTE)val; val >>= 8;
  561. *ptr++ = (BYTE)val; val >>= 8;
  562. *ptr++ = (BYTE)val;
  563. }
  564. #endif
  565. #endif /* !_FS_READONLY */
  566. /*-----------------------------------------------------------------------*/
  567. /* String functions */
  568. /*-----------------------------------------------------------------------*/
  569. /* Copy memory to memory */
  570. static
  571. void mem_cpy (void* dst, const void* src, UINT cnt) {
  572. BYTE *d = (BYTE*)dst;
  573. const BYTE *s = (const BYTE*)src;
  574. if (cnt) {
  575. do *d++ = *s++; while (--cnt);
  576. }
  577. }
  578. /* Fill memory block */
  579. static
  580. void mem_set (void* dst, int val, UINT cnt) {
  581. BYTE *d = (BYTE*)dst;
  582. do *d++ = (BYTE)val; while (--cnt);
  583. }
  584. /* Compare memory block */
  585. static
  586. int mem_cmp (const void* dst, const void* src, UINT cnt) { /* ZR:same, NZ:different */
  587. const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
  588. int r = 0;
  589. do {
  590. r = *d++ - *s++;
  591. } while (--cnt && r == 0);
  592. return r;
  593. }
  594. /* Check if chr is contained in the string */
  595. static
  596. int chk_chr (const char* str, int chr) { /* NZ:contained, ZR:not contained */
  597. while (*str && *str != chr) str++;
  598. return *str;
  599. }
  600. #if _FS_REENTRANT
  601. /*-----------------------------------------------------------------------*/
  602. /* Request/Release grant to access the volume */
  603. /*-----------------------------------------------------------------------*/
  604. static
  605. int lock_fs (
  606. FATFS* fs /* File system object */
  607. )
  608. {
  609. return ff_req_grant(fs->sobj);
  610. }
  611. static
  612. void unlock_fs (
  613. FATFS* fs, /* File system object */
  614. FRESULT res /* Result code to be returned */
  615. )
  616. {
  617. if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
  618. ff_rel_grant(fs->sobj);
  619. }
  620. }
  621. #endif
  622. #if _FS_LOCK != 0
  623. /*-----------------------------------------------------------------------*/
  624. /* File lock control functions */
  625. /*-----------------------------------------------------------------------*/
  626. static
  627. FRESULT chk_lock ( /* Check if the file can be accessed */
  628. DIR* dp, /* Directory object pointing the file to be checked */
  629. int acc /* Desired access type (0:Read, 1:Write, 2:Delete/Rename) */
  630. )
  631. {
  632. UINT i, be;
  633. /* Search file semaphore table */
  634. for (i = be = 0; i < _FS_LOCK; i++) {
  635. if (Files[i].fs) { /* Existing entry */
  636. if (Files[i].fs == dp->obj.fs && /* Check if the object matched with an open object */
  637. Files[i].clu == dp->obj.sclust &&
  638. Files[i].ofs == dp->dptr) break;
  639. } else { /* Blank entry */
  640. be = 1;
  641. }
  642. }
  643. if (i == _FS_LOCK) { /* The object is not opened */
  644. return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES; /* Is there a blank entry for new object? */
  645. }
  646. /* The object has been opened. Reject any open against writing file and all write mode open */
  647. return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  648. }
  649. static
  650. int enq_lock (void) /* Check if an entry is available for a new object */
  651. {
  652. UINT i;
  653. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  654. return (i == _FS_LOCK) ? 0 : 1;
  655. }
  656. static
  657. UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
  658. DIR* dp, /* Directory object pointing the file to register or increment */
  659. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  660. )
  661. {
  662. UINT i;
  663. for (i = 0; i < _FS_LOCK; i++) { /* Find the object */
  664. if (Files[i].fs == dp->obj.fs &&
  665. Files[i].clu == dp->obj.sclust &&
  666. Files[i].ofs == dp->dptr) break;
  667. }
  668. if (i == _FS_LOCK) { /* Not opened. Register it as new. */
  669. for (i = 0; i < _FS_LOCK && Files[i].fs; i++) ;
  670. if (i == _FS_LOCK) return 0; /* No free entry to register (int err) */
  671. Files[i].fs = dp->obj.fs;
  672. Files[i].clu = dp->obj.sclust;
  673. Files[i].ofs = dp->dptr;
  674. Files[i].ctr = 0;
  675. }
  676. if (acc && Files[i].ctr) return 0; /* Access violation (int err) */
  677. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  678. return i + 1;
  679. }
  680. static
  681. FRESULT dec_lock ( /* Decrement object open counter */
  682. UINT i /* Semaphore index (1..) */
  683. )
  684. {
  685. WORD n;
  686. FRESULT res;
  687. if (--i < _FS_LOCK) { /* Shift index number origin from 0 */
  688. n = Files[i].ctr;
  689. if (n == 0x100) n = 0; /* If write mode open, delete the entry */
  690. if (n > 0) n--; /* Decrement read mode open count */
  691. Files[i].ctr = n;
  692. if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
  693. res = FR_OK;
  694. } else {
  695. res = FR_INT_ERR; /* Invalid index nunber */
  696. }
  697. return res;
  698. }
  699. static
  700. void clear_lock ( /* Clear lock entries of the volume */
  701. FATFS *fs
  702. )
  703. {
  704. UINT i;
  705. for (i = 0; i < _FS_LOCK; i++) {
  706. if (Files[i].fs == fs) Files[i].fs = 0;
  707. }
  708. }
  709. #endif /* _FS_LOCK != 0 */
  710. /*-----------------------------------------------------------------------*/
  711. /* Move/Flush disk access window in the file system object */
  712. /*-----------------------------------------------------------------------*/
  713. #if !_FS_READONLY
  714. static
  715. FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERROR */
  716. FATFS* fs /* File system object */
  717. )
  718. {
  719. DWORD wsect;
  720. UINT nf;
  721. FRESULT res = FR_OK;
  722. if (fs->wflag) { /* Write back the sector if it is dirty */
  723. wsect = fs->winsect; /* Current sector number */
  724. if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK) {
  725. res = FR_DISK_ERR;
  726. } else {
  727. fs->wflag = 0;
  728. if (wsect - fs->fatbase < fs->fsize) { /* Is it in the FAT area? */
  729. for (nf = fs->n_fats; nf >= 2; nf--) { /* Reflect the change to all FAT copies */
  730. wsect += fs->fsize;
  731. disk_write(fs->drv, fs->win, wsect, 1);
  732. }
  733. }
  734. }
  735. }
  736. return res;
  737. }
  738. #endif
  739. static
  740. FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERROR */
  741. FATFS* fs, /* File system object */
  742. DWORD sector /* Sector number to make appearance in the fs->win[] */
  743. )
  744. {
  745. FRESULT res = FR_OK;
  746. if (sector != fs->winsect) { /* Window offset changed? */
  747. #if !_FS_READONLY
  748. res = sync_window(fs); /* Write-back changes */
  749. #endif
  750. if (res == FR_OK) { /* Fill sector window with new data */
  751. if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK) {
  752. sector = 0xFFFFFFFF; /* Invalidate window if data is not reliable */
  753. res = FR_DISK_ERR;
  754. }
  755. fs->winsect = sector;
  756. }
  757. }
  758. return res;
  759. }
  760. #if !_FS_READONLY
  761. /*-----------------------------------------------------------------------*/
  762. /* Synchronize file system and strage device */
  763. /*-----------------------------------------------------------------------*/
  764. static
  765. FRESULT sync_fs ( /* FR_OK:succeeded, !=0:error */
  766. FATFS* fs /* File system object */
  767. )
  768. {
  769. FRESULT res;
  770. res = sync_window(fs);
  771. if (res == FR_OK) {
  772. /* Update FSInfo sector if needed */
  773. if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) {
  774. /* Create FSInfo structure */
  775. mem_set(fs->win, 0, SS(fs));
  776. st_word(fs->win + BS_55AA, 0xAA55);
  777. st_dword(fs->win + FSI_LeadSig, 0x41615252);
  778. st_dword(fs->win + FSI_StrucSig, 0x61417272);
  779. st_dword(fs->win + FSI_Free_Count, fs->free_clst);
  780. st_dword(fs->win + FSI_Nxt_Free, fs->last_clst);
  781. /* Write it into the FSInfo sector */
  782. fs->winsect = fs->volbase + 1;
  783. disk_write(fs->drv, fs->win, fs->winsect, 1);
  784. fs->fsi_flag = 0;
  785. }
  786. /* Make sure that no pending write process in the physical drive */
  787. if (disk_ioctl(fs->drv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
  788. }
  789. return res;
  790. }
  791. #endif
  792. /*-----------------------------------------------------------------------*/
  793. /* Get sector# from cluster# */
  794. /*-----------------------------------------------------------------------*/
  795. static
  796. DWORD clust2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
  797. FATFS* fs, /* File system object */
  798. DWORD clst /* Cluster# to be converted */
  799. )
  800. {
  801. clst -= 2;
  802. if (clst >= fs->n_fatent - 2) return 0; /* Invalid cluster# */
  803. return clst * fs->csize + fs->database;
  804. }
  805. /*-----------------------------------------------------------------------*/
  806. /* FAT access - Read value of a FAT entry */
  807. /*-----------------------------------------------------------------------*/
  808. static
  809. DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
  810. _FDID* obj, /* Corresponding object */
  811. DWORD clst /* Cluster number to get the value */
  812. )
  813. {
  814. UINT wc, bc;
  815. DWORD val;
  816. FATFS *fs = obj->fs;
  817. if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
  818. val = 1; /* Internal error */
  819. } else {
  820. val = 0xFFFFFFFF; /* Default value falls on disk error */
  821. switch (fs->fs_type) {
  822. case FS_FAT12 :
  823. bc = (UINT)clst; bc += bc / 2;
  824. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  825. wc = fs->win[bc++ % SS(fs)];
  826. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  827. wc |= fs->win[bc % SS(fs)] << 8;
  828. val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
  829. break;
  830. case FS_FAT16 :
  831. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
  832. val = ld_word(fs->win + clst * 2 % SS(fs));
  833. break;
  834. case FS_FAT32 :
  835. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  836. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF;
  837. break;
  838. #if _FS_EXFAT
  839. case FS_EXFAT :
  840. if (obj->objsize) {
  841. DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
  842. DWORD clen = (DWORD)((obj->objsize - 1) / SS(fs)) / fs->csize; /* Number of clusters - 1 */
  843. if (obj->stat == 2) { /* Is there no valid chain on the FAT? */
  844. if (cofs <= clen) {
  845. val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* Generate the value */
  846. break;
  847. }
  848. }
  849. if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the contiguous part? */
  850. val = clst + 1; /* Generate the value */
  851. break;
  852. }
  853. if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
  854. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  855. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF;
  856. break;
  857. }
  858. }
  859. /* go next */
  860. #endif
  861. default:
  862. val = 1; /* Internal error */
  863. }
  864. }
  865. return val;
  866. }
  867. #if !_FS_READONLY
  868. /*-----------------------------------------------------------------------*/
  869. /* FAT access - Change value of a FAT entry */
  870. /*-----------------------------------------------------------------------*/
  871. static
  872. FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
  873. FATFS* fs, /* Corresponding file system object */
  874. DWORD clst, /* FAT index number (cluster number) to be changed */
  875. DWORD val /* New value to be set to the entry */
  876. )
  877. {
  878. UINT bc;
  879. BYTE *p;
  880. FRESULT res = FR_INT_ERR;
  881. if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
  882. switch (fs->fs_type) {
  883. case FS_FAT12 : /* Bitfield items */
  884. bc = (UINT)clst; bc += bc / 2;
  885. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  886. if (res != FR_OK) break;
  887. p = fs->win + bc++ % SS(fs);
  888. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
  889. fs->wflag = 1;
  890. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  891. if (res != FR_OK) break;
  892. p = fs->win + bc % SS(fs);
  893. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
  894. fs->wflag = 1;
  895. break;
  896. case FS_FAT16 : /* WORD aligned items */
  897. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  898. if (res != FR_OK) break;
  899. st_word(fs->win + clst * 2 % SS(fs), (WORD)val);
  900. fs->wflag = 1;
  901. break;
  902. case FS_FAT32 : /* DWORD aligned items */
  903. #if _FS_EXFAT
  904. case FS_EXFAT :
  905. #endif
  906. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  907. if (res != FR_OK) break;
  908. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  909. val = (val & 0x0FFFFFFF) | (ld_dword(fs->win + clst * 4 % SS(fs)) & 0xF0000000);
  910. }
  911. st_dword(fs->win + clst * 4 % SS(fs), val);
  912. fs->wflag = 1;
  913. break;
  914. }
  915. }
  916. return res;
  917. }
  918. #endif /* !_FS_READONLY */
  919. #if _FS_EXFAT && !_FS_READONLY
  920. /*-----------------------------------------------------------------------*/
  921. /* exFAT: Accessing FAT and Allocation Bitmap */
  922. /*-----------------------------------------------------------------------*/
  923. /*---------------------------------------------*/
  924. /* exFAT: Find a contiguous free cluster block */
  925. /*---------------------------------------------*/
  926. static
  927. DWORD find_bitmap ( /* 0:No free cluster, 2..:Free cluster found, 0xFFFFFFFF:Disk error */
  928. FATFS* fs, /* File system object */
  929. DWORD clst, /* Cluster number to scan from */
  930. DWORD ncl /* Number of contiguous clusters to find (1..) */
  931. )
  932. {
  933. BYTE bm, bv;
  934. UINT i;
  935. DWORD val, scl, ctr;
  936. clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
  937. if (clst >= fs->n_fatent - 2) clst = 0;
  938. scl = val = clst; ctr = 0;
  939. for (;;) {
  940. if (move_window(fs, fs->database + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF; /* (assuming bitmap is located top of the cluster heap) */
  941. i = val / 8 % SS(fs); bm = 1 << (val % 8);
  942. do {
  943. do {
  944. bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
  945. if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
  946. val = 0; bm = 0; i = 4096;
  947. }
  948. if (!bv) { /* Is it a free cluster? */
  949. if (++ctr == ncl) return scl + 2; /* Check run length */
  950. } else {
  951. scl = val; ctr = 0; /* Encountered a live cluster, restart to scan */
  952. }
  953. if (val == clst) return 0; /* All cluster scanned? */
  954. } while (bm);
  955. bm = 1;
  956. } while (++i < SS(fs));
  957. }
  958. }
  959. /*------------------------------------*/
  960. /* exFAT: Set/Clear a block of bitmap */
  961. /*------------------------------------*/
  962. static
  963. FRESULT change_bitmap (
  964. FATFS* fs, /* File system object */
  965. DWORD clst, /* Cluster number to change from */
  966. DWORD ncl, /* Number of clusters to be changed */
  967. int bv /* bit value to be set (0 or 1) */
  968. )
  969. {
  970. BYTE bm;
  971. UINT i;
  972. DWORD sect;
  973. clst -= 2; /* The first bit corresponds to cluster #2 */
  974. sect = fs->database + clst / 8 / SS(fs); /* Sector address (assuming bitmap is located top of the cluster heap) */
  975. i = clst / 8 % SS(fs); /* Byte offset in the sector */
  976. bm = 1 << (clst % 8); /* Bit mask in the byte */
  977. for (;;) {
  978. if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
  979. do {
  980. do {
  981. if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
  982. fs->win[i] ^= bm; /* Flip the bit */
  983. fs->wflag = 1;
  984. if (--ncl == 0) return FR_OK; /* All bits processed? */
  985. } while (bm <<= 1); /* Next bit */
  986. bm = 1;
  987. } while (++i < SS(fs)); /* Next byte */
  988. i = 0;
  989. }
  990. }
  991. /*---------------------------------------------*/
  992. /* Complement contiguous part of the FAT chain */
  993. /*---------------------------------------------*/
  994. static
  995. FRESULT fill_fat_chain (
  996. _FDID* obj /* Pointer to the corresponding object */
  997. )
  998. {
  999. FRESULT res;
  1000. DWORD cl, n;
  1001. if (obj->stat == 3) { /* Has the object been changed 'fragmented'? */
  1002. for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
  1003. res = put_fat(obj->fs, cl, cl + 1);
  1004. if (res != FR_OK) return res;
  1005. }
  1006. obj->stat = 0; /* Change status 'FAT chain is valid' */
  1007. }
  1008. return FR_OK;
  1009. }
  1010. #endif /* _FS_EXFAT && !_FS_READONLY */
  1011. #if !_FS_READONLY
  1012. /*-----------------------------------------------------------------------*/
  1013. /* FAT handling - Remove a cluster chain */
  1014. /*-----------------------------------------------------------------------*/
  1015. static
  1016. FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
  1017. _FDID* obj, /* Corresponding object */
  1018. DWORD clst, /* Cluster to remove a chain from */
  1019. DWORD pclst /* Previous cluster of clst (0:an entire chain) */
  1020. )
  1021. {
  1022. FRESULT res = FR_OK;
  1023. DWORD nxt;
  1024. FATFS *fs = obj->fs;
  1025. #if _FS_EXFAT || _USE_TRIM
  1026. DWORD scl = clst, ecl = clst;
  1027. #endif
  1028. #if _USE_TRIM
  1029. DWORD rt[2];
  1030. #endif
  1031. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
  1032. /* Mark the previous cluster 'EOC' on the FAT if it exists */
  1033. if (pclst && (!_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) {
  1034. res = put_fat(fs, pclst, 0xFFFFFFFF);
  1035. if (res != FR_OK) return res;
  1036. }
  1037. /* Remove the chain */
  1038. do {
  1039. nxt = get_fat(obj, clst); /* Get cluster status */
  1040. if (nxt == 0) break; /* Empty cluster? */
  1041. if (nxt == 1) return FR_INT_ERR; /* Internal error? */
  1042. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */
  1043. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1044. res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */
  1045. if (res != FR_OK) return res;
  1046. }
  1047. if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
  1048. fs->free_clst++;
  1049. fs->fsi_flag |= 1;
  1050. }
  1051. #if _FS_EXFAT || _USE_TRIM
  1052. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  1053. ecl = nxt;
  1054. } else { /* End of contiguous cluster block */
  1055. #if _FS_EXFAT
  1056. if (fs->fs_type == FS_EXFAT) {
  1057. res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */
  1058. if (res != FR_OK) return res;
  1059. }
  1060. #endif
  1061. #if _USE_TRIM
  1062. rt[0] = clust2sect(fs, scl); /* Start sector */
  1063. rt[1] = clust2sect(fs, ecl) + fs->csize - 1; /* End sector */
  1064. disk_ioctl(fs->drv, CTRL_TRIM, rt); /* Inform device the block can be erased */
  1065. #endif
  1066. scl = ecl = nxt;
  1067. }
  1068. #endif
  1069. clst = nxt; /* Next cluster */
  1070. } while (clst < fs->n_fatent); /* Repeat while not the last link */
  1071. #if _FS_EXFAT
  1072. if (fs->fs_type == FS_EXFAT) {
  1073. if (pclst == 0) { /* Does object have no chain? */
  1074. obj->stat = 0; /* Change the object status 'initial' */
  1075. } else {
  1076. if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Did the chain got contiguous? */
  1077. obj->stat = 2; /* Change the object status 'contiguous' */
  1078. }
  1079. }
  1080. }
  1081. #endif
  1082. return FR_OK;
  1083. }
  1084. /*-----------------------------------------------------------------------*/
  1085. /* FAT handling - Stretch a chain or Create a new chain */
  1086. /*-----------------------------------------------------------------------*/
  1087. static
  1088. DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  1089. _FDID* obj, /* Corresponding object */
  1090. DWORD clst /* Cluster# to stretch, 0:Create a new chain */
  1091. )
  1092. {
  1093. DWORD cs, ncl, scl;
  1094. FRESULT res;
  1095. FATFS *fs = obj->fs;
  1096. if (clst == 0) { /* Create a new chain */
  1097. scl = fs->last_clst; /* Get suggested cluster to start from */
  1098. if (scl == 0 || scl >= fs->n_fatent) scl = 1;
  1099. }
  1100. else { /* Stretch current chain */
  1101. cs = get_fat(obj, clst); /* Check the cluster status */
  1102. if (cs < 2) return 1; /* Invalid value */
  1103. if (cs == 0xFFFFFFFF) return cs; /* A disk error occurred */
  1104. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  1105. scl = clst;
  1106. }
  1107. #if _FS_EXFAT
  1108. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1109. ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */
  1110. if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */
  1111. res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */
  1112. if (res == FR_INT_ERR) return 1;
  1113. if (res == FR_DISK_ERR) return 0xFFFFFFFF;
  1114. if (clst == 0) { /* Is it a new chain? */
  1115. obj->stat = 2; /* Set status 'contiguous chain' */
  1116. } else { /* This is a stretched chain */
  1117. if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */
  1118. obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */
  1119. obj->stat = 3; /* Change status 'just fragmented' */
  1120. }
  1121. }
  1122. } else
  1123. #endif
  1124. { /* On the FAT12/16/32 volume */
  1125. ncl = scl; /* Start cluster */
  1126. for (;;) {
  1127. ncl++; /* Next cluster */
  1128. if (ncl >= fs->n_fatent) { /* Check wrap-around */
  1129. ncl = 2;
  1130. if (ncl > scl) return 0; /* No free cluster */
  1131. }
  1132. cs = get_fat(obj, ncl); /* Get the cluster status */
  1133. if (cs == 0) break; /* Found a free cluster */
  1134. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* An error occurred */
  1135. if (ncl == scl) return 0; /* No free cluster */
  1136. }
  1137. }
  1138. if (_FS_EXFAT && fs->fs_type == FS_EXFAT && obj->stat == 2) { /* Is it a contiguous chain? */
  1139. res = FR_OK; /* FAT does not need to be written */
  1140. } else {
  1141. res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
  1142. if (res == FR_OK && clst) {
  1143. res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */
  1144. }
  1145. }
  1146. if (res == FR_OK) { /* Update FSINFO if function succeeded. */
  1147. fs->last_clst = ncl;
  1148. if (fs->free_clst < fs->n_fatent - 2) fs->free_clst--;
  1149. fs->fsi_flag |= 1;
  1150. } else {
  1151. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Create error status */
  1152. }
  1153. return ncl; /* Return new cluster number or error status */
  1154. }
  1155. #endif /* !_FS_READONLY */
  1156. #if _USE_FASTSEEK
  1157. /*-----------------------------------------------------------------------*/
  1158. /* FAT handling - Convert offset into cluster with link map table */
  1159. /*-----------------------------------------------------------------------*/
  1160. static
  1161. DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  1162. FIL* fp, /* Pointer to the file object */
  1163. FSIZE_t ofs /* File offset to be converted to cluster# */
  1164. )
  1165. {
  1166. DWORD cl, ncl, *tbl;
  1167. FATFS *fs = fp->obj.fs;
  1168. tbl = fp->cltbl + 1; /* Top of CLMT */
  1169. cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
  1170. for (;;) {
  1171. ncl = *tbl++; /* Number of cluters in the fragment */
  1172. if (ncl == 0) return 0; /* End of table? (error) */
  1173. if (cl < ncl) break; /* In this fragment? */
  1174. cl -= ncl; tbl++; /* Next fragment */
  1175. }
  1176. return cl + *tbl; /* Return the cluster number */
  1177. }
  1178. #endif /* _USE_FASTSEEK */
  1179. /*-----------------------------------------------------------------------*/
  1180. /* Directory handling - Set directory index */
  1181. /*-----------------------------------------------------------------------*/
  1182. static
  1183. FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
  1184. DIR* dp, /* Pointer to directory object */
  1185. DWORD ofs /* Offset of directory table */
  1186. )
  1187. {
  1188. DWORD csz, clst;
  1189. FATFS *fs = dp->obj.fs;
  1190. if (ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
  1191. return FR_INT_ERR;
  1192. }
  1193. dp->dptr = ofs; /* Set current offset */
  1194. clst = dp->obj.sclust; /* Table start cluster (0:root) */
  1195. if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */
  1196. clst = fs->dirbase;
  1197. if (_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
  1198. }
  1199. if (clst == 0) { /* Static table (root-directory in FAT12/16) */
  1200. if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */
  1201. dp->sect = fs->dirbase;
  1202. } else { /* Dynamic table (sub-directory or root-directory in FAT32+) */
  1203. csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */
  1204. while (ofs >= csz) { /* Follow cluster chain */
  1205. clst = get_fat(&dp->obj, clst); /* Get next cluster */
  1206. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1207. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */
  1208. ofs -= csz;
  1209. }
  1210. dp->sect = clust2sect(fs, clst);
  1211. }
  1212. dp->clust = clst; /* Current cluster# */
  1213. if (!dp->sect) return FR_INT_ERR;
  1214. dp->sect += ofs / SS(fs); /* Sector# of the directory entry */
  1215. dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */
  1216. return FR_OK;
  1217. }
  1218. /*-----------------------------------------------------------------------*/
  1219. /* Directory handling - Move directory table index next */
  1220. /*-----------------------------------------------------------------------*/
  1221. static
  1222. FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
  1223. DIR* dp, /* Pointer to the directory object */
  1224. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  1225. )
  1226. {
  1227. DWORD ofs, clst;
  1228. FATFS *fs = dp->obj.fs;
  1229. #if !_FS_READONLY
  1230. UINT n;
  1231. #endif
  1232. ofs = dp->dptr + SZDIRE; /* Next entry */
  1233. if (!dp->sect || ofs >= (DWORD)((_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) return FR_NO_FILE; /* Report EOT when offset has reached max value */
  1234. if (ofs % SS(fs) == 0) { /* Sector changed? */
  1235. dp->sect++; /* Next sector */
  1236. if (!dp->clust) { /* Static table */
  1237. if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */
  1238. dp->sect = 0; return FR_NO_FILE;
  1239. }
  1240. }
  1241. else { /* Dynamic table */
  1242. if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */
  1243. clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */
  1244. if (clst <= 1) return FR_INT_ERR; /* Internal error */
  1245. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1246. if (clst >= fs->n_fatent) { /* Reached end of dynamic table */
  1247. #if !_FS_READONLY
  1248. if (!stretch) { /* If no stretch, report EOT */
  1249. dp->sect = 0; return FR_NO_FILE;
  1250. }
  1251. clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */
  1252. if (clst == 0) return FR_DENIED; /* No free cluster */
  1253. if (clst == 1) return FR_INT_ERR; /* Internal error */
  1254. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1255. /* Clean-up the stretched table */
  1256. if (_FS_EXFAT) dp->obj.stat |= 4; /* The directory needs to be updated */
  1257. if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */
  1258. mem_set(fs->win, 0, SS(fs)); /* Clear window buffer */
  1259. for (n = 0, fs->winsect = clust2sect(fs, clst); n < fs->csize; n++, fs->winsect++) { /* Fill the new cluster with 0 */
  1260. fs->wflag = 1;
  1261. if (sync_window(fs) != FR_OK) return FR_DISK_ERR;
  1262. }
  1263. fs->winsect -= n; /* Restore window offset */
  1264. #else
  1265. if (!stretch) dp->sect = 0; /* If no stretch, report EOT (this is to suppress warning) */
  1266. dp->sect = 0; return FR_NO_FILE; /* Report EOT */
  1267. #endif
  1268. }
  1269. dp->clust = clst; /* Initialize data for new cluster */
  1270. dp->sect = clust2sect(fs, clst);
  1271. }
  1272. }
  1273. }
  1274. dp->dptr = ofs; /* Current entry */
  1275. dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
  1276. return FR_OK;
  1277. }
  1278. #if !_FS_READONLY
  1279. /*-----------------------------------------------------------------------*/
  1280. /* Directory handling - Reserve a block of directory entries */
  1281. /*-----------------------------------------------------------------------*/
  1282. static
  1283. FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
  1284. DIR* dp, /* Pointer to the directory object */
  1285. UINT nent /* Number of contiguous entries to allocate */
  1286. )
  1287. {
  1288. FRESULT res;
  1289. UINT n;
  1290. FATFS *fs = dp->obj.fs;
  1291. res = dir_sdi(dp, 0);
  1292. if (res == FR_OK) {
  1293. n = 0;
  1294. do {
  1295. res = move_window(fs, dp->sect);
  1296. if (res != FR_OK) break;
  1297. #if _FS_EXFAT
  1298. if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) {
  1299. #else
  1300. if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) {
  1301. #endif
  1302. if (++n == nent) break; /* A block of contiguous free entries is found */
  1303. } else {
  1304. n = 0; /* Not a blank entry. Restart to search */
  1305. }
  1306. res = dir_next(dp, 1);
  1307. } while (res == FR_OK); /* Next entry with table stretch enabled */
  1308. }
  1309. if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
  1310. return res;
  1311. }
  1312. #endif /* !_FS_READONLY */
  1313. /*-----------------------------------------------------------------------*/
  1314. /* FAT: Directory handling - Load/Store start cluster number */
  1315. /*-----------------------------------------------------------------------*/
  1316. static
  1317. DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */
  1318. FATFS* fs, /* Pointer to the fs object */
  1319. const BYTE* dir /* Pointer to the key entry */
  1320. )
  1321. {
  1322. DWORD cl;
  1323. cl = ld_word(dir + DIR_FstClusLO);
  1324. if (fs->fs_type == FS_FAT32) {
  1325. cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16;
  1326. }
  1327. return cl;
  1328. }
  1329. #if !_FS_READONLY
  1330. static
  1331. void st_clust (
  1332. FATFS* fs, /* Pointer to the fs object */
  1333. BYTE* dir, /* Pointer to the key entry */
  1334. DWORD cl /* Value to be set */
  1335. )
  1336. {
  1337. st_word(dir + DIR_FstClusLO, (WORD)cl);
  1338. if (fs->fs_type == FS_FAT32) {
  1339. st_word(dir + DIR_FstClusHI, (WORD)(cl >> 16));
  1340. }
  1341. }
  1342. #endif
  1343. #if _USE_LFN != 0
  1344. /*------------------------------------------------------------------------*/
  1345. /* FAT-LFN: LFN handling */
  1346. /*------------------------------------------------------------------------*/
  1347. static
  1348. const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN characters in the directory entry */
  1349. /*--------------------------------------------------------*/
  1350. /* FAT-LFN: Compare a part of file name with an LFN entry */
  1351. /*--------------------------------------------------------*/
  1352. static
  1353. int cmp_lfn ( /* 1:matched, 0:not matched */
  1354. const WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */
  1355. BYTE* dir /* Pointer to the directory entry containing the part of LFN */
  1356. )
  1357. {
  1358. UINT i, s;
  1359. WCHAR wc, uc;
  1360. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
  1361. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1362. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1363. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1364. if (wc) {
  1365. if (i >= _MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */
  1366. return 0; /* Not matched */
  1367. }
  1368. wc = uc;
  1369. } else {
  1370. if (uc != 0xFFFF) return 0; /* Check filler */
  1371. }
  1372. }
  1373. if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */
  1374. return 1; /* The part of LFN matched */
  1375. }
  1376. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
  1377. /*-----------------------------------------------------*/
  1378. /* FAT-LFN: Pick a part of file name from an LFN entry */
  1379. /*-----------------------------------------------------*/
  1380. static
  1381. int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
  1382. WCHAR* lfnbuf, /* Pointer to the LFN working buffer */
  1383. BYTE* dir /* Pointer to the LFN entry */
  1384. )
  1385. {
  1386. UINT i, s;
  1387. WCHAR wc, uc;
  1388. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
  1389. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1390. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1391. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1392. if (wc) {
  1393. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1394. lfnbuf[i++] = wc = uc; /* Store it */
  1395. } else {
  1396. if (uc != 0xFFFF) return 0; /* Check filler */
  1397. }
  1398. }
  1399. if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */
  1400. if (i >= _MAX_LFN) return 0; /* Buffer overflow? */
  1401. lfnbuf[i] = 0;
  1402. }
  1403. return 1; /* The part of LFN is valid */
  1404. }
  1405. #endif
  1406. #if !_FS_READONLY
  1407. /*-----------------------------------------*/
  1408. /* FAT-LFN: Create an entry of LFN entries */
  1409. /*-----------------------------------------*/
  1410. static
  1411. void put_lfn (
  1412. const WCHAR* lfn, /* Pointer to the LFN */
  1413. BYTE* dir, /* Pointer to the LFN entry to be created */
  1414. BYTE ord, /* LFN order (1-20) */
  1415. BYTE sum /* Checksum of the corresponding SFN */
  1416. )
  1417. {
  1418. UINT i, s;
  1419. WCHAR wc;
  1420. dir[LDIR_Chksum] = sum; /* Set checksum */
  1421. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  1422. dir[LDIR_Type] = 0;
  1423. st_word(dir + LDIR_FstClusLO, 0);
  1424. i = (ord - 1) * 13; /* Get offset in the LFN working buffer */
  1425. s = wc = 0;
  1426. do {
  1427. if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */
  1428. st_word(dir + LfnOfs[s], wc); /* Put it */
  1429. if (wc == 0) wc = 0xFFFF; /* Padding characters for left locations */
  1430. } while (++s < 13);
  1431. if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */
  1432. dir[LDIR_Ord] = ord; /* Set the LFN order */
  1433. }
  1434. #endif /* !_FS_READONLY */
  1435. #endif /* _USE_LFN != 0 */
  1436. #if _USE_LFN != 0 && !_FS_READONLY
  1437. /*-----------------------------------------------------------------------*/
  1438. /* FAT-LFN: Create a Numbered SFN */
  1439. /*-----------------------------------------------------------------------*/
  1440. static
  1441. void gen_numname (
  1442. BYTE* dst, /* Pointer to the buffer to store numbered SFN */
  1443. const BYTE* src, /* Pointer to SFN */
  1444. const WCHAR* lfn, /* Pointer to LFN */
  1445. UINT seq /* Sequence number */
  1446. )
  1447. {
  1448. BYTE ns[8], c;
  1449. UINT i, j;
  1450. WCHAR wc;
  1451. DWORD sr;
  1452. mem_cpy(dst, src, 11);
  1453. if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
  1454. sr = seq;
  1455. while (*lfn) { /* Create a CRC */
  1456. wc = *lfn++;
  1457. for (i = 0; i < 16; i++) {
  1458. sr = (sr << 1) + (wc & 1);
  1459. wc >>= 1;
  1460. if (sr & 0x10000) sr ^= 0x11021;
  1461. }
  1462. }
  1463. seq = (UINT)sr;
  1464. }
  1465. /* itoa (hexdecimal) */
  1466. i = 7;
  1467. do {
  1468. c = (BYTE)((seq % 16) + '0');
  1469. if (c > '9') c += 7;
  1470. ns[i--] = c;
  1471. seq /= 16;
  1472. } while (seq);
  1473. ns[i] = '~';
  1474. /* Append the number */
  1475. for (j = 0; j < i && dst[j] != ' '; j++) {
  1476. if (IsDBCS1(dst[j])) {
  1477. if (j == i - 1) break;
  1478. j++;
  1479. }
  1480. }
  1481. do {
  1482. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1483. } while (j < 8);
  1484. }
  1485. #endif /* _USE_LFN != 0 && !_FS_READONLY */
  1486. #if _USE_LFN != 0
  1487. /*-----------------------------------------------------------------------*/
  1488. /* FAT-LFN: Calculate checksum of an SFN entry */
  1489. /*-----------------------------------------------------------------------*/
  1490. static
  1491. BYTE sum_sfn (
  1492. const BYTE* dir /* Pointer to the SFN entry */
  1493. )
  1494. {
  1495. BYTE sum = 0;
  1496. UINT n = 11;
  1497. do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
  1498. return sum;
  1499. }
  1500. #endif /* _USE_LFN != 0 */
  1501. #if _FS_EXFAT
  1502. /*-----------------------------------------------------------------------*/
  1503. /* exFAT: Checksum */
  1504. /*-----------------------------------------------------------------------*/
  1505. static
  1506. WORD xdir_sum ( /* Get checksum of the directoly block */
  1507. const BYTE* dir /* Directory entry block to be calculated */
  1508. )
  1509. {
  1510. UINT i, szblk;
  1511. WORD sum;
  1512. szblk = (dir[XDIR_NumSec] + 1) * SZDIRE;
  1513. for (i = sum = 0; i < szblk; i++) {
  1514. if (i == XDIR_SetSum) { /* Skip sum field */
  1515. i++;
  1516. } else {
  1517. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
  1518. }
  1519. }
  1520. return sum;
  1521. }
  1522. static
  1523. WORD xname_sum ( /* Get check sum (to be used as hash) of the name */
  1524. const WCHAR* name /* File name to be calculated */
  1525. )
  1526. {
  1527. WCHAR chr;
  1528. WORD sum = 0;
  1529. while ((chr = *name++) != 0) {
  1530. chr = ff_wtoupper(chr); /* File name needs to be ignored case */
  1531. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr & 0xFF);
  1532. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr >> 8);
  1533. }
  1534. return sum;
  1535. }
  1536. #if !_FS_READONLY && _USE_MKFS
  1537. static
  1538. DWORD xsum32 (
  1539. BYTE dat, /* Data to be sumed */
  1540. DWORD sum /* Previous value */
  1541. )
  1542. {
  1543. sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
  1544. return sum;
  1545. }
  1546. #endif
  1547. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  1548. /*------------------------------------------------------*/
  1549. /* exFAT: Get object information from a directory block */
  1550. /*------------------------------------------------------*/
  1551. static
  1552. void get_xdir_info (
  1553. BYTE* dirb, /* Pointer to the direcotry entry block 85+C0+C1s */
  1554. FILINFO* fno /* Buffer to store the extracted file information */
  1555. )
  1556. {
  1557. UINT di, si;
  1558. WCHAR w;
  1559. #if !_LFN_UNICODE
  1560. UINT nc;
  1561. #endif
  1562. /* Get file name */
  1563. #if _LFN_UNICODE
  1564. if (dirb[XDIR_NumName] <= _MAX_LFN) {
  1565. for (si = SZDIRE * 2, di = 0; di < dirb[XDIR_NumName]; si += 2, di++) {
  1566. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  1567. w = ld_word(dirb + si); /* Get a character */
  1568. fno->fname[di] = w; /* Store it */
  1569. }
  1570. } else {
  1571. di = 0; /* Buffer overflow and inaccessible object */
  1572. }
  1573. #else
  1574. for (si = SZDIRE * 2, di = nc = 0; nc < dirb[XDIR_NumName]; si += 2, nc++) {
  1575. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  1576. w = ld_word(dirb + si); /* Get a character */
  1577. w = ff_convert(w, 0); /* Unicode -> OEM */
  1578. if (w == 0) { di = 0; break; } /* Could not be converted and inaccessible object */
  1579. if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
  1580. fno->fname[di++] = (char)(w >> 8);
  1581. }
  1582. if (di >= _MAX_LFN) { di = 0; break; } /* Buffer overflow and inaccessible object */
  1583. fno->fname[di++] = (char)w;
  1584. }
  1585. #endif
  1586. if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object? */
  1587. fno->fname[di] = 0; /* Terminate file name */
  1588. fno->altname[0] = 0; /* No SFN */
  1589. fno->fattrib = dirb[XDIR_Attr]; /* Attribute */
  1590. fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(dirb + XDIR_FileSize); /* Size */
  1591. fno->ftime = ld_word(dirb + XDIR_ModTime + 0); /* Time */
  1592. fno->fdate = ld_word(dirb + XDIR_ModTime + 2); /* Date */
  1593. }
  1594. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  1595. /*-----------------------------------*/
  1596. /* exFAT: Get a directry entry block */
  1597. /*-----------------------------------*/
  1598. static
  1599. FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
  1600. DIR* dp /* Pointer to the reading direcotry object pointing the 85 entry */
  1601. )
  1602. {
  1603. FRESULT res;
  1604. UINT i, nent;
  1605. BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
  1606. /* Load 85 entry */
  1607. res = move_window(dp->obj.fs, dp->sect);
  1608. if (res != FR_OK) return res;
  1609. if (dp->dir[XDIR_Type] != 0x85) return FR_INT_ERR;
  1610. mem_cpy(dirb, dp->dir, SZDIRE);
  1611. nent = dirb[XDIR_NumSec] + 1;
  1612. /* Load C0 entry */
  1613. res = dir_next(dp, 0);
  1614. if (res != FR_OK) return res;
  1615. res = move_window(dp->obj.fs, dp->sect);
  1616. if (res != FR_OK) return res;
  1617. if (dp->dir[XDIR_Type] != 0xC0) return FR_INT_ERR;
  1618. mem_cpy(dirb + SZDIRE, dp->dir, SZDIRE);
  1619. /* Load C1 entries */
  1620. if (nent < 3 || nent > 19) return FR_NO_FILE;
  1621. i = SZDIRE * 2; nent *= SZDIRE;
  1622. do {
  1623. res = dir_next(dp, 0);
  1624. if (res != FR_OK) return res;
  1625. res = move_window(dp->obj.fs, dp->sect);
  1626. if (res != FR_OK) return res;
  1627. if (dp->dir[XDIR_Type] != 0xC1) return FR_INT_ERR;
  1628. mem_cpy(dirb + i, dp->dir, SZDIRE);
  1629. i += SZDIRE;
  1630. } while (i < nent);
  1631. /* Sanity check */
  1632. if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR;
  1633. return FR_OK;
  1634. }
  1635. #if !_FS_READONLY || _FS_RPATH != 0
  1636. /*------------------------------------------------*/
  1637. /* exFAT: Load the object's directory entry block */
  1638. /*------------------------------------------------*/
  1639. static
  1640. FRESULT load_obj_dir (
  1641. DIR* dp, /* Blank directory object to be used to access containing direcotry */
  1642. const _FDID* obj /* Object with containing directory information */
  1643. )
  1644. {
  1645. FRESULT res;
  1646. /* Open object containing directory */
  1647. dp->obj.fs = obj->fs;
  1648. dp->obj.sclust = obj->c_scl;
  1649. dp->obj.stat = (BYTE)obj->c_size;
  1650. dp->obj.objsize = obj->c_size & 0xFFFFFF00;
  1651. dp->blk_ofs = obj->c_ofs;
  1652. res = dir_sdi(dp, dp->blk_ofs); /* Goto the block location */
  1653. if (res == FR_OK) {
  1654. res = load_xdir(dp); /* Load the object's entry block */
  1655. }
  1656. return res;
  1657. }
  1658. #endif
  1659. #if !_FS_READONLY
  1660. /*-----------------------------------------------*/
  1661. /* exFAT: Store the directory block to the media */
  1662. /*-----------------------------------------------*/
  1663. static
  1664. FRESULT store_xdir (
  1665. DIR* dp /* Pointer to the direcotry object */
  1666. )
  1667. {
  1668. FRESULT res;
  1669. UINT nent;
  1670. BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */
  1671. /* Create set sum */
  1672. st_word(dirb + XDIR_SetSum, xdir_sum(dirb));
  1673. nent = dirb[XDIR_NumSec] + 1;
  1674. /* Store the set of directory to the volume */
  1675. res = dir_sdi(dp, dp->blk_ofs);
  1676. while (res == FR_OK) {
  1677. res = move_window(dp->obj.fs, dp->sect);
  1678. if (res != FR_OK) break;
  1679. mem_cpy(dp->dir, dirb, SZDIRE);
  1680. dp->obj.fs->wflag = 1;
  1681. if (--nent == 0) break;
  1682. dirb += SZDIRE;
  1683. res = dir_next(dp, 0);
  1684. }
  1685. return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
  1686. }
  1687. /*-------------------------------------------*/
  1688. /* exFAT: Create a new directory enrty block */
  1689. /*-------------------------------------------*/
  1690. static
  1691. void create_xdir (
  1692. BYTE* dirb, /* Pointer to the direcotry entry block buffer */
  1693. const WCHAR* lfn /* Pointer to the nul terminated file name */
  1694. )
  1695. {
  1696. UINT i;
  1697. BYTE nb, nc;
  1698. WCHAR chr;
  1699. mem_set(dirb, 0, 2 * SZDIRE); /* Initialize 85+C0 entry */
  1700. dirb[XDIR_Type] = 0x85;
  1701. dirb[XDIR_Type + SZDIRE] = 0xC0;
  1702. st_word(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */
  1703. i = SZDIRE * 2; /* C1 offset */
  1704. nc = 0; nb = 1; chr = 1;
  1705. do {
  1706. dirb[i++] = 0xC1; dirb[i++] = 0; /* Entry type C1 */
  1707. do { /* Fill name field */
  1708. if (chr && (chr = lfn[nc]) != 0) nc++; /* Get a character if exist */
  1709. st_word(dirb + i, chr); i += 2; /* Store it */
  1710. } while (i % SZDIRE);
  1711. nb++;
  1712. } while (lfn[nc]); /* Fill next entry if any char follows */
  1713. dirb[XDIR_NumName] = nc; /* Set name length */
  1714. dirb[XDIR_NumSec] = nb; /* Set number of C0+C1s */
  1715. }
  1716. #endif /* !_FS_READONLY */
  1717. #endif /* _FS_EXFAT */
  1718. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 || _USE_LABEL || _FS_EXFAT
  1719. /*-----------------------------------------------------------------------*/
  1720. /* Read an object from the directory */
  1721. /*-----------------------------------------------------------------------*/
  1722. static
  1723. FRESULT dir_read (
  1724. DIR* dp, /* Pointer to the directory object */
  1725. int vol /* Filtered by 0:file/directory or 1:volume label */
  1726. )
  1727. {
  1728. FRESULT res = FR_NO_FILE;
  1729. FATFS *fs = dp->obj.fs;
  1730. BYTE a, c;
  1731. #if _USE_LFN != 0
  1732. BYTE ord = 0xFF, sum = 0xFF;
  1733. #endif
  1734. while (dp->sect) {
  1735. res = move_window(fs, dp->sect);
  1736. if (res != FR_OK) break;
  1737. c = dp->dir[DIR_Name]; /* Test for the entry type */
  1738. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of the directory */
  1739. #if _FS_EXFAT
  1740. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1741. if (_USE_LABEL && vol) {
  1742. if (c == 0x83) break; /* Volume label entry? */
  1743. } else {
  1744. if (c == 0x85) { /* Start of the file entry block? */
  1745. dp->blk_ofs = dp->dptr; /* Get location of the block */
  1746. res = load_xdir(dp); /* Load the entry block */
  1747. if (res == FR_OK) {
  1748. dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
  1749. }
  1750. break;
  1751. }
  1752. }
  1753. } else
  1754. #endif
  1755. { /* On the FAT12/16/32 volume */
  1756. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */
  1757. #if _USE_LFN != 0 /* LFN configuration */
  1758. if (c == DDEM || c == '.' || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
  1759. ord = 0xFF;
  1760. } else {
  1761. if (a == AM_LFN) { /* An LFN entry is found */
  1762. if (c & LLEF) { /* Is it start of an LFN sequence? */
  1763. sum = dp->dir[LDIR_Chksum];
  1764. c &= (BYTE)~LLEF; ord = c;
  1765. dp->blk_ofs = dp->dptr;
  1766. }
  1767. /* Check LFN validity and capture it */
  1768. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1769. } else { /* An SFN entry is found */
  1770. if (ord || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */
  1771. dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */
  1772. }
  1773. break;
  1774. }
  1775. }
  1776. #else /* Non LFN configuration */
  1777. if (c != DDEM && c != '.' && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */
  1778. break;
  1779. }
  1780. #endif
  1781. }
  1782. res = dir_next(dp, 0); /* Next entry */
  1783. if (res != FR_OK) break;
  1784. }
  1785. if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
  1786. return res;
  1787. }
  1788. #endif /* _FS_MINIMIZE <= 1 || _USE_LABEL || _FS_RPATH >= 2 */
  1789. /*-----------------------------------------------------------------------*/
  1790. /* Directory handling - Find an object in the directory */
  1791. /*-----------------------------------------------------------------------*/
  1792. static
  1793. FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
  1794. DIR* dp /* Pointer to the directory object with the file name */
  1795. )
  1796. {
  1797. FRESULT res;
  1798. FATFS *fs = dp->obj.fs;
  1799. BYTE c;
  1800. #if _USE_LFN != 0
  1801. BYTE a, ord, sum;
  1802. #endif
  1803. res = dir_sdi(dp, 0); /* Rewind directory object */
  1804. if (res != FR_OK) return res;
  1805. #if _FS_EXFAT
  1806. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1807. BYTE nc;
  1808. UINT di, ni;
  1809. WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
  1810. while ((res = dir_read(dp, 0)) == FR_OK) { /* Read an item */
  1811. if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip the comparison if hash value mismatched */
  1812. for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */
  1813. if ((di % SZDIRE) == 0) di += 2;
  1814. if (ff_wtoupper(ld_word(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break;
  1815. }
  1816. if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
  1817. }
  1818. return res;
  1819. }
  1820. #endif
  1821. /* On the FAT12/16/32 volume */
  1822. #if _USE_LFN != 0
  1823. ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1824. #endif
  1825. do {
  1826. res = move_window(fs, dp->sect);
  1827. if (res != FR_OK) break;
  1828. c = dp->dir[DIR_Name];
  1829. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  1830. #if _USE_LFN != 0 /* LFN configuration */
  1831. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK;
  1832. if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  1833. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1834. } else {
  1835. if (a == AM_LFN) { /* An LFN entry is found */
  1836. if (!(dp->fn[NSFLAG] & NS_NOLFN)) {
  1837. if (c & LLEF) { /* Is it start of LFN sequence? */
  1838. sum = dp->dir[LDIR_Chksum];
  1839. c &= (BYTE)~LLEF; ord = c; /* LFN start order */
  1840. dp->blk_ofs = dp->dptr; /* Start offset of LFN */
  1841. }
  1842. /* Check validity of the LFN entry and compare it with given name */
  1843. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1844. }
  1845. } else { /* An SFN entry is found */
  1846. if (!ord && sum == sum_sfn(dp->dir)) break; /* LFN matched? */
  1847. if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */
  1848. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1849. }
  1850. }
  1851. #else /* Non LFN configuration */
  1852. dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;
  1853. if (!(dp->dir[DIR_Attr] & AM_VOL) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */
  1854. #endif
  1855. res = dir_next(dp, 0); /* Next entry */
  1856. } while (res == FR_OK);
  1857. return res;
  1858. }
  1859. #if !_FS_READONLY
  1860. /*-----------------------------------------------------------------------*/
  1861. /* Register an object to the directory */
  1862. /*-----------------------------------------------------------------------*/
  1863. static
  1864. FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
  1865. DIR* dp /* Target directory with object name to be created */
  1866. )
  1867. {
  1868. FRESULT res;
  1869. FATFS *fs = dp->obj.fs;
  1870. #if _USE_LFN != 0 /* LFN configuration */
  1871. UINT n, nlen, nent;
  1872. BYTE sn[12], sum;
  1873. if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */
  1874. for (nlen = 0; fs->lfnbuf[nlen]; nlen++) ; /* Get lfn length */
  1875. #if _FS_EXFAT
  1876. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1877. DIR dj;
  1878. nent = (nlen + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
  1879. res = dir_alloc(dp, nent); /* Allocate entries */
  1880. if (res != FR_OK) return res;
  1881. dp->blk_ofs = dp->dptr - SZDIRE * (nent - 1); /* Set block position */
  1882. if (dp->obj.sclust != 0 && (dp->obj.stat & 4)) { /* Has the sub-directory been stretched? */
  1883. dp->obj.stat &= 3;
  1884. dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase object size by cluster size */
  1885. res = fill_fat_chain(&dp->obj); /* Complement FAT chain if needed */
  1886. if (res != FR_OK) return res;
  1887. res = load_obj_dir(&dj, &dp->obj);
  1888. if (res != FR_OK) return res; /* Load the object status */
  1889. st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); /* Update the allocation status */
  1890. st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);
  1891. fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1;
  1892. res = store_xdir(&dj); /* Store the object status */
  1893. if (res != FR_OK) return res;
  1894. }
  1895. create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
  1896. return FR_OK;
  1897. }
  1898. #endif
  1899. /* On the FAT12/16/32 volume */
  1900. mem_cpy(sn, dp->fn, 12);
  1901. if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  1902. dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */
  1903. for (n = 1; n < 100; n++) {
  1904. gen_numname(dp->fn, sn, fs->lfnbuf, n); /* Generate a numbered name */
  1905. res = dir_find(dp); /* Check if the name collides with existing SFN */
  1906. if (res != FR_OK) break;
  1907. }
  1908. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  1909. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  1910. dp->fn[NSFLAG] = sn[NSFLAG];
  1911. }
  1912. /* Create an SFN with/without LFNs. */
  1913. nent = (sn[NSFLAG] & NS_LFN) ? (nlen + 12) / 13 + 1 : 1; /* Number of entries to allocate */
  1914. res = dir_alloc(dp, nent); /* Allocate entries */
  1915. if (res == FR_OK && --nent) { /* Set LFN entry if needed */
  1916. res = dir_sdi(dp, dp->dptr - nent * SZDIRE);
  1917. if (res == FR_OK) {
  1918. sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */
  1919. do { /* Store LFN entries in bottom first */
  1920. res = move_window(fs, dp->sect);
  1921. if (res != FR_OK) break;
  1922. put_lfn(fs->lfnbuf, dp->dir, (BYTE)nent, sum);
  1923. fs->wflag = 1;
  1924. res = dir_next(dp, 0); /* Next entry */
  1925. } while (res == FR_OK && --nent);
  1926. }
  1927. }
  1928. #else /* Non LFN configuration */
  1929. res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
  1930. #endif
  1931. /* Set SFN entry */
  1932. if (res == FR_OK) {
  1933. res = move_window(fs, dp->sect);
  1934. if (res == FR_OK) {
  1935. mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */
  1936. mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
  1937. #if _USE_LFN != 0
  1938. dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
  1939. #endif
  1940. fs->wflag = 1;
  1941. }
  1942. }
  1943. return res;
  1944. }
  1945. #endif /* !_FS_READONLY */
  1946. #if !_FS_READONLY && _FS_MINIMIZE == 0
  1947. /*-----------------------------------------------------------------------*/
  1948. /* Remove an object from the directory */
  1949. /*-----------------------------------------------------------------------*/
  1950. static
  1951. FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
  1952. DIR* dp /* Directory object pointing the entry to be removed */
  1953. )
  1954. {
  1955. FRESULT res;
  1956. FATFS *fs = dp->obj.fs;
  1957. #if _USE_LFN != 0 /* LFN configuration */
  1958. DWORD last = dp->dptr;
  1959. res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
  1960. if (res == FR_OK) {
  1961. do {
  1962. res = move_window(fs, dp->sect);
  1963. if (res != FR_OK) break;
  1964. /* Mark an entry 'deleted' */
  1965. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1966. dp->dir[XDIR_Type] &= 0x7F;
  1967. } else { /* On the FAT12/16/32 volume */
  1968. dp->dir[DIR_Name] = DDEM;
  1969. }
  1970. fs->wflag = 1;
  1971. if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */
  1972. res = dir_next(dp, 0); /* Next entry */
  1973. } while (res == FR_OK);
  1974. if (res == FR_NO_FILE) res = FR_INT_ERR;
  1975. }
  1976. #else /* Non LFN configuration */
  1977. res = move_window(fs, dp->sect);
  1978. if (res == FR_OK) {
  1979. dp->dir[DIR_Name] = DDEM;
  1980. fs->wflag = 1;
  1981. }
  1982. #endif
  1983. return res;
  1984. }
  1985. #endif /* !_FS_READONLY && _FS_MINIMIZE == 0 */
  1986. #if _FS_MINIMIZE <= 1 || _FS_RPATH >= 2
  1987. /*-----------------------------------------------------------------------*/
  1988. /* Get file information from directory entry */
  1989. /*-----------------------------------------------------------------------*/
  1990. static
  1991. void get_fileinfo ( /* No return code */
  1992. DIR* dp, /* Pointer to the directory object */
  1993. FILINFO* fno /* Pointer to the file information to be filled */
  1994. )
  1995. {
  1996. UINT i, j;
  1997. TCHAR c;
  1998. DWORD tm;
  1999. #if _USE_LFN != 0
  2000. WCHAR w, lfv;
  2001. FATFS *fs = dp->obj.fs;
  2002. #endif
  2003. fno->fname[0] = 0; /* Invaidate file info */
  2004. if (!dp->sect) return; /* Exit if read pointer has reached end of directory */
  2005. #if _USE_LFN != 0 /* LFN configuration */
  2006. #if _FS_EXFAT
  2007. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2008. get_xdir_info(fs->dirbuf, fno);
  2009. return;
  2010. } else
  2011. #endif
  2012. { /* On the FAT12/16/32 volume */
  2013. if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
  2014. i = j = 0;
  2015. while ((w = fs->lfnbuf[j++]) != 0) { /* Get an LFN character */
  2016. #if !_LFN_UNICODE
  2017. w = ff_convert(w, 0); /* Unicode -> OEM */
  2018. if (w == 0) { i = 0; break; } /* No LFN if it could not be converted */
  2019. if (_DF1S && w >= 0x100) { /* Put 1st byte if it is a DBC (always false at SBCS cfg) */
  2020. fno->fname[i++] = (char)(w >> 8);
  2021. }
  2022. #endif
  2023. if (i >= _MAX_LFN) { i = 0; break; } /* No LFN if buffer overflow */
  2024. fno->fname[i++] = (TCHAR)w;
  2025. }
  2026. fno->fname[i] = 0; /* Terminate the LFN */
  2027. }
  2028. }
  2029. i = j = 0;
  2030. lfv = fno->fname[i]; /* LFN is exist if non-zero */
  2031. while (i < 11) { /* Copy name body and extension */
  2032. c = (TCHAR)dp->dir[i++];
  2033. if (c == ' ') continue; /* Skip padding spaces */
  2034. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  2035. if (i == 9) { /* Insert a . if extension is exist */
  2036. if (!lfv) fno->fname[j] = '.';
  2037. fno->altname[j++] = '.';
  2038. }
  2039. #if _LFN_UNICODE
  2040. if (IsDBCS1(c) && i != 8 && i != 11 && IsDBCS2(dp->dir[i])) {
  2041. c = c << 8 | dp->dir[i++];
  2042. }
  2043. c = ff_convert(c, 1); /* OEM -> Unicode */
  2044. if (!c) c = '?';
  2045. #endif
  2046. fno->altname[j] = c;
  2047. if (!lfv) {
  2048. if (IsUpper(c) && (dp->dir[DIR_NTres] & (i >= 9 ? NS_EXT : NS_BODY))) {
  2049. c += 0x20; /* To lower */
  2050. }
  2051. fno->fname[j] = c;
  2052. }
  2053. j++;
  2054. }
  2055. if (!lfv) {
  2056. fno->fname[j] = 0;
  2057. if (!dp->dir[DIR_NTres]) j = 0; /* Altname is no longer needed if neither LFN nor case info is exist. */
  2058. }
  2059. fno->altname[j] = 0; /* Terminate the SFN */
  2060. #else /* Non-LFN configuration */
  2061. i = j = 0;
  2062. while (i < 11) { /* Copy name body and extension */
  2063. c = (TCHAR)dp->dir[i++];
  2064. if (c == ' ') continue; /* Skip padding spaces */
  2065. if (c == RDDEM) c = (TCHAR)DDEM; /* Restore replaced DDEM character */
  2066. if (i == 9) fno->fname[j++] = '.'; /* Insert a . if extension is exist */
  2067. fno->fname[j++] = c;
  2068. }
  2069. fno->fname[j] = 0;
  2070. #endif
  2071. fno->fattrib = dp->dir[DIR_Attr]; /* Attribute */
  2072. fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */
  2073. tm = ld_dword(dp->dir + DIR_ModTime); /* Timestamp */
  2074. fno->ftime = (WORD)tm; fno->fdate = (WORD)(tm >> 16);
  2075. }
  2076. #endif /* _FS_MINIMIZE <= 1 || _FS_RPATH >= 2 */
  2077. #if _USE_FIND && _FS_MINIMIZE <= 1
  2078. /*-----------------------------------------------------------------------*/
  2079. /* Pattern matching */
  2080. /*-----------------------------------------------------------------------*/
  2081. static
  2082. WCHAR get_achar ( /* Get a character and advances ptr 1 or 2 */
  2083. const TCHAR** ptr /* Pointer to pointer to the SBCS/DBCS/Unicode string */
  2084. )
  2085. {
  2086. #if !_LFN_UNICODE
  2087. WCHAR chr;
  2088. chr = (BYTE)*(*ptr)++; /* Get a byte */
  2089. if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
  2090. #ifdef _EXCVT
  2091. if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
  2092. #else
  2093. if (IsDBCS1(chr) && IsDBCS2(**ptr)) { /* Get DBC 2nd byte if needed */
  2094. chr = chr << 8 | (BYTE)*(*ptr)++;
  2095. }
  2096. #endif
  2097. return chr;
  2098. #else
  2099. return ff_wtoupper(*(*ptr)++); /* Get a word and to upper */
  2100. #endif
  2101. }
  2102. static
  2103. int pattern_matching ( /* 0:not matched, 1:matched */
  2104. const TCHAR* pat, /* Matching pattern */
  2105. const TCHAR* nam, /* String to be tested */
  2106. int skip, /* Number of pre-skip chars (number of ?s) */
  2107. int inf /* Infinite search (* specified) */
  2108. )
  2109. {
  2110. const TCHAR *pp, *np;
  2111. WCHAR pc, nc;
  2112. int nm, nx;
  2113. while (skip--) { /* Pre-skip name chars */
  2114. if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
  2115. }
  2116. if (!*pat && inf) return 1; /* (short circuit) */
  2117. do {
  2118. pp = pat; np = nam; /* Top of pattern and name to match */
  2119. for (;;) {
  2120. if (*pp == '?' || *pp == '*') { /* Wildcard? */
  2121. nm = nx = 0;
  2122. do { /* Analyze the wildcard chars */
  2123. if (*pp++ == '?') nm++; else nx = 1;
  2124. } while (*pp == '?' || *pp == '*');
  2125. if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */
  2126. nc = *np; break; /* Branch mismatched */
  2127. }
  2128. pc = get_achar(&pp); /* Get a pattern char */
  2129. nc = get_achar(&np); /* Get a name char */
  2130. if (pc != nc) break; /* Branch mismatched? */
  2131. if (pc == 0) return 1; /* Branch matched? (matched at end of both strings) */
  2132. }
  2133. get_achar(&nam); /* nam++ */
  2134. } while (inf && nc); /* Retry until end of name if infinite search is specified */
  2135. return 0;
  2136. }
  2137. #endif /* _USE_FIND && _FS_MINIMIZE <= 1 */
  2138. /*-----------------------------------------------------------------------*/
  2139. /* Pick a top segment and create the object name in directory form */
  2140. /*-----------------------------------------------------------------------*/
  2141. static
  2142. FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
  2143. DIR* dp, /* Pointer to the directory object */
  2144. const TCHAR** path /* Pointer to pointer to the segment in the path string */
  2145. )
  2146. {
  2147. #if _USE_LFN != 0 /* LFN configuration */
  2148. BYTE b, cf;
  2149. WCHAR w, *lfn;
  2150. UINT i, ni, si, di;
  2151. const TCHAR *p;
  2152. /* Create LFN in Unicode */
  2153. p = *path; lfn = dp->obj.fs->lfnbuf; si = di = 0;
  2154. for (;;) {
  2155. w = p[si++]; /* Get a character */
  2156. if (w < ' ') break; /* Break if end of the path name */
  2157. if (w == '/' || w == '\\') { /* Break if a separator is found */
  2158. while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
  2159. break;
  2160. }
  2161. if (di >= _MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
  2162. #if !_LFN_UNICODE
  2163. w &= 0xFF;
  2164. if (IsDBCS1(w)) { /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
  2165. b = (BYTE)p[si++]; /* Get 2nd byte */
  2166. w = (w << 8) + b; /* Create a DBC */
  2167. if (!IsDBCS2(b)) return FR_INVALID_NAME; /* Reject invalid sequence */
  2168. }
  2169. w = ff_convert(w, 1); /* Convert ANSI/OEM to Unicode */
  2170. if (!w) return FR_INVALID_NAME; /* Reject invalid code */
  2171. #endif
  2172. if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */
  2173. lfn[di++] = w; /* Store the Unicode character */
  2174. }
  2175. *path = &p[si]; /* Return pointer to the next segment */
  2176. cf = (w < ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2177. #if _FS_RPATH != 0
  2178. if ((di == 1 && lfn[di - 1] == '.') ||
  2179. (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
  2180. lfn[di] = 0;
  2181. for (i = 0; i < 11; i++) /* Create dot name for SFN entry */
  2182. dp->fn[i] = (i < di) ? '.' : ' ';
  2183. dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
  2184. return FR_OK;
  2185. }
  2186. #endif
  2187. while (di) { /* Snip off trailing spaces and dots if exist */
  2188. w = lfn[di - 1];
  2189. if (w != ' ' && w != '.') break;
  2190. di--;
  2191. }
  2192. lfn[di] = 0; /* LFN is created */
  2193. if (di == 0) return FR_INVALID_NAME; /* Reject nul name */
  2194. /* Create SFN in directory form */
  2195. mem_set(dp->fn, ' ', 11);
  2196. for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ; /* Strip leading spaces and dots */
  2197. if (si) cf |= NS_LOSS | NS_LFN;
  2198. while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */
  2199. i = b = 0; ni = 8;
  2200. for (;;) {
  2201. w = lfn[si++]; /* Get an LFN character */
  2202. if (!w) break; /* Break on end of the LFN */
  2203. if (w == ' ' || (w == '.' && si != di)) { /* Remove spaces and dots */
  2204. cf |= NS_LOSS | NS_LFN; continue;
  2205. }
  2206. if (i >= ni || si == di) { /* Extension or end of SFN */
  2207. if (ni == 11) { /* Long extension */
  2208. cf |= NS_LOSS | NS_LFN; break;
  2209. }
  2210. if (si != di) cf |= NS_LOSS | NS_LFN; /* Out of 8.3 format */
  2211. if (si > di) break; /* No extension */
  2212. si = di; i = 8; ni = 11; /* Enter extension section */
  2213. b <<= 2; continue;
  2214. }
  2215. if (w >= 0x80) { /* Non ASCII character */
  2216. #ifdef _EXCVT
  2217. w = ff_convert(w, 0); /* Unicode -> OEM code */
  2218. if (w) w = ExCvt[w - 0x80]; /* Convert extended character to upper (SBCS) */
  2219. #else
  2220. w = ff_convert(ff_wtoupper(w), 0); /* Upper converted Unicode -> OEM code */
  2221. #endif
  2222. cf |= NS_LFN; /* Force create LFN entry */
  2223. }
  2224. if (_DF1S && w >= 0x100) { /* Is this DBC? (always false at SBCS cfg) */
  2225. if (i >= ni - 1) {
  2226. cf |= NS_LOSS | NS_LFN; i = ni; continue;
  2227. }
  2228. dp->fn[i++] = (BYTE)(w >> 8);
  2229. } else { /* SBC */
  2230. if (!w || chk_chr("+,;=[]", w)) { /* Replace illegal characters for SFN */
  2231. w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  2232. } else {
  2233. if (IsUpper(w)) { /* ASCII large capital */
  2234. b |= 2;
  2235. } else {
  2236. if (IsLower(w)) { /* ASCII small capital */
  2237. b |= 1; w -= 0x20;
  2238. }
  2239. }
  2240. }
  2241. }
  2242. dp->fn[i++] = (BYTE)w;
  2243. }
  2244. if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2245. if (ni == 8) b <<= 2;
  2246. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* Create LFN entry when there are composite capitals */
  2247. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
  2248. if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */
  2249. if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */
  2250. }
  2251. dp->fn[NSFLAG] = cf; /* SFN is created */
  2252. return FR_OK;
  2253. #else /* _USE_LFN != 0 : Non-LFN configuration */
  2254. BYTE c, d, *sfn;
  2255. UINT ni, si, i;
  2256. const char *p;
  2257. /* Create file name in directory form */
  2258. p = *path; sfn = dp->fn;
  2259. mem_set(sfn, ' ', 11);
  2260. si = i = 0; ni = 8;
  2261. #if _FS_RPATH != 0
  2262. if (p[si] == '.') { /* Is this a dot entry? */
  2263. for (;;) {
  2264. c = (BYTE)p[si++];
  2265. if (c != '.' || si >= 3) break;
  2266. sfn[i++] = c;
  2267. }
  2268. if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
  2269. *path = p + si; /* Return pointer to the next segment */
  2270. sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */
  2271. return FR_OK;
  2272. }
  2273. #endif
  2274. for (;;) {
  2275. c = (BYTE)p[si++];
  2276. if (c <= ' ') break; /* Break if end of the path name */
  2277. if (c == '/' || c == '\\') { /* Break if a separator is found */
  2278. while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */
  2279. break;
  2280. }
  2281. if (c == '.' || i >= ni) { /* End of body or over size? */
  2282. if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Over size or invalid dot */
  2283. i = 8; ni = 11; /* Goto extension */
  2284. continue;
  2285. }
  2286. if (c >= 0x80) { /* Extended character? */
  2287. #ifdef _EXCVT
  2288. c = ExCvt[c - 0x80]; /* To upper extended characters (SBCS cfg) */
  2289. #else
  2290. #if !_DF1S
  2291. return FR_INVALID_NAME; /* Reject extended characters (ASCII only cfg) */
  2292. #endif
  2293. #endif
  2294. }
  2295. if (IsDBCS1(c)) { /* Check if it is a DBC 1st byte (always false at SBCS cfg.) */
  2296. d = (BYTE)p[si++]; /* Get 2nd byte */
  2297. if (!IsDBCS2(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */
  2298. sfn[i++] = c;
  2299. sfn[i++] = d;
  2300. } else { /* SBC */
  2301. if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
  2302. if (IsLower(c)) c -= 0x20; /* To upper */
  2303. sfn[i++] = c;
  2304. }
  2305. }
  2306. *path = p + si; /* Return pointer to the next segment */
  2307. if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
  2308. if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2309. sfn[NSFLAG] = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2310. return FR_OK;
  2311. #endif /* _USE_LFN != 0 */
  2312. }
  2313. /*-----------------------------------------------------------------------*/
  2314. /* Follow a file path */
  2315. /*-----------------------------------------------------------------------*/
  2316. static
  2317. FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  2318. DIR* dp, /* Directory object to return last directory and found object */
  2319. const TCHAR* path /* Full-path string to find a file or directory */
  2320. )
  2321. {
  2322. FRESULT res;
  2323. BYTE ns;
  2324. _FDID *obj = &dp->obj;
  2325. FATFS *fs = obj->fs;
  2326. #if _FS_RPATH != 0
  2327. if (*path != '/' && *path != '\\') { /* Without heading separator */
  2328. obj->sclust = fs->cdir; /* Start from the current directory */
  2329. } else
  2330. #endif
  2331. { /* With heading separator */
  2332. while (*path == '/' || *path == '\\') path++; /* Strip heading separator */
  2333. obj->sclust = 0; /* Start from the root directory */
  2334. }
  2335. #if _FS_EXFAT && _FS_RPATH != 0
  2336. if (fs->fs_type == FS_EXFAT && obj->sclust) { /* Retrieve the sub-directory status if needed */
  2337. DIR dj;
  2338. obj->c_scl = fs->cdc_scl;
  2339. obj->c_size = fs->cdc_size;
  2340. obj->c_ofs = fs->cdc_ofs;
  2341. res = load_obj_dir(&dj, obj);
  2342. if (res != FR_OK) return res;
  2343. obj->objsize = ld_dword(fs->dirbuf + XDIR_FileSize);
  2344. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2345. }
  2346. #endif
  2347. if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
  2348. dp->fn[NSFLAG] = NS_NONAME;
  2349. res = dir_sdi(dp, 0);
  2350. } else { /* Follow path */
  2351. for (;;) {
  2352. res = create_name(dp, &path); /* Get a segment name of the path */
  2353. if (res != FR_OK) break;
  2354. res = dir_find(dp); /* Find an object with the segment name */
  2355. ns = dp->fn[NSFLAG];
  2356. if (res != FR_OK) { /* Failed to find the object */
  2357. if (res == FR_NO_FILE) { /* Object is not found */
  2358. if (_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there */
  2359. if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
  2360. dp->fn[NSFLAG] = NS_NONAME;
  2361. res = FR_OK;
  2362. } else { /* Could not find the object */
  2363. if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
  2364. }
  2365. }
  2366. break;
  2367. }
  2368. if (ns & NS_LAST) break; /* Last segment matched. Function completed. */
  2369. /* Get into the sub-directory */
  2370. if (!(obj->attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */
  2371. res = FR_NO_PATH; break;
  2372. }
  2373. #if _FS_EXFAT
  2374. if (fs->fs_type == FS_EXFAT) {
  2375. obj->c_scl = obj->sclust; /* Save containing directory information for next dir */
  2376. obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
  2377. obj->c_ofs = dp->blk_ofs;
  2378. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Open next directory */
  2379. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2380. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2381. } else
  2382. #endif
  2383. {
  2384. obj->sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
  2385. }
  2386. }
  2387. }
  2388. return res;
  2389. }
  2390. /*-----------------------------------------------------------------------*/
  2391. /* Get logical drive number from path name */
  2392. /*-----------------------------------------------------------------------*/
  2393. static
  2394. int get_ldnumber ( /* Returns logical drive number (-1:invalid drive) */
  2395. const TCHAR** path /* Pointer to pointer to the path name */
  2396. )
  2397. {
  2398. const TCHAR *tp, *tt;
  2399. UINT i;
  2400. int vol = -1;
  2401. #if _STR_VOLUME_ID /* Find string drive id */
  2402. static const char* const str[] = {_VOLUME_STRS};
  2403. const char *sp;
  2404. char c;
  2405. TCHAR tc;
  2406. #endif
  2407. if (*path) { /* If the pointer is not a null */
  2408. for (tt = *path; (UINT)*tt >= (_USE_LFN ? ' ' : '!') && *tt != ':'; tt++) ; /* Find ':' in the path */
  2409. if (*tt == ':') { /* If a ':' is exist in the path name */
  2410. tp = *path;
  2411. i = *tp++ - '0';
  2412. if (i < 10 && tp == tt) { /* Is there a numeric drive id? */
  2413. if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
  2414. vol = (int)i;
  2415. *path = ++tt;
  2416. }
  2417. }
  2418. #if _STR_VOLUME_ID
  2419. else { /* No numeric drive number, find string drive id */
  2420. i = 0; tt++;
  2421. do {
  2422. sp = str[i]; tp = *path;
  2423. do { /* Compare a string drive id with path name */
  2424. c = *sp++; tc = *tp++;
  2425. if (IsLower(tc)) tc -= 0x20;
  2426. } while (c && (TCHAR)c == tc);
  2427. } while ((c || tp != tt) && ++i < _VOLUMES); /* Repeat for each id until pattern match */
  2428. if (i < _VOLUMES) { /* If a drive id is found, get the value and strip it */
  2429. vol = (int)i;
  2430. *path = tt;
  2431. }
  2432. }
  2433. #endif
  2434. return vol;
  2435. }
  2436. #if _FS_RPATH != 0 && _VOLUMES >= 2
  2437. vol = CurrVol; /* Current drive */
  2438. #else
  2439. vol = 0; /* Drive 0 */
  2440. #endif
  2441. }
  2442. return vol;
  2443. }
  2444. /*-----------------------------------------------------------------------*/
  2445. /* Load a sector and check if it is an FAT boot sector */
  2446. /*-----------------------------------------------------------------------*/
  2447. static
  2448. BYTE check_fs ( /* 0:FAT, 1:exFAT, 2:Valid BS but not FAT, 3:Not a BS, 4:Disk error */
  2449. FATFS* fs, /* File system object */
  2450. DWORD sect /* Sector# (lba) to check if it is an FAT-VBR or not */
  2451. )
  2452. {
  2453. fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */
  2454. if (move_window(fs, sect) != FR_OK) return 4; /* Load boot record */
  2455. if (ld_word(fs->win + BS_55AA) != 0xAA55) return 3; /* Check boot record signature (always placed at offset 510 even if the sector size is >512) */
  2456. if (fs->win[BS_JmpBoot] == 0xE9 || (fs->win[BS_JmpBoot] == 0xEB && fs->win[BS_JmpBoot + 2] == 0x90)) {
  2457. if ((ld_dword(fs->win + BS_FilSysType) & 0xFFFFFF) == 0x544146) return 0; /* Check "FAT" string */
  2458. if (ld_dword(fs->win + BS_FilSysType32) == 0x33544146) return 0; /* Check "FAT3" string */
  2459. }
  2460. #if _FS_EXFAT
  2461. if (!mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1;
  2462. #endif
  2463. return 2;
  2464. }
  2465. /*-----------------------------------------------------------------------*/
  2466. /* Find logical drive and check if the volume is mounted */
  2467. /*-----------------------------------------------------------------------*/
  2468. static
  2469. FRESULT find_volume ( /* FR_OK(0): successful, !=0: any error occurred */
  2470. const TCHAR** path, /* Pointer to pointer to the path name (drive number) */
  2471. FATFS** rfs, /* Pointer to pointer to the found file system object */
  2472. BYTE mode /* !=0: Check write protection for write access */
  2473. )
  2474. {
  2475. BYTE fmt, *pt;
  2476. int vol;
  2477. DSTATUS stat;
  2478. DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];
  2479. WORD nrsv;
  2480. FATFS *fs;
  2481. UINT i;
  2482. /* Get logical drive number */
  2483. *rfs = 0;
  2484. vol = get_ldnumber(path);
  2485. if (vol < 0) return FR_INVALID_DRIVE;
  2486. /* Check if the file system object is valid or not */
  2487. fs = FatFs[vol]; /* Get pointer to the file system object */
  2488. if (!fs) return FR_NOT_ENABLED; /* Is the file system object available? */
  2489. ENTER_FF(fs); /* Lock the volume */
  2490. *rfs = fs; /* Return pointer to the file system object */
  2491. mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
  2492. if (fs->fs_type) { /* If the volume has been mounted */
  2493. stat = disk_status(fs->drv);
  2494. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
  2495. if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
  2496. return FR_WRITE_PROTECTED;
  2497. }
  2498. return FR_OK; /* The file system object is valid */
  2499. }
  2500. }
  2501. /* The file system object is not valid. */
  2502. /* Following code attempts to mount the volume. (analyze BPB and initialize the fs object) */
  2503. fs->fs_type = 0; /* Clear the file system object */
  2504. fs->drv = LD2PD(vol); /* Bind the logical drive and a physical drive */
  2505. stat = disk_initialize(fs->drv); /* Initialize the physical drive */
  2506. if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
  2507. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  2508. }
  2509. if (!_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
  2510. return FR_WRITE_PROTECTED;
  2511. }
  2512. #if _MAX_SS != _MIN_SS /* Get sector size (multiple sector size cfg only) */
  2513. if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
  2514. if (SS(fs) > _MAX_SS || SS(fs) < _MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
  2515. #endif
  2516. /* Find an FAT partition on the drive. Supports only generic partitioning, FDISK and SFD. */
  2517. bsect = 0;
  2518. fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT-VBR as SFD */
  2519. if (fmt == 2 || (fmt < 2 && LD2PT(vol) != 0)) { /* Not an FAT-VBR or forced partition number */
  2520. for (i = 0; i < 4; i++) { /* Get partition offset */
  2521. pt = fs->win + (MBR_Table + i * SZ_PTE);
  2522. br[i] = pt[PTE_System] ? ld_dword(pt + PTE_StLba) : 0;
  2523. }
  2524. i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */
  2525. if (i) i--;
  2526. do { /* Find an FAT volume */
  2527. bsect = br[i];
  2528. fmt = bsect ? check_fs(fs, bsect) : 3; /* Check the partition */
  2529. } while (!LD2PT(vol) && fmt >= 2 && ++i < 4);
  2530. }
  2531. if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */
  2532. if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  2533. /* An FAT volume is found. Following code initializes the file system object */
  2534. #if _FS_EXFAT
  2535. if (fmt == 1) {
  2536. QWORD maxlba;
  2537. for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
  2538. if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
  2539. if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT revision (Must be 1.0) */
  2540. if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
  2541. return FR_NO_FILESYSTEM;
  2542. maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA + 1 of the volume */
  2543. if (maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be handled in 32-bit LBA) */
  2544. fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
  2545. fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
  2546. if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
  2547. fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
  2548. if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768) */
  2549. nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */
  2550. if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
  2551. fs->n_fatent = nclst + 2;
  2552. /* Boundaries and Limits */
  2553. fs->volbase = bsect;
  2554. fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);
  2555. fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);
  2556. if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size requiered) */
  2557. fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);
  2558. /* Check if bitmap location is in assumption (at the first cluster) */
  2559. if (move_window(fs, clust2sect(fs, fs->dirbase)) != FR_OK) return FR_DISK_ERR;
  2560. for (i = 0; i < SS(fs); i += SZDIRE) {
  2561. if (fs->win[i] == 0x81 && ld_dword(fs->win + i + 20) == 2) break; /* 81 entry with cluster #2? */
  2562. }
  2563. if (i == SS(fs)) return FR_NO_FILESYSTEM;
  2564. #if !_FS_READONLY
  2565. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2566. #endif
  2567. fmt = FS_EXFAT; /* FAT sub-type */
  2568. } else
  2569. #endif /* _FS_EXFAT */
  2570. {
  2571. if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
  2572. fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
  2573. if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
  2574. fs->fsize = fasize;
  2575. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
  2576. if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  2577. fasize *= fs->n_fats; /* Number of sectors for FAT area */
  2578. fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
  2579. if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  2580. fs->n_rootdir = ld_word(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
  2581. if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
  2582. tsect = ld_word(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
  2583. if (tsect == 0) tsect = ld_dword(fs->win + BPB_TotSec32);
  2584. nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
  2585. if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
  2586. /* Determine the FAT sub type */
  2587. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
  2588. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2589. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  2590. if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2591. fmt = FS_FAT32;
  2592. if (nclst <= MAX_FAT16) fmt = FS_FAT16;
  2593. if (nclst <= MAX_FAT12) fmt = FS_FAT12;
  2594. /* Boundaries and Limits */
  2595. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  2596. fs->volbase = bsect; /* Volume start sector */
  2597. fs->fatbase = bsect + nrsv; /* FAT start sector */
  2598. fs->database = bsect + sysect; /* Data start sector */
  2599. if (fmt == FS_FAT32) {
  2600. if (ld_word(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
  2601. if (fs->n_rootdir) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  2602. fs->dirbase = ld_dword(fs->win + BPB_RootClus32); /* Root directory start cluster */
  2603. szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
  2604. } else {
  2605. if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM;/* (BPB_RootEntCnt must not be 0) */
  2606. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  2607. szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
  2608. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  2609. }
  2610. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
  2611. #if !_FS_READONLY
  2612. /* Get FSINFO if available */
  2613. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2614. fs->fsi_flag = 0x80;
  2615. #if (_FS_NOFSINFO & 3) != 3
  2616. if (fmt == FS_FAT32 /* Enable FSINFO only if FAT32 and BPB_FSInfo32 == 1 */
  2617. && ld_word(fs->win + BPB_FSInfo32) == 1
  2618. && move_window(fs, bsect + 1) == FR_OK)
  2619. {
  2620. fs->fsi_flag = 0;
  2621. if (ld_word(fs->win + BS_55AA) == 0xAA55 /* Load FSINFO data if available */
  2622. && ld_dword(fs->win + FSI_LeadSig) == 0x41615252
  2623. && ld_dword(fs->win + FSI_StrucSig) == 0x61417272)
  2624. {
  2625. #if (_FS_NOFSINFO & 1) == 0
  2626. fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
  2627. #endif
  2628. #if (_FS_NOFSINFO & 2) == 0
  2629. fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
  2630. #endif
  2631. }
  2632. }
  2633. #endif /* (_FS_NOFSINFO & 3) != 3 */
  2634. #endif /* !_FS_READONLY */
  2635. }
  2636. fs->fs_type = fmt; /* FAT sub-type */
  2637. fs->id = ++Fsid; /* File system mount ID */
  2638. #if _USE_LFN == 1
  2639. fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
  2640. #if _FS_EXFAT
  2641. fs->dirbuf = DirBuf; /* Static directory block working buuffer */
  2642. #endif
  2643. #endif
  2644. #if _FS_RPATH != 0
  2645. fs->cdir = 0; /* Initialize current directory */
  2646. #endif
  2647. #if _FS_LOCK != 0 /* Clear file lock semaphores */
  2648. clear_lock(fs);
  2649. #endif
  2650. return FR_OK;
  2651. }
  2652. /*-----------------------------------------------------------------------*/
  2653. /* Check if the file/directory object is valid or not */
  2654. /*-----------------------------------------------------------------------*/
  2655. static
  2656. FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
  2657. _FDID* obj, /* Pointer to the _OBJ, the 1st member in the FIL/DIR object, to check validity */
  2658. FATFS** fs /* Pointer to pointer to the owner file system object to return */
  2659. )
  2660. {
  2661. FRESULT res;
  2662. if (!obj || !obj->fs || !obj->fs->fs_type || obj->fs->id != obj->id || (disk_status(obj->fs->drv) & STA_NOINIT)) {
  2663. *fs = 0; /* The object is invalid */
  2664. res = FR_INVALID_OBJECT;
  2665. } else {
  2666. *fs = obj->fs; /* Owner file sytem object */
  2667. ENTER_FF(obj->fs); /* Lock file system */
  2668. res = FR_OK;
  2669. }
  2670. return res;
  2671. }
  2672. /*---------------------------------------------------------------------------
  2673. Public Functions (FatFs API)
  2674. ----------------------------------------------------------------------------*/
  2675. /*-----------------------------------------------------------------------*/
  2676. /* Mount/Unmount a Logical Drive */
  2677. /*-----------------------------------------------------------------------*/
  2678. FRESULT f_mount (
  2679. FATFS* fs, /* Pointer to the file system object (NULL:unmount)*/
  2680. const TCHAR* path, /* Logical drive number to be mounted/unmounted */
  2681. BYTE opt /* Mode option 0:Do not mount (delayed mount), 1:Mount immediately */
  2682. )
  2683. {
  2684. FATFS *cfs;
  2685. int vol;
  2686. FRESULT res;
  2687. const TCHAR *rp = path;
  2688. /* Get logical drive number */
  2689. vol = get_ldnumber(&rp);
  2690. if (vol < 0) return FR_INVALID_DRIVE;
  2691. cfs = FatFs[vol]; /* Pointer to fs object */
  2692. if (cfs) {
  2693. #if _FS_LOCK != 0
  2694. clear_lock(cfs);
  2695. #endif
  2696. #if _FS_REENTRANT /* Discard sync object of the current volume */
  2697. if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
  2698. #endif
  2699. cfs->fs_type = 0; /* Clear old fs object */
  2700. }
  2701. if (fs) {
  2702. fs->fs_type = 0; /* Clear new fs object */
  2703. #if _FS_REENTRANT /* Create sync object for the new volume */
  2704. if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
  2705. #endif
  2706. }
  2707. FatFs[vol] = fs; /* Register new fs object */
  2708. if (!fs || opt != 1) return FR_OK; /* Do not mount now, it will be mounted later */
  2709. res = find_volume(&path, &fs, 0); /* Force mounted the volume */
  2710. LEAVE_FF(fs, res);
  2711. }
  2712. /*-----------------------------------------------------------------------*/
  2713. /* Open or Create a File */
  2714. /*-----------------------------------------------------------------------*/
  2715. FRESULT f_open (
  2716. FIL* fp, /* Pointer to the blank file object */
  2717. const TCHAR* path, /* Pointer to the file name */
  2718. BYTE mode /* Access mode and file open mode flags */
  2719. )
  2720. {
  2721. FRESULT res;
  2722. DIR dj;
  2723. FATFS *fs;
  2724. #if !_FS_READONLY
  2725. DWORD dw, cl, bcs, clst, sc;
  2726. FSIZE_t ofs;
  2727. #endif
  2728. DEF_NAMBUF
  2729. if (!fp) return FR_INVALID_OBJECT;
  2730. /* Get logical drive */
  2731. mode &= _FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND | FA_SEEKEND;
  2732. res = find_volume(&path, &fs, mode);
  2733. if (res == FR_OK) {
  2734. dj.obj.fs = fs;
  2735. INIT_NAMBUF(fs);
  2736. res = follow_path(&dj, path); /* Follow the file path */
  2737. #if !_FS_READONLY /* R/W configuration */
  2738. if (res == FR_OK) {
  2739. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  2740. res = FR_INVALID_NAME;
  2741. }
  2742. #if _FS_LOCK != 0
  2743. else {
  2744. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2745. }
  2746. #endif
  2747. }
  2748. /* Create or Open a file */
  2749. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  2750. if (res != FR_OK) { /* No file, create new */
  2751. if (res == FR_NO_FILE) /* There is no file to open, create a new entry */
  2752. #if _FS_LOCK != 0
  2753. res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  2754. #else
  2755. res = dir_register(&dj);
  2756. #endif
  2757. mode |= FA_CREATE_ALWAYS; /* File is created */
  2758. }
  2759. else { /* Any object is already existing */
  2760. if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
  2761. res = FR_DENIED;
  2762. } else {
  2763. if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
  2764. }
  2765. }
  2766. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate it if overwrite mode */
  2767. dw = GET_FATTIME();
  2768. #if _FS_EXFAT
  2769. if (fs->fs_type == FS_EXFAT) {
  2770. /* Get current allocation info */
  2771. fp->obj.fs = fs;
  2772. fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus);
  2773. fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2774. fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2775. /* Initialize directory entry block */
  2776. st_dword(fs->dirbuf + XDIR_CrtTime, dw); /* Set created time */
  2777. fs->dirbuf[XDIR_CrtTime10] = 0;
  2778. st_dword(fs->dirbuf + XDIR_ModTime, dw); /* Set modified time */
  2779. fs->dirbuf[XDIR_ModTime10] = 0;
  2780. fs->dirbuf[XDIR_Attr] = AM_ARC; /* Reset attribute */
  2781. st_dword(fs->dirbuf + XDIR_FstClus, 0); /* Reset file allocation info */
  2782. st_qword(fs->dirbuf + XDIR_FileSize, 0);
  2783. st_qword(fs->dirbuf + XDIR_ValidFileSize, 0);
  2784. fs->dirbuf[XDIR_GenFlags] = 1;
  2785. res = store_xdir(&dj);
  2786. if (res == FR_OK && fp->obj.sclust) { /* Remove the cluster chain if exist */
  2787. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  2788. fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
  2789. }
  2790. } else
  2791. #endif
  2792. {
  2793. /* Clean directory info */
  2794. st_dword(dj.dir + DIR_CrtTime, dw); /* Set created time */
  2795. st_dword(dj.dir + DIR_ModTime, dw); /* Set modified time */
  2796. dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
  2797. cl = ld_clust(fs, dj.dir); /* Get cluster chain */
  2798. st_clust(fs, dj.dir, 0); /* Reset file allocation info */
  2799. st_dword(dj.dir + DIR_FileSize, 0);
  2800. fs->wflag = 1;
  2801. if (cl) { /* Remove the cluster chain if exist */
  2802. dw = fs->winsect;
  2803. res = remove_chain(&dj.obj, cl, 0);
  2804. if (res == FR_OK) {
  2805. res = move_window(fs, dw);
  2806. fs->last_clst = cl - 1; /* Reuse the cluster hole */
  2807. }
  2808. }
  2809. }
  2810. }
  2811. }
  2812. else { /* Open an existing file */
  2813. if (res == FR_OK) { /* Following succeeded */
  2814. if (dj.obj.attr & AM_DIR) { /* It is a directory */
  2815. res = FR_NO_FILE;
  2816. } else {
  2817. if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* R/O violation */
  2818. res = FR_DENIED;
  2819. }
  2820. }
  2821. }
  2822. }
  2823. if (res == FR_OK) {
  2824. if (mode & FA_CREATE_ALWAYS) /* Set file change flag if created or overwritten */
  2825. mode |= FA_MODIFIED;
  2826. fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
  2827. fp->dir_ptr = dj.dir;
  2828. #if _FS_LOCK != 0
  2829. fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
  2830. if (!fp->obj.lockid) res = FR_INT_ERR;
  2831. #endif
  2832. }
  2833. #else /* R/O configuration */
  2834. if (res == FR_OK) {
  2835. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  2836. res = FR_INVALID_NAME;
  2837. } else {
  2838. if (dj.obj.attr & AM_DIR) { /* It is a directory */
  2839. res = FR_NO_FILE;
  2840. }
  2841. }
  2842. }
  2843. #endif
  2844. if (res == FR_OK) {
  2845. #if _FS_EXFAT
  2846. if (fs->fs_type == FS_EXFAT) {
  2847. fp->obj.sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get allocation info */
  2848. fp->obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  2849. fp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2850. fp->obj.c_scl = dj.obj.sclust;
  2851. fp->obj.c_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  2852. fp->obj.c_ofs = dj.blk_ofs;
  2853. } else
  2854. #endif
  2855. {
  2856. fp->obj.sclust = ld_clust(fs, dj.dir); /* Get allocation info */
  2857. fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
  2858. }
  2859. #if _USE_FASTSEEK
  2860. fp->cltbl = 0; /* Disable fast seek mode */
  2861. #endif
  2862. fp->obj.fs = fs; /* Validate the file object */
  2863. fp->obj.id = fs->id;
  2864. fp->flag = mode; /* Set file access mode */
  2865. fp->err = 0; /* Clear error flag */
  2866. fp->sect = 0; /* Invalidate current data sector */
  2867. fp->fptr = 0; /* Set file pointer top of the file */
  2868. #if !_FS_READONLY
  2869. #if !_FS_TINY
  2870. mem_set(fp->buf, 0, _MAX_SS); /* Clear sector buffer */
  2871. #endif
  2872. if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
  2873. fp->fptr = fp->obj.objsize; /* Offset to seek */
  2874. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
  2875. clst = fp->obj.sclust; /* Follow the cluster chain */
  2876. for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
  2877. clst = get_fat(&fp->obj, clst);
  2878. if (clst <= 1) res = FR_INT_ERR;
  2879. if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
  2880. }
  2881. fp->clust = clst;
  2882. if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
  2883. if ((sc = clust2sect(fs, clst)) == 0) {
  2884. res = FR_INT_ERR;
  2885. } else {
  2886. fp->sect = sc + (DWORD)(ofs / SS(fs));
  2887. #if !_FS_TINY
  2888. if (disk_read(fs->drv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
  2889. #endif
  2890. }
  2891. }
  2892. }
  2893. #endif
  2894. }
  2895. FREE_NAMBUF();
  2896. }
  2897. if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
  2898. LEAVE_FF(fs, res);
  2899. }
  2900. /*-----------------------------------------------------------------------*/
  2901. /* Read File */
  2902. /*-----------------------------------------------------------------------*/
  2903. FRESULT f_read (
  2904. FIL* fp, /* Pointer to the file object */
  2905. void* buff, /* Pointer to data buffer */
  2906. UINT btr, /* Number of bytes to read */
  2907. UINT* br /* Pointer to number of bytes read */
  2908. )
  2909. {
  2910. FRESULT res;
  2911. FATFS *fs;
  2912. DWORD clst, sect;
  2913. FSIZE_t remain;
  2914. UINT rcnt, cc, csect;
  2915. BYTE *rbuff = (BYTE*)buff;
  2916. *br = 0; /* Clear read byte counter */
  2917. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  2918. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  2919. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  2920. remain = fp->obj.objsize - fp->fptr;
  2921. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  2922. for ( ; btr; /* Repeat until all data read */
  2923. rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
  2924. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  2925. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  2926. if (csect == 0) { /* On the cluster boundary? */
  2927. if (fp->fptr == 0) { /* On the top of the file? */
  2928. clst = fp->obj.sclust; /* Follow cluster chain from the origin */
  2929. } else { /* Middle or end of the file */
  2930. #if _USE_FASTSEEK
  2931. if (fp->cltbl) {
  2932. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  2933. } else
  2934. #endif
  2935. {
  2936. clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
  2937. }
  2938. }
  2939. if (clst < 2) ABORT(fs, FR_INT_ERR);
  2940. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  2941. fp->clust = clst; /* Update current cluster */
  2942. }
  2943. sect = clust2sect(fs, fp->clust); /* Get current sector */
  2944. if (!sect) ABORT(fs, FR_INT_ERR);
  2945. sect += csect;
  2946. cc = btr / SS(fs); /* When remaining bytes >= sector size, */
  2947. if (cc) { /* Read maximum contiguous sectors directly */
  2948. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  2949. cc = fs->csize - csect;
  2950. }
  2951. if (disk_read(fs->drv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  2952. #if !_FS_READONLY && _FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  2953. #if _FS_TINY
  2954. if (fs->wflag && fs->winsect - sect < cc) {
  2955. mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
  2956. }
  2957. #else
  2958. if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
  2959. mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
  2960. }
  2961. #endif
  2962. #endif
  2963. rcnt = SS(fs) * cc; /* Number of bytes transferred */
  2964. continue;
  2965. }
  2966. #if !_FS_TINY
  2967. if (fp->sect != sect) { /* Load data sector if not in cache */
  2968. #if !_FS_READONLY
  2969. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  2970. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  2971. fp->flag &= (BYTE)~FA_DIRTY;
  2972. }
  2973. #endif
  2974. if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  2975. }
  2976. #endif
  2977. fp->sect = sect;
  2978. }
  2979. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  2980. if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
  2981. #if _FS_TINY
  2982. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  2983. mem_cpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  2984. #else
  2985. mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  2986. #endif
  2987. }
  2988. LEAVE_FF(fs, FR_OK);
  2989. }
  2990. #if !_FS_READONLY
  2991. /*-----------------------------------------------------------------------*/
  2992. /* Write File */
  2993. /*-----------------------------------------------------------------------*/
  2994. FRESULT f_write (
  2995. FIL* fp, /* Pointer to the file object */
  2996. const void* buff, /* Pointer to the data to be written */
  2997. UINT btw, /* Number of bytes to write */
  2998. UINT* bw /* Pointer to number of bytes written */
  2999. )
  3000. {
  3001. FRESULT res;
  3002. FATFS *fs;
  3003. DWORD clst, sect;
  3004. UINT wcnt, cc, csect;
  3005. const BYTE *wbuff = (const BYTE*)buff;
  3006. *bw = 0; /* Clear write byte counter */
  3007. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3008. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3009. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3010. /* Check fptr wrap-around (file size cannot reach 4GiB on FATxx) */
  3011. if ((!_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
  3012. btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
  3013. }
  3014. for ( ; btw; /* Repeat until all data written */
  3015. wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize, *bw += wcnt, btw -= wcnt) {
  3016. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  3017. csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
  3018. if (csect == 0) { /* On the cluster boundary? */
  3019. if (fp->fptr == 0) { /* On the top of the file? */
  3020. clst = fp->obj.sclust; /* Follow from the origin */
  3021. if (clst == 0) { /* If no cluster is allocated, */
  3022. clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
  3023. }
  3024. } else { /* On the middle or end of the file */
  3025. #if _USE_FASTSEEK
  3026. if (fp->cltbl) {
  3027. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  3028. } else
  3029. #endif
  3030. {
  3031. clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
  3032. }
  3033. }
  3034. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  3035. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3036. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3037. fp->clust = clst; /* Update current cluster */
  3038. if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
  3039. }
  3040. #if _FS_TINY
  3041. if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
  3042. #else
  3043. if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
  3044. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3045. fp->flag &= (BYTE)~FA_DIRTY;
  3046. }
  3047. #endif
  3048. sect = clust2sect(fs, fp->clust); /* Get current sector */
  3049. if (!sect) ABORT(fs, FR_INT_ERR);
  3050. sect += csect;
  3051. cc = btw / SS(fs); /* When remaining bytes >= sector size, */
  3052. if (cc) { /* Write maximum contiguous sectors directly */
  3053. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3054. cc = fs->csize - csect;
  3055. }
  3056. if (disk_write(fs->drv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3057. #if _FS_MINIMIZE <= 2
  3058. #if _FS_TINY
  3059. if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3060. mem_cpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
  3061. fs->wflag = 0;
  3062. }
  3063. #else
  3064. if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3065. mem_cpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
  3066. fp->flag &= (BYTE)~FA_DIRTY;
  3067. }
  3068. #endif
  3069. #endif
  3070. wcnt = SS(fs) * cc; /* Number of bytes transferred */
  3071. continue;
  3072. }
  3073. #if _FS_TINY
  3074. if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
  3075. if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
  3076. fs->winsect = sect;
  3077. }
  3078. #else
  3079. if (fp->sect != sect && /* Fill sector cache with file data */
  3080. fp->fptr < fp->obj.objsize &&
  3081. disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) {
  3082. ABORT(fs, FR_DISK_ERR);
  3083. }
  3084. #endif
  3085. fp->sect = sect;
  3086. }
  3087. wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  3088. if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
  3089. #if _FS_TINY
  3090. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3091. mem_cpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3092. fs->wflag = 1;
  3093. #else
  3094. mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3095. fp->flag |= FA_DIRTY;
  3096. #endif
  3097. }
  3098. fp->flag |= FA_MODIFIED; /* Set file change flag */
  3099. LEAVE_FF(fs, FR_OK);
  3100. }
  3101. /*-----------------------------------------------------------------------*/
  3102. /* Synchronize the File */
  3103. /*-----------------------------------------------------------------------*/
  3104. FRESULT f_sync (
  3105. FIL* fp /* Pointer to the file object */
  3106. )
  3107. {
  3108. FRESULT res;
  3109. FATFS *fs;
  3110. DWORD tm;
  3111. BYTE *dir;
  3112. #if _FS_EXFAT
  3113. DEF_NAMBUF
  3114. #endif
  3115. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3116. if (res == FR_OK) {
  3117. if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
  3118. #if !_FS_TINY
  3119. if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
  3120. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
  3121. fp->flag &= (BYTE)~FA_DIRTY;
  3122. }
  3123. #endif
  3124. /* Update the directory entry */
  3125. tm = GET_FATTIME(); /* Modified time */
  3126. #if _FS_EXFAT
  3127. if (fs->fs_type == FS_EXFAT) {
  3128. res = fill_fat_chain(&fp->obj); /* Create FAT chain if needed */
  3129. if (res == FR_OK) {
  3130. DIR dj;
  3131. INIT_NAMBUF(fs);
  3132. res = load_obj_dir(&dj, &fp->obj); /* Load directory entry block */
  3133. if (res == FR_OK) {
  3134. fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive bit */
  3135. fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation info */
  3136. st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);
  3137. st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);
  3138. st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);
  3139. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
  3140. fs->dirbuf[XDIR_ModTime10] = 0;
  3141. st_dword(fs->dirbuf + XDIR_AccTime, 0);
  3142. res = store_xdir(&dj); /* Restore it to the directory */
  3143. if (res == FR_OK) {
  3144. res = sync_fs(fs);
  3145. fp->flag &= (BYTE)~FA_MODIFIED;
  3146. }
  3147. }
  3148. FREE_NAMBUF();
  3149. }
  3150. } else
  3151. #endif
  3152. {
  3153. res = move_window(fs, fp->dir_sect);
  3154. if (res == FR_OK) {
  3155. dir = fp->dir_ptr;
  3156. dir[DIR_Attr] |= AM_ARC; /* Set archive bit */
  3157. st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation info */
  3158. st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
  3159. st_dword(dir + DIR_ModTime, tm); /* Update modified time */
  3160. st_word(dir + DIR_LstAccDate, 0);
  3161. fs->wflag = 1;
  3162. res = sync_fs(fs); /* Restore it to the directory */
  3163. fp->flag &= (BYTE)~FA_MODIFIED;
  3164. }
  3165. }
  3166. }
  3167. }
  3168. LEAVE_FF(fs, res);
  3169. }
  3170. #endif /* !_FS_READONLY */
  3171. /*-----------------------------------------------------------------------*/
  3172. /* Close File */
  3173. /*-----------------------------------------------------------------------*/
  3174. FRESULT f_close (
  3175. FIL* fp /* Pointer to the file object to be closed */
  3176. )
  3177. {
  3178. FRESULT res;
  3179. FATFS *fs;
  3180. #if !_FS_READONLY
  3181. res = f_sync(fp); /* Flush cached data */
  3182. if (res == FR_OK)
  3183. #endif
  3184. {
  3185. res = validate(&fp->obj, &fs); /* Lock volume */
  3186. if (res == FR_OK) {
  3187. #if _FS_LOCK != 0
  3188. res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
  3189. if (res == FR_OK)
  3190. #endif
  3191. {
  3192. fp->obj.fs = 0; /* Invalidate file object */
  3193. }
  3194. #if _FS_REENTRANT
  3195. unlock_fs(fs, FR_OK); /* Unlock volume */
  3196. #endif
  3197. }
  3198. }
  3199. return res;
  3200. }
  3201. #if _FS_RPATH >= 1
  3202. /*-----------------------------------------------------------------------*/
  3203. /* Change Current Directory or Current Drive, Get Current Directory */
  3204. /*-----------------------------------------------------------------------*/
  3205. #if _VOLUMES >= 2
  3206. FRESULT f_chdrive (
  3207. const TCHAR* path /* Drive number */
  3208. )
  3209. {
  3210. int vol;
  3211. /* Get logical drive number */
  3212. vol = get_ldnumber(&path);
  3213. if (vol < 0) return FR_INVALID_DRIVE;
  3214. CurrVol = (BYTE)vol; /* Set it as current volume */
  3215. return FR_OK;
  3216. }
  3217. #endif
  3218. FRESULT f_chdir (
  3219. const TCHAR* path /* Pointer to the directory path */
  3220. )
  3221. {
  3222. FRESULT res;
  3223. DIR dj;
  3224. FATFS *fs;
  3225. DEF_NAMBUF
  3226. /* Get logical drive */
  3227. res = find_volume(&path, &fs, 0);
  3228. if (res == FR_OK) {
  3229. dj.obj.fs = fs;
  3230. INIT_NAMBUF(fs);
  3231. res = follow_path(&dj, path); /* Follow the path */
  3232. if (res == FR_OK) { /* Follow completed */
  3233. if (dj.fn[NSFLAG] & NS_NONAME) {
  3234. fs->cdir = dj.obj.sclust; /* It is the start directory itself */
  3235. #if _FS_EXFAT
  3236. if (fs->fs_type == FS_EXFAT) {
  3237. fs->cdc_scl = dj.obj.c_scl;
  3238. fs->cdc_size = dj.obj.c_size;
  3239. fs->cdc_ofs = dj.obj.c_ofs;
  3240. }
  3241. #endif
  3242. } else {
  3243. if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
  3244. #if _FS_EXFAT
  3245. if (fs->fs_type == FS_EXFAT) {
  3246. fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
  3247. fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
  3248. fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  3249. fs->cdc_ofs = dj.blk_ofs;
  3250. } else
  3251. #endif
  3252. {
  3253. fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
  3254. }
  3255. } else {
  3256. res = FR_NO_PATH; /* Reached but a file */
  3257. }
  3258. }
  3259. }
  3260. FREE_NAMBUF();
  3261. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3262. }
  3263. LEAVE_FF(fs, res);
  3264. }
  3265. #if _FS_RPATH >= 2
  3266. FRESULT f_getcwd (
  3267. TCHAR* buff, /* Pointer to the directory path */
  3268. UINT len /* Size of path */
  3269. )
  3270. {
  3271. FRESULT res;
  3272. DIR dj;
  3273. FATFS *fs;
  3274. UINT i, n;
  3275. DWORD ccl;
  3276. TCHAR *tp;
  3277. FILINFO fno;
  3278. DEF_NAMBUF
  3279. *buff = 0;
  3280. /* Get logical drive */
  3281. res = find_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */
  3282. if (res == FR_OK) {
  3283. dj.obj.fs = fs;
  3284. INIT_NAMBUF(fs);
  3285. i = len; /* Bottom of buffer (directory stack base) */
  3286. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
  3287. dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
  3288. while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
  3289. res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
  3290. if (res != FR_OK) break;
  3291. res = move_window(fs, dj.sect);
  3292. if (res != FR_OK) break;
  3293. dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
  3294. res = dir_sdi(&dj, 0);
  3295. if (res != FR_OK) break;
  3296. do { /* Find the entry links to the child directory */
  3297. res = dir_read(&dj, 0);
  3298. if (res != FR_OK) break;
  3299. if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
  3300. res = dir_next(&dj, 0);
  3301. } while (res == FR_OK);
  3302. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  3303. if (res != FR_OK) break;
  3304. get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
  3305. for (n = 0; fno.fname[n]; n++) ;
  3306. if (i < n + 3) {
  3307. res = FR_NOT_ENOUGH_CORE; break;
  3308. }
  3309. while (n) buff[--i] = fno.fname[--n];
  3310. buff[--i] = '/';
  3311. }
  3312. }
  3313. tp = buff;
  3314. if (res == FR_OK) {
  3315. #if _VOLUMES >= 2
  3316. *tp++ = '0' + CurrVol; /* Put drive number */
  3317. *tp++ = ':';
  3318. #endif
  3319. if (i == len) { /* Root-directory */
  3320. *tp++ = '/';
  3321. } else { /* Sub-directroy */
  3322. do /* Add stacked path str */
  3323. *tp++ = buff[i++];
  3324. while (i < len);
  3325. }
  3326. }
  3327. *tp = 0;
  3328. FREE_NAMBUF();
  3329. }
  3330. LEAVE_FF(fs, res);
  3331. }
  3332. #endif /* _FS_RPATH >= 2 */
  3333. #endif /* _FS_RPATH >= 1 */
  3334. #if _FS_MINIMIZE <= 2
  3335. /*-----------------------------------------------------------------------*/
  3336. /* Seek File R/W Pointer */
  3337. /*-----------------------------------------------------------------------*/
  3338. FRESULT f_lseek (
  3339. FIL* fp, /* Pointer to the file object */
  3340. FSIZE_t ofs /* File pointer from top of file */
  3341. )
  3342. {
  3343. FRESULT res;
  3344. FATFS *fs;
  3345. DWORD clst, bcs, nsect;
  3346. FSIZE_t ifptr;
  3347. #if _USE_FASTSEEK
  3348. DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
  3349. #endif
  3350. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3351. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3352. #if _USE_FASTSEEK
  3353. if (fp->cltbl) { /* Fast seek */
  3354. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  3355. tbl = fp->cltbl;
  3356. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  3357. cl = fp->obj.sclust; /* Origin of the chain */
  3358. if (cl) {
  3359. do {
  3360. /* Get a fragment */
  3361. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  3362. do {
  3363. pcl = cl; ncl++;
  3364. cl = get_fat(&fp->obj, cl);
  3365. if (cl <= 1) ABORT(fs, FR_INT_ERR);
  3366. if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3367. } while (cl == pcl + 1);
  3368. if (ulen <= tlen) { /* Store the length and top of the fragment */
  3369. *tbl++ = ncl; *tbl++ = tcl;
  3370. }
  3371. } while (cl < fs->n_fatent); /* Repeat until end of chain */
  3372. }
  3373. *fp->cltbl = ulen; /* Number of items used */
  3374. if (ulen <= tlen) {
  3375. *tbl = 0; /* Terminate table */
  3376. } else {
  3377. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  3378. }
  3379. } else { /* Fast seek */
  3380. if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
  3381. fp->fptr = ofs; /* Set file pointer */
  3382. if (ofs) {
  3383. fp->clust = clmt_clust(fp, ofs - 1);
  3384. dsc = clust2sect(fs, fp->clust);
  3385. if (!dsc) ABORT(fs, FR_INT_ERR);
  3386. dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
  3387. if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
  3388. #if !_FS_TINY
  3389. #if !_FS_READONLY
  3390. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3391. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3392. fp->flag &= (BYTE)~FA_DIRTY;
  3393. }
  3394. #endif
  3395. if (disk_read(fs->drv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
  3396. #endif
  3397. fp->sect = dsc;
  3398. }
  3399. }
  3400. }
  3401. } else
  3402. #endif
  3403. /* Normal Seek */
  3404. {
  3405. #if _FS_EXFAT
  3406. if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4GiB-1 if at FATxx */
  3407. #endif
  3408. if (ofs > fp->obj.objsize && (_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
  3409. ofs = fp->obj.objsize;
  3410. }
  3411. ifptr = fp->fptr;
  3412. fp->fptr = nsect = 0;
  3413. if (ofs) {
  3414. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
  3415. if (ifptr > 0 &&
  3416. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  3417. fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
  3418. ofs -= fp->fptr;
  3419. clst = fp->clust;
  3420. } else { /* When seek to back cluster, */
  3421. clst = fp->obj.sclust; /* start from the first cluster */
  3422. #if !_FS_READONLY
  3423. if (clst == 0) { /* If no cluster chain, create a new chain */
  3424. clst = create_chain(&fp->obj, 0);
  3425. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3426. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3427. fp->obj.sclust = clst;
  3428. }
  3429. #endif
  3430. fp->clust = clst;
  3431. }
  3432. if (clst != 0) {
  3433. while (ofs > bcs) { /* Cluster following loop */
  3434. ofs -= bcs; fp->fptr += bcs;
  3435. #if !_FS_READONLY
  3436. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  3437. if (_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
  3438. fp->obj.objsize = fp->fptr;
  3439. fp->flag |= FA_MODIFIED;
  3440. }
  3441. clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
  3442. if (clst == 0) { /* Clip file size in case of disk full */
  3443. ofs = 0; break;
  3444. }
  3445. } else
  3446. #endif
  3447. {
  3448. clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
  3449. }
  3450. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3451. if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
  3452. fp->clust = clst;
  3453. }
  3454. fp->fptr += ofs;
  3455. if (ofs % SS(fs)) {
  3456. nsect = clust2sect(fs, clst); /* Current sector */
  3457. if (!nsect) ABORT(fs, FR_INT_ERR);
  3458. nsect += (DWORD)(ofs / SS(fs));
  3459. }
  3460. }
  3461. }
  3462. if (!_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
  3463. fp->obj.objsize = fp->fptr;
  3464. fp->flag |= FA_MODIFIED;
  3465. }
  3466. if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
  3467. #if !_FS_TINY
  3468. #if !_FS_READONLY
  3469. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3470. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3471. fp->flag &= (BYTE)~FA_DIRTY;
  3472. }
  3473. #endif
  3474. if (disk_read(fs->drv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3475. #endif
  3476. fp->sect = nsect;
  3477. }
  3478. }
  3479. LEAVE_FF(fs, res);
  3480. }
  3481. #if _FS_MINIMIZE <= 1
  3482. /*-----------------------------------------------------------------------*/
  3483. /* Create a Directory Object */
  3484. /*-----------------------------------------------------------------------*/
  3485. FRESULT f_opendir (
  3486. DIR* dp, /* Pointer to directory object to create */
  3487. const TCHAR* path /* Pointer to the directory path */
  3488. )
  3489. {
  3490. FRESULT res;
  3491. FATFS *fs;
  3492. _FDID *obj;
  3493. DEF_NAMBUF
  3494. if (!dp) return FR_INVALID_OBJECT;
  3495. /* Get logical drive */
  3496. obj = &dp->obj;
  3497. res = find_volume(&path, &fs, 0);
  3498. if (res == FR_OK) {
  3499. obj->fs = fs;
  3500. INIT_NAMBUF(fs);
  3501. res = follow_path(dp, path); /* Follow the path to the directory */
  3502. if (res == FR_OK) { /* Follow completed */
  3503. if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
  3504. if (obj->attr & AM_DIR) { /* This object is a sub-directory */
  3505. #if _FS_EXFAT
  3506. if (fs->fs_type == FS_EXFAT) {
  3507. obj->c_scl = obj->sclust; /* Save containing directory inforamation */
  3508. obj->c_size = ((DWORD)obj->objsize & 0xFFFFFF00) | obj->stat;
  3509. obj->c_ofs = dp->blk_ofs;
  3510. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Get object location and status */
  3511. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  3512. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2;
  3513. } else
  3514. #endif
  3515. {
  3516. obj->sclust = ld_clust(fs, dp->dir); /* Get object location */
  3517. }
  3518. } else { /* This object is a file */
  3519. res = FR_NO_PATH;
  3520. }
  3521. }
  3522. if (res == FR_OK) {
  3523. obj->id = fs->id;
  3524. res = dir_sdi(dp, 0); /* Rewind directory */
  3525. #if _FS_LOCK != 0
  3526. if (res == FR_OK) {
  3527. if (obj->sclust) {
  3528. obj->lockid = inc_lock(dp, 0); /* Lock the sub directory */
  3529. if (!obj->lockid) res = FR_TOO_MANY_OPEN_FILES;
  3530. } else {
  3531. obj->lockid = 0; /* Root directory need not to be locked */
  3532. }
  3533. }
  3534. #endif
  3535. }
  3536. }
  3537. FREE_NAMBUF();
  3538. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3539. }
  3540. if (res != FR_OK) obj->fs = 0; /* Invalidate the directory object if function faild */
  3541. LEAVE_FF(fs, res);
  3542. }
  3543. /*-----------------------------------------------------------------------*/
  3544. /* Close Directory */
  3545. /*-----------------------------------------------------------------------*/
  3546. FRESULT f_closedir (
  3547. DIR *dp /* Pointer to the directory object to be closed */
  3548. )
  3549. {
  3550. FRESULT res;
  3551. FATFS *fs;
  3552. res = validate(&dp->obj, &fs); /* Check validity of the file object */
  3553. if (res == FR_OK) {
  3554. #if _FS_LOCK != 0
  3555. if (dp->obj.lockid) { /* Decrement sub-directory open counter */
  3556. res = dec_lock(dp->obj.lockid);
  3557. }
  3558. if (res == FR_OK)
  3559. #endif
  3560. {
  3561. dp->obj.fs = 0; /* Invalidate directory object */
  3562. }
  3563. #if _FS_REENTRANT
  3564. unlock_fs(fs, FR_OK); /* Unlock volume */
  3565. #endif
  3566. }
  3567. return res;
  3568. }
  3569. /*-----------------------------------------------------------------------*/
  3570. /* Read Directory Entries in Sequence */
  3571. /*-----------------------------------------------------------------------*/
  3572. FRESULT f_readdir (
  3573. DIR* dp, /* Pointer to the open directory object */
  3574. FILINFO* fno /* Pointer to file information to return */
  3575. )
  3576. {
  3577. FRESULT res;
  3578. FATFS *fs;
  3579. DEF_NAMBUF
  3580. res = validate(&dp->obj, &fs); /* Check validity of the directory object */
  3581. if (res == FR_OK) {
  3582. if (!fno) {
  3583. res = dir_sdi(dp, 0); /* Rewind the directory object */
  3584. } else {
  3585. INIT_NAMBUF(fs);
  3586. res = dir_read(dp, 0); /* Read an item */
  3587. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
  3588. if (res == FR_OK) { /* A valid entry is found */
  3589. get_fileinfo(dp, fno); /* Get the object information */
  3590. res = dir_next(dp, 0); /* Increment index for next */
  3591. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
  3592. }
  3593. FREE_NAMBUF();
  3594. }
  3595. }
  3596. LEAVE_FF(fs, res);
  3597. }
  3598. FRESULT f_seekdir(
  3599. DIR *dj, /* Pointer to the open directory object */
  3600. int offset /* the seek offset */
  3601. )
  3602. {
  3603. int i = 0;
  3604. if (dir_sdi(dj, 0) != FR_OK || offset < 0)
  3605. return FR_INT_ERR;
  3606. while(i < offset)
  3607. {
  3608. if(dir_read(dj, 0) != FR_OK || dir_next(dj, 0) != FR_OK)
  3609. return FR_INT_ERR;
  3610. i++;
  3611. }
  3612. return FR_OK;
  3613. }
  3614. #if _USE_FIND
  3615. /*-----------------------------------------------------------------------*/
  3616. /* Find Next File */
  3617. /*-----------------------------------------------------------------------*/
  3618. FRESULT f_findnext (
  3619. DIR* dp, /* Pointer to the open directory object */
  3620. FILINFO* fno /* Pointer to the file information structure */
  3621. )
  3622. {
  3623. FRESULT res;
  3624. for (;;) {
  3625. res = f_readdir(dp, fno); /* Get a directory item */
  3626. if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
  3627. if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */
  3628. #if _USE_LFN != 0 && _USE_FIND == 2
  3629. if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */
  3630. #endif
  3631. }
  3632. return res;
  3633. }
  3634. /*-----------------------------------------------------------------------*/
  3635. /* Find First File */
  3636. /*-----------------------------------------------------------------------*/
  3637. FRESULT f_findfirst (
  3638. DIR* dp, /* Pointer to the blank directory object */
  3639. FILINFO* fno, /* Pointer to the file information structure */
  3640. const TCHAR* path, /* Pointer to the directory to open */
  3641. const TCHAR* pattern /* Pointer to the matching pattern */
  3642. )
  3643. {
  3644. FRESULT res;
  3645. dp->pat = pattern; /* Save pointer to pattern string */
  3646. res = f_opendir(dp, path); /* Open the target directory */
  3647. if (res == FR_OK) {
  3648. res = f_findnext(dp, fno); /* Find the first item */
  3649. }
  3650. return res;
  3651. }
  3652. #endif /* _USE_FIND */
  3653. #if _FS_MINIMIZE == 0
  3654. /*-----------------------------------------------------------------------*/
  3655. /* Get File Status */
  3656. /*-----------------------------------------------------------------------*/
  3657. FRESULT f_stat (
  3658. const TCHAR* path, /* Pointer to the file path */
  3659. FILINFO* fno /* Pointer to file information to return */
  3660. )
  3661. {
  3662. FRESULT res;
  3663. DIR dj;
  3664. DEF_NAMBUF
  3665. /* Get logical drive */
  3666. res = find_volume(&path, &dj.obj.fs, 0);
  3667. if (res == FR_OK) {
  3668. INIT_NAMBUF(dj.obj.fs);
  3669. res = follow_path(&dj, path); /* Follow the file path */
  3670. if (res == FR_OK) { /* Follow completed */
  3671. if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
  3672. res = FR_INVALID_NAME;
  3673. } else { /* Found an object */
  3674. if (fno) get_fileinfo(&dj, fno);
  3675. }
  3676. }
  3677. FREE_NAMBUF();
  3678. }
  3679. LEAVE_FF(dj.obj.fs, res);
  3680. }
  3681. #if !_FS_READONLY
  3682. /*-----------------------------------------------------------------------*/
  3683. /* Get Number of Free Clusters */
  3684. /*-----------------------------------------------------------------------*/
  3685. FRESULT f_getfree (
  3686. const TCHAR* path, /* Path name of the logical drive number */
  3687. DWORD* nclst, /* Pointer to a variable to return number of free clusters */
  3688. FATFS** fatfs /* Pointer to return pointer to corresponding file system object */
  3689. )
  3690. {
  3691. FRESULT res;
  3692. FATFS *fs;
  3693. DWORD nfree, clst, sect, stat;
  3694. UINT i;
  3695. BYTE *p;
  3696. _FDID obj;
  3697. /* Get logical drive */
  3698. res = find_volume(&path, &fs, 0);
  3699. if (res == FR_OK) {
  3700. *fatfs = fs; /* Return ptr to the fs object */
  3701. /* If free_clst is valid, return it without full cluster scan */
  3702. if (fs->free_clst <= fs->n_fatent - 2) {
  3703. *nclst = fs->free_clst;
  3704. } else {
  3705. /* Get number of free clusters */
  3706. nfree = 0;
  3707. if (fs->fs_type == FS_FAT12) { /* FAT12: Sector unalighed FAT entries */
  3708. clst = 2; obj.fs = fs;
  3709. do {
  3710. stat = get_fat(&obj, clst);
  3711. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  3712. if (stat == 1) { res = FR_INT_ERR; break; }
  3713. if (stat == 0) nfree++;
  3714. } while (++clst < fs->n_fatent);
  3715. } else {
  3716. #if _FS_EXFAT
  3717. if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan bitmap table */
  3718. BYTE bm;
  3719. UINT b;
  3720. clst = fs->n_fatent - 2;
  3721. sect = fs->database;
  3722. i = 0;
  3723. do {
  3724. if (i == 0 && (res = move_window(fs, sect++)) != FR_OK) break;
  3725. for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
  3726. if (!(bm & 1)) nfree++;
  3727. bm >>= 1;
  3728. }
  3729. i = (i + 1) % SS(fs);
  3730. } while (clst);
  3731. } else
  3732. #endif
  3733. { /* FAT16/32: Sector alighed FAT entries */
  3734. clst = fs->n_fatent; sect = fs->fatbase;
  3735. i = 0; p = 0;
  3736. do {
  3737. if (i == 0) {
  3738. res = move_window(fs, sect++);
  3739. if (res != FR_OK) break;
  3740. p = fs->win;
  3741. i = SS(fs);
  3742. }
  3743. if (fs->fs_type == FS_FAT16) {
  3744. if (ld_word(p) == 0) nfree++;
  3745. p += 2; i -= 2;
  3746. } else {
  3747. if ((ld_dword(p) & 0x0FFFFFFF) == 0) nfree++;
  3748. p += 4; i -= 4;
  3749. }
  3750. } while (--clst);
  3751. }
  3752. }
  3753. *nclst = nfree; /* Return the free clusters */
  3754. fs->free_clst = nfree; /* Now free_clst is valid */
  3755. fs->fsi_flag |= 1; /* FSInfo is to be updated */
  3756. }
  3757. }
  3758. LEAVE_FF(fs, res);
  3759. }
  3760. /*-----------------------------------------------------------------------*/
  3761. /* Truncate File */
  3762. /*-----------------------------------------------------------------------*/
  3763. FRESULT f_truncate (
  3764. FIL* fp /* Pointer to the file object */
  3765. )
  3766. {
  3767. FRESULT res;
  3768. FATFS *fs;
  3769. DWORD ncl;
  3770. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3771. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  3772. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3773. if (fp->obj.objsize > fp->fptr) {
  3774. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  3775. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  3776. fp->obj.sclust = 0;
  3777. } else { /* When truncate a part of the file, remove remaining clusters */
  3778. ncl = get_fat(&fp->obj, fp->clust);
  3779. res = FR_OK;
  3780. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3781. if (ncl == 1) res = FR_INT_ERR;
  3782. if (res == FR_OK && ncl < fs->n_fatent) {
  3783. res = remove_chain(&fp->obj, ncl, fp->clust);
  3784. }
  3785. }
  3786. fp->obj.objsize = fp->fptr; /* Set file size to current R/W point */
  3787. fp->flag |= FA_MODIFIED;
  3788. #if !_FS_TINY
  3789. if (res == FR_OK && (fp->flag & FA_DIRTY)) {
  3790. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) {
  3791. res = FR_DISK_ERR;
  3792. } else {
  3793. fp->flag &= (BYTE)~FA_DIRTY;
  3794. }
  3795. }
  3796. #endif
  3797. if (res != FR_OK) ABORT(fs, res);
  3798. }
  3799. LEAVE_FF(fs, res);
  3800. }
  3801. /*-----------------------------------------------------------------------*/
  3802. /* Delete a File/Directory */
  3803. /*-----------------------------------------------------------------------*/
  3804. FRESULT f_unlink (
  3805. const TCHAR* path /* Pointer to the file or directory path */
  3806. )
  3807. {
  3808. FRESULT res;
  3809. DIR dj, sdj;
  3810. DWORD dclst = 0;
  3811. FATFS *fs;
  3812. #if _FS_EXFAT
  3813. _FDID obj;
  3814. #endif
  3815. DEF_NAMBUF
  3816. /* Get logical drive */
  3817. res = find_volume(&path, &fs, FA_WRITE);
  3818. dj.obj.fs = fs;
  3819. if (res == FR_OK) {
  3820. INIT_NAMBUF(fs);
  3821. res = follow_path(&dj, path); /* Follow the file path */
  3822. if (_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
  3823. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  3824. }
  3825. #if _FS_LOCK != 0
  3826. if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
  3827. #endif
  3828. if (res == FR_OK) { /* The object is accessible */
  3829. if (dj.fn[NSFLAG] & NS_NONAME) {
  3830. res = FR_INVALID_NAME; /* Cannot remove the origin directory */
  3831. } else {
  3832. if (dj.obj.attr & AM_RDO) {
  3833. res = FR_DENIED; /* Cannot remove R/O object */
  3834. }
  3835. }
  3836. if (res == FR_OK) {
  3837. #if _FS_EXFAT
  3838. obj.fs = fs;
  3839. if (fs->fs_type == FS_EXFAT) {
  3840. obj.sclust = dclst = ld_dword(fs->dirbuf + XDIR_FstClus);
  3841. obj.objsize = ld_qword(fs->dirbuf + XDIR_FileSize);
  3842. obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  3843. } else
  3844. #endif
  3845. {
  3846. dclst = ld_clust(fs, dj.dir);
  3847. }
  3848. if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory ? */
  3849. #if _FS_RPATH != 0
  3850. if (dclst == fs->cdir) { /* Is it the current directory? */
  3851. res = FR_DENIED;
  3852. } else
  3853. #endif
  3854. {
  3855. sdj.obj.fs = fs; /* Open the sub-directory */
  3856. sdj.obj.sclust = dclst;
  3857. #if _FS_EXFAT
  3858. if (fs->fs_type == FS_EXFAT) {
  3859. sdj.obj.objsize = obj.objsize;
  3860. sdj.obj.stat = obj.stat;
  3861. }
  3862. #endif
  3863. res = dir_sdi(&sdj, 0);
  3864. if (res == FR_OK) {
  3865. res = dir_read(&sdj, 0); /* Read an item */
  3866. if (res == FR_OK) res = FR_DENIED; /* Not empty? */
  3867. if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
  3868. }
  3869. }
  3870. }
  3871. }
  3872. if (res == FR_OK) {
  3873. res = dir_remove(&dj); /* Remove the directory entry */
  3874. if (res == FR_OK && dclst) { /* Remove the cluster chain if exist */
  3875. #if _FS_EXFAT
  3876. res = remove_chain(&obj, dclst, 0);
  3877. #else
  3878. res = remove_chain(&dj.obj, dclst, 0);
  3879. #endif
  3880. }
  3881. if (res == FR_OK) res = sync_fs(fs);
  3882. }
  3883. }
  3884. FREE_NAMBUF();
  3885. }
  3886. LEAVE_FF(fs, res);
  3887. }
  3888. /*-----------------------------------------------------------------------*/
  3889. /* Create a Directory */
  3890. /*-----------------------------------------------------------------------*/
  3891. FRESULT f_mkdir (
  3892. const TCHAR* path /* Pointer to the directory path */
  3893. )
  3894. {
  3895. FRESULT res;
  3896. DIR dj;
  3897. FATFS *fs;
  3898. BYTE *dir;
  3899. UINT n;
  3900. DWORD dsc, dcl, pcl, tm;
  3901. DEF_NAMBUF
  3902. /* Get logical drive */
  3903. res = find_volume(&path, &fs, FA_WRITE);
  3904. dj.obj.fs = fs;
  3905. if (res == FR_OK) {
  3906. INIT_NAMBUF(fs);
  3907. res = follow_path(&dj, path); /* Follow the file path */
  3908. if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */
  3909. if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {
  3910. res = FR_INVALID_NAME;
  3911. }
  3912. if (res == FR_NO_FILE) { /* Can create a new directory */
  3913. dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */
  3914. dj.obj.objsize = (DWORD)fs->csize * SS(fs);
  3915. res = FR_OK;
  3916. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */
  3917. if (dcl == 1) res = FR_INT_ERR;
  3918. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
  3919. if (res == FR_OK) res = sync_window(fs); /* Flush FAT */
  3920. tm = GET_FATTIME();
  3921. if (res == FR_OK) { /* Initialize the new directory table */
  3922. dsc = clust2sect(fs, dcl);
  3923. dir = fs->win;
  3924. mem_set(dir, 0, SS(fs));
  3925. if (!_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  3926. mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */
  3927. dir[DIR_Name] = '.';
  3928. dir[DIR_Attr] = AM_DIR;
  3929. st_dword(dir + DIR_ModTime, tm);
  3930. st_clust(fs, dir, dcl);
  3931. mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */
  3932. dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
  3933. if (fs->fs_type == FS_FAT32 && pcl == fs->dirbase) pcl = 0;
  3934. st_clust(fs, dir + SZDIRE, pcl);
  3935. }
  3936. for (n = fs->csize; n; n--) { /* Write dot entries and clear following sectors */
  3937. fs->winsect = dsc++;
  3938. fs->wflag = 1;
  3939. res = sync_window(fs);
  3940. if (res != FR_OK) break;
  3941. mem_set(dir, 0, SS(fs));
  3942. }
  3943. }
  3944. if (res == FR_OK) res = dir_register(&dj); /* Register the object to the directoy */
  3945. if (res == FR_OK) {
  3946. #if _FS_EXFAT
  3947. if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
  3948. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
  3949. st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
  3950. st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */
  3951. st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);
  3952. fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag (contiguous) */
  3953. fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
  3954. res = store_xdir(&dj);
  3955. } else
  3956. #endif
  3957. {
  3958. dir = dj.dir;
  3959. st_dword(dir + DIR_ModTime, tm); /* Created time */
  3960. st_clust(fs, dir, dcl); /* Table start cluster */
  3961. dir[DIR_Attr] = AM_DIR; /* Attribute */
  3962. fs->wflag = 1;
  3963. }
  3964. if (res == FR_OK) res = sync_fs(fs);
  3965. } else {
  3966. remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */
  3967. }
  3968. }
  3969. FREE_NAMBUF();
  3970. }
  3971. LEAVE_FF(fs, res);
  3972. }
  3973. /*-----------------------------------------------------------------------*/
  3974. /* Rename a File/Directory */
  3975. /*-----------------------------------------------------------------------*/
  3976. FRESULT f_rename (
  3977. const TCHAR* path_old, /* Pointer to the object name to be renamed */
  3978. const TCHAR* path_new /* Pointer to the new name */
  3979. )
  3980. {
  3981. FRESULT res;
  3982. DIR djo, djn;
  3983. FATFS *fs;
  3984. BYTE buf[_FS_EXFAT ? SZDIRE * 2 : 24], *dir;
  3985. DWORD dw;
  3986. DEF_NAMBUF
  3987. get_ldnumber(&path_new); /* Ignore drive number of new name */
  3988. res = find_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
  3989. if (res == FR_OK) {
  3990. djo.obj.fs = fs;
  3991. INIT_NAMBUF(fs);
  3992. res = follow_path(&djo, path_old); /* Check old object */
  3993. if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
  3994. #if _FS_LOCK != 0
  3995. if (res == FR_OK) res = chk_lock(&djo, 2);
  3996. #endif
  3997. if (res == FR_OK) { /* Object to be renamed is found */
  3998. #if _FS_EXFAT
  3999. if (fs->fs_type == FS_EXFAT) { /* At exFAT */
  4000. BYTE nf, nn;
  4001. WORD nh;
  4002. mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
  4003. mem_cpy(&djn, &djo, sizeof djo);
  4004. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4005. if (res == FR_OK) { /* Is new name already in use by any other object? */
  4006. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4007. }
  4008. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4009. res = dir_register(&djn); /* Register the new entry */
  4010. if (res == FR_OK) {
  4011. nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
  4012. nh = ld_word(fs->dirbuf + XDIR_NameHash);
  4013. mem_cpy(fs->dirbuf, buf, SZDIRE * 2);
  4014. fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
  4015. st_word(fs->dirbuf + XDIR_NameHash, nh);
  4016. /* Start of critical section where any interruption can cause a cross-link */
  4017. res = store_xdir(&djn);
  4018. }
  4019. }
  4020. } else
  4021. #endif
  4022. { /* At FAT12/FAT16/FAT32 */
  4023. mem_cpy(buf, djo.dir + DIR_Attr, 21); /* Save information about the object except name */
  4024. mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
  4025. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4026. if (res == FR_OK) { /* Is new name already in use by any other object? */
  4027. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4028. }
  4029. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4030. res = dir_register(&djn); /* Register the new entry */
  4031. if (res == FR_OK) {
  4032. dir = djn.dir; /* Copy information about object except name */
  4033. mem_cpy(dir + 13, buf + 2, 19);
  4034. dir[DIR_Attr] = buf[0] | AM_ARC;
  4035. fs->wflag = 1;
  4036. if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
  4037. dw = clust2sect(fs, ld_clust(fs, dir));
  4038. if (!dw) {
  4039. res = FR_INT_ERR;
  4040. } else {
  4041. /* Start of critical section where any interruption can cause a cross-link */
  4042. res = move_window(fs, dw);
  4043. dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
  4044. if (res == FR_OK && dir[1] == '.') {
  4045. st_clust(fs, dir, djn.obj.sclust);
  4046. fs->wflag = 1;
  4047. }
  4048. }
  4049. }
  4050. }
  4051. }
  4052. }
  4053. if (res == FR_OK) {
  4054. res = dir_remove(&djo); /* Remove old entry */
  4055. if (res == FR_OK) {
  4056. res = sync_fs(fs);
  4057. }
  4058. }
  4059. /* End of critical section */
  4060. }
  4061. FREE_NAMBUF();
  4062. }
  4063. LEAVE_FF(fs, res);
  4064. }
  4065. #endif /* !_FS_READONLY */
  4066. #endif /* _FS_MINIMIZE == 0 */
  4067. #endif /* _FS_MINIMIZE <= 1 */
  4068. #endif /* _FS_MINIMIZE <= 2 */
  4069. #if _USE_CHMOD && !_FS_READONLY
  4070. /*-----------------------------------------------------------------------*/
  4071. /* Change Attribute */
  4072. /*-----------------------------------------------------------------------*/
  4073. FRESULT f_chmod (
  4074. const TCHAR* path, /* Pointer to the file path */
  4075. BYTE attr, /* Attribute bits */
  4076. BYTE mask /* Attribute mask to change */
  4077. )
  4078. {
  4079. FRESULT res;
  4080. DIR dj;
  4081. FATFS *fs;
  4082. DEF_NAMBUF
  4083. res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4084. dj.obj.fs = fs;
  4085. if (res == FR_OK) {
  4086. INIT_NAMBUF(fs);
  4087. res = follow_path(&dj, path); /* Follow the file path */
  4088. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4089. if (res == FR_OK) {
  4090. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  4091. #if _FS_EXFAT
  4092. if (fs->fs_type == FS_EXFAT) {
  4093. fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4094. res = store_xdir(&dj);
  4095. } else
  4096. #endif
  4097. {
  4098. dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4099. fs->wflag = 1;
  4100. }
  4101. if (res == FR_OK) res = sync_fs(fs);
  4102. }
  4103. FREE_NAMBUF();
  4104. }
  4105. LEAVE_FF(fs, res);
  4106. }
  4107. /*-----------------------------------------------------------------------*/
  4108. /* Change Timestamp */
  4109. /*-----------------------------------------------------------------------*/
  4110. FRESULT f_utime (
  4111. const TCHAR* path, /* Pointer to the file/directory name */
  4112. const FILINFO* fno /* Pointer to the time stamp to be set */
  4113. )
  4114. {
  4115. FRESULT res;
  4116. DIR dj;
  4117. FATFS *fs;
  4118. DEF_NAMBUF
  4119. res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4120. dj.obj.fs = fs;
  4121. if (res == FR_OK) {
  4122. INIT_NAMBUF(fs);
  4123. res = follow_path(&dj, path); /* Follow the file path */
  4124. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4125. if (res == FR_OK) {
  4126. #if _FS_EXFAT
  4127. if (fs->fs_type == FS_EXFAT) {
  4128. st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4129. res = store_xdir(&dj);
  4130. } else
  4131. #endif
  4132. {
  4133. st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4134. fs->wflag = 1;
  4135. }
  4136. if (res == FR_OK) res = sync_fs(fs);
  4137. }
  4138. FREE_NAMBUF();
  4139. }
  4140. LEAVE_FF(fs, res);
  4141. }
  4142. #endif /* _USE_CHMOD && !_FS_READONLY */
  4143. #if _USE_LABEL
  4144. /*-----------------------------------------------------------------------*/
  4145. /* Get Volume Label */
  4146. /*-----------------------------------------------------------------------*/
  4147. FRESULT f_getlabel (
  4148. const TCHAR* path, /* Path name of the logical drive number */
  4149. TCHAR* label, /* Pointer to a buffer to return the volume label */
  4150. DWORD* vsn /* Pointer to a variable to return the volume serial number */
  4151. )
  4152. {
  4153. FRESULT res;
  4154. DIR dj;
  4155. FATFS *fs;
  4156. UINT si, di;
  4157. #if _LFN_UNICODE || _FS_EXFAT
  4158. WCHAR w;
  4159. #endif
  4160. /* Get logical drive */
  4161. res = find_volume(&path, &fs, 0);
  4162. /* Get volume label */
  4163. if (res == FR_OK && label) {
  4164. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4165. res = dir_sdi(&dj, 0);
  4166. if (res == FR_OK) {
  4167. res = dir_read(&dj, 1); /* Find a volume label entry */
  4168. if (res == FR_OK) {
  4169. #if _FS_EXFAT
  4170. if (fs->fs_type == FS_EXFAT) {
  4171. for (si = di = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
  4172. w = ld_word(dj.dir + XDIR_Label + si * 2);
  4173. #if _LFN_UNICODE
  4174. label[di++] = w;
  4175. #else
  4176. w = ff_convert(w, 0); /* Unicode -> OEM */
  4177. if (w == 0) w = '?'; /* Replace wrong character */
  4178. if (_DF1S && w >= 0x100) label[di++] = (char)(w >> 8);
  4179. label[di++] = (char)w;
  4180. #endif
  4181. }
  4182. label[di] = 0;
  4183. } else
  4184. #endif
  4185. {
  4186. si = di = 0; /* Extract volume label from AM_VOL entry with code comversion */
  4187. do {
  4188. #if _LFN_UNICODE
  4189. w = (si < 11) ? dj.dir[si++] : ' ';
  4190. if (IsDBCS1(w) && si < 11 && IsDBCS2(dj.dir[si])) {
  4191. w = w << 8 | dj.dir[si++];
  4192. }
  4193. label[di++] = ff_convert(w, 1); /* OEM -> Unicode */
  4194. #else
  4195. label[di++] = dj.dir[si++];
  4196. #endif
  4197. } while (di < 11);
  4198. do { /* Truncate trailing spaces */
  4199. label[di] = 0;
  4200. if (di == 0) break;
  4201. } while (label[--di] == ' ');
  4202. }
  4203. }
  4204. }
  4205. if (res == FR_NO_FILE) { /* No label entry and return nul string */
  4206. label[0] = 0;
  4207. res = FR_OK;
  4208. }
  4209. }
  4210. /* Get volume serial number */
  4211. if (res == FR_OK && vsn) {
  4212. res = move_window(fs, fs->volbase);
  4213. if (res == FR_OK) {
  4214. switch (fs->fs_type) {
  4215. case FS_EXFAT: di = BPB_VolIDEx; break;
  4216. case FS_FAT32: di = BS_VolID32; break;
  4217. default: di = BS_VolID;
  4218. }
  4219. *vsn = ld_dword(fs->win + di);
  4220. }
  4221. }
  4222. LEAVE_FF(fs, res);
  4223. }
  4224. #if !_FS_READONLY
  4225. /*-----------------------------------------------------------------------*/
  4226. /* Set Volume Label */
  4227. /*-----------------------------------------------------------------------*/
  4228. FRESULT f_setlabel (
  4229. const TCHAR* label /* Pointer to the volume label to set */
  4230. )
  4231. {
  4232. FRESULT res;
  4233. DIR dj;
  4234. FATFS *fs;
  4235. BYTE dirvn[22];
  4236. UINT i, j, slen;
  4237. WCHAR w;
  4238. static const char badchr[] = "\"*+,.:;<=>\?[]|\x7F";
  4239. /* Get logical drive */
  4240. res = find_volume(&label, &fs, FA_WRITE);
  4241. if (res != FR_OK) LEAVE_FF(fs, res);
  4242. dj.obj.fs = fs;
  4243. /* Get length of given volume label */
  4244. for (slen = 0; (UINT)label[slen] >= ' '; slen++) ; /* Get name length */
  4245. #if _FS_EXFAT
  4246. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  4247. for (i = j = 0; i < slen; ) { /* Create volume label in directory form */
  4248. w = label[i++];
  4249. #if !_LFN_UNICODE
  4250. if (IsDBCS1(w)) {
  4251. w = (i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  4252. }
  4253. w = ff_convert(w, 1);
  4254. #endif
  4255. if (w == 0 || chk_chr(badchr, w) || j == 22) { /* Check validity check validity of the volume label */
  4256. LEAVE_FF(fs, FR_INVALID_NAME);
  4257. }
  4258. st_word(dirvn + j, w); j += 2;
  4259. }
  4260. slen = j;
  4261. } else
  4262. #endif
  4263. { /* On the FAT12/16/32 volume */
  4264. for ( ; slen && label[slen - 1] == ' '; slen--) ; /* Remove trailing spaces */
  4265. if (slen) { /* Is there a volume label to be set? */
  4266. dirvn[0] = 0; i = j = 0; /* Create volume label in directory form */
  4267. do {
  4268. #if _LFN_UNICODE
  4269. w = ff_convert(ff_wtoupper(label[i++]), 0);
  4270. #else
  4271. w = (BYTE)label[i++];
  4272. if (IsDBCS1(w)) {
  4273. w = (j < 10 && i < slen && IsDBCS2(label[i])) ? w << 8 | (BYTE)label[i++] : 0;
  4274. }
  4275. #if _USE_LFN != 0
  4276. w = ff_convert(ff_wtoupper(ff_convert(w, 1)), 0);
  4277. #else
  4278. if (IsLower(w)) w -= 0x20; /* To upper ASCII characters */
  4279. #ifdef _EXCVT
  4280. if (w >= 0x80) w = ExCvt[w - 0x80]; /* To upper extended characters (SBCS cfg) */
  4281. #else
  4282. if (!_DF1S && w >= 0x80) w = 0; /* Reject extended characters (ASCII cfg) */
  4283. #endif
  4284. #endif
  4285. #endif
  4286. if (w == 0 || chk_chr(badchr, w) || j >= (UINT)((w >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
  4287. LEAVE_FF(fs, FR_INVALID_NAME);
  4288. }
  4289. if (w >= 0x100) dirvn[j++] = (BYTE)(w >> 8);
  4290. dirvn[j++] = (BYTE)w;
  4291. } while (i < slen);
  4292. while (j < 11) dirvn[j++] = ' '; /* Fill remaining name field */
  4293. if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
  4294. }
  4295. }
  4296. /* Set volume label */
  4297. dj.obj.sclust = 0; /* Open root directory */
  4298. res = dir_sdi(&dj, 0);
  4299. if (res == FR_OK) {
  4300. res = dir_read(&dj, 1); /* Get volume label entry */
  4301. if (res == FR_OK) {
  4302. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4303. dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2); /* Change the volume label */
  4304. mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
  4305. } else {
  4306. if (slen) {
  4307. mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */
  4308. } else {
  4309. dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
  4310. }
  4311. }
  4312. fs->wflag = 1;
  4313. res = sync_fs(fs);
  4314. } else { /* No volume label entry is found or error */
  4315. if (res == FR_NO_FILE) {
  4316. res = FR_OK;
  4317. if (slen) { /* Create a volume label entry */
  4318. res = dir_alloc(&dj, 1); /* Allocate an entry */
  4319. if (res == FR_OK) {
  4320. mem_set(dj.dir, 0, SZDIRE); /* Clear the entry */
  4321. if (_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4322. dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */
  4323. dj.dir[XDIR_NumLabel] = (BYTE)(slen / 2);
  4324. mem_cpy(dj.dir + XDIR_Label, dirvn, slen);
  4325. } else {
  4326. dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
  4327. mem_cpy(dj.dir, dirvn, 11);
  4328. }
  4329. fs->wflag = 1;
  4330. res = sync_fs(fs);
  4331. }
  4332. }
  4333. }
  4334. }
  4335. }
  4336. LEAVE_FF(fs, res);
  4337. }
  4338. #endif /* !_FS_READONLY */
  4339. #endif /* _USE_LABEL */
  4340. #if _USE_EXPAND && !_FS_READONLY
  4341. /*-----------------------------------------------------------------------*/
  4342. /* Allocate a Contiguous Blocks to the File */
  4343. /*-----------------------------------------------------------------------*/
  4344. FRESULT f_expand (
  4345. FIL* fp, /* Pointer to the file object */
  4346. FSIZE_t fsz, /* File size to be expanded to */
  4347. BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
  4348. )
  4349. {
  4350. FRESULT res;
  4351. FATFS *fs;
  4352. DWORD n, clst, stcl, scl, ncl, tcl, lclst;
  4353. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4354. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4355. if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
  4356. #if _FS_EXFAT
  4357. if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
  4358. #endif
  4359. n = (DWORD)fs->csize * SS(fs); /* Cluster size */
  4360. tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
  4361. stcl = fs->last_clst; lclst = 0;
  4362. if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
  4363. #if _FS_EXFAT
  4364. if (fs->fs_type == FS_EXFAT) {
  4365. scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
  4366. if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
  4367. if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4368. if (res == FR_OK) {
  4369. if (opt) {
  4370. res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
  4371. lclst = scl + tcl - 1;
  4372. } else {
  4373. lclst = scl - 1;
  4374. }
  4375. }
  4376. } else
  4377. #endif
  4378. {
  4379. scl = clst = stcl; ncl = 0;
  4380. for (;;) { /* Find a contiguous cluster block */
  4381. n = get_fat(&fp->obj, clst);
  4382. if (++clst >= fs->n_fatent) clst = 2;
  4383. if (n == 1) { res = FR_INT_ERR; break; }
  4384. if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  4385. if (n == 0) { /* Is it a free cluster? */
  4386. if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
  4387. } else {
  4388. scl = clst; ncl = 0; /* Not a free cluster */
  4389. }
  4390. if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
  4391. }
  4392. if (res == FR_OK) {
  4393. if (opt) {
  4394. for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
  4395. res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
  4396. if (res != FR_OK) break;
  4397. lclst = clst;
  4398. }
  4399. } else {
  4400. lclst = scl - 1;
  4401. }
  4402. }
  4403. }
  4404. if (res == FR_OK) {
  4405. fs->last_clst = lclst; /* Set suggested start cluster to start next */
  4406. if (opt) {
  4407. fp->obj.sclust = scl; /* Update object allocation information */
  4408. fp->obj.objsize = fsz;
  4409. if (_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
  4410. fp->flag |= FA_MODIFIED;
  4411. if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
  4412. fs->free_clst -= tcl;
  4413. fs->fsi_flag |= 1;
  4414. }
  4415. }
  4416. }
  4417. LEAVE_FF(fs, res);
  4418. }
  4419. #endif /* _USE_EXPAND && !_FS_READONLY */
  4420. #if _USE_FORWARD
  4421. /*-----------------------------------------------------------------------*/
  4422. /* Forward data to the stream directly */
  4423. /*-----------------------------------------------------------------------*/
  4424. FRESULT f_forward (
  4425. FIL* fp, /* Pointer to the file object */
  4426. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  4427. UINT btf, /* Number of bytes to forward */
  4428. UINT* bf /* Pointer to number of bytes forwarded */
  4429. )
  4430. {
  4431. FRESULT res;
  4432. FATFS *fs;
  4433. DWORD clst, sect;
  4434. FSIZE_t remain;
  4435. UINT rcnt, csect;
  4436. BYTE *dbuf;
  4437. *bf = 0; /* Clear transfer byte counter */
  4438. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4439. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4440. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  4441. remain = fp->obj.objsize - fp->fptr;
  4442. if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
  4443. for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */
  4444. fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {
  4445. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  4446. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  4447. if (csect == 0) { /* On the cluster boundary? */
  4448. clst = (fp->fptr == 0) ? /* On the top of the file? */
  4449. fp->obj.sclust : get_fat(&fp->obj, fp->clust);
  4450. if (clst <= 1) ABORT(fs, FR_INT_ERR);
  4451. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  4452. fp->clust = clst; /* Update current cluster */
  4453. }
  4454. }
  4455. sect = clust2sect(fs, fp->clust); /* Get current data sector */
  4456. if (!sect) ABORT(fs, FR_INT_ERR);
  4457. sect += csect;
  4458. #if _FS_TINY
  4459. if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
  4460. dbuf = fs->win;
  4461. #else
  4462. if (fp->sect != sect) { /* Fill sector cache with file data */
  4463. #if !_FS_READONLY
  4464. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  4465. if (disk_write(fs->drv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4466. fp->flag &= (BYTE)~FA_DIRTY;
  4467. }
  4468. #endif
  4469. if (disk_read(fs->drv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4470. }
  4471. dbuf = fp->buf;
  4472. #endif
  4473. fp->sect = sect;
  4474. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */
  4475. if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
  4476. rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
  4477. if (!rcnt) ABORT(fs, FR_INT_ERR);
  4478. }
  4479. LEAVE_FF(fs, FR_OK);
  4480. }
  4481. #endif /* _USE_FORWARD */
  4482. #if _USE_MKFS && !_FS_READONLY
  4483. /*-----------------------------------------------------------------------*/
  4484. /* Create FAT file system on the logical drive */
  4485. /*-----------------------------------------------------------------------*/
  4486. FRESULT f_mkfs (
  4487. const TCHAR* path, /* Logical drive number */
  4488. BYTE opt, /* Format option */
  4489. DWORD au, /* Size of allocation unit [byte] */
  4490. void* work, /* Pointer to working buffer */
  4491. UINT len /* Size of working buffer */
  4492. )
  4493. {
  4494. const UINT n_fats = 1; /* Number of FATs for FAT12/16/32 volume (1 or 2) */
  4495. const UINT n_rootdir = 512; /* Number of root directory entries for FAT12/16 volume */
  4496. static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT12/16 volume (4Ks unit) */
  4497. static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
  4498. BYTE fmt, sys, *buf, *pte, pdrv, part;
  4499. WORD ss;
  4500. DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;
  4501. DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */
  4502. DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */
  4503. UINT i;
  4504. int vol;
  4505. DSTATUS stat;
  4506. #if _USE_TRIM || _FS_EXFAT
  4507. DWORD tbl[3];
  4508. #endif
  4509. /* Check mounted drive and clear work area */
  4510. vol = get_ldnumber(&path); /* Get target logical drive */
  4511. if (vol < 0) return FR_INVALID_DRIVE;
  4512. if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear mounted volume */
  4513. pdrv = LD2PD(vol); /* Physical drive */
  4514. part = LD2PT(vol); /* Partition (0:create as new, 1-4:get from partition table) */
  4515. /* Check physical drive status */
  4516. stat = disk_initialize(pdrv);
  4517. if (stat & STA_NOINIT) return FR_NOT_READY;
  4518. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  4519. if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK || !sz_blk || sz_blk > 32768 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Erase block to align data area */
  4520. #if _MAX_SS != _MIN_SS /* Get sector size of the medium */
  4521. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
  4522. if (ss > _MAX_SS || ss < _MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  4523. #else
  4524. ss = _MAX_SS;
  4525. #endif
  4526. if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */
  4527. au /= ss; /* Cluster size in unit of sector */
  4528. /* Get working buffer */
  4529. buf = (BYTE*)work; /* Working buffer */
  4530. sz_buf = len / ss; /* Size of working buffer (sector) */
  4531. szb_buf = sz_buf * ss; /* Size of working buffer (byte) */
  4532. if (!szb_buf) return FR_MKFS_ABORTED;
  4533. /* Determine where the volume to be located (b_vol, sz_vol) */
  4534. if (_MULTI_PARTITION && part != 0) {
  4535. /* Get partition information from partition table in the MBR */
  4536. if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Load MBR */
  4537. if (ld_word(buf + BS_55AA) != 0xAA55) return FR_MKFS_ABORTED; /* Check if MBR is valid */
  4538. pte = buf + (MBR_Table + (part - 1) * SZ_PTE);
  4539. if (!pte[PTE_System]) return FR_MKFS_ABORTED; /* No partition? */
  4540. b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
  4541. sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
  4542. } else {
  4543. /* Create a single-partition in this function */
  4544. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) return FR_DISK_ERR;
  4545. b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */
  4546. if (sz_vol < b_vol) return FR_MKFS_ABORTED;
  4547. sz_vol -= b_vol; /* Volume size */
  4548. }
  4549. if (sz_vol < 128) return FR_MKFS_ABORTED; /* Check if volume size is >=128s */
  4550. /* Pre-determine the FAT type */
  4551. do {
  4552. if (_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */
  4553. if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */
  4554. fmt = FS_EXFAT; break;
  4555. }
  4556. }
  4557. if (au > 128) return FR_INVALID_PARAMETER; /* Too large au for FAT/FAT32 */
  4558. if (opt & FM_FAT32) { /* FAT32 possible? */
  4559. if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */
  4560. fmt = FS_FAT32; break;
  4561. }
  4562. }
  4563. if (!(opt & FM_FAT)) return FR_INVALID_PARAMETER; /* no-FAT? */
  4564. fmt = FS_FAT16;
  4565. } while (0);
  4566. #if _FS_EXFAT
  4567. if (fmt == FS_EXFAT) { /* Create an exFAT volume */
  4568. DWORD szb_bit, szb_case, sum, nb, cl;
  4569. WCHAR ch, si;
  4570. UINT j, st;
  4571. BYTE b;
  4572. if (sz_vol < 0x1000) return FR_MKFS_ABORTED; /* Too small volume? */
  4573. #if _USE_TRIM
  4574. tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
  4575. disk_ioctl(pdrv, CTRL_TRIM, tbl);
  4576. #endif
  4577. /* Determine FAT location, data location and number of clusters */
  4578. if (!au) { /* au auto-selection */
  4579. au = 8;
  4580. if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */
  4581. if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */
  4582. }
  4583. b_fat = b_vol + 32; /* FAT start at offset 32 */
  4584. sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
  4585. b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */
  4586. if (b_data >= sz_vol / 2) return FR_MKFS_ABORTED; /* Too small volume? */
  4587. n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */
  4588. if (n_clst <16) return FR_MKFS_ABORTED; /* Too few clusters? */
  4589. if (n_clst > MAX_EXFAT) return FR_MKFS_ABORTED; /* Too many clusters? */
  4590. szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
  4591. tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */
  4592. /* Create a compressed up-case table */
  4593. sect = b_data + au * tbl[0]; /* Table start sector */
  4594. sum = 0; /* Table checksum to be stored in the 82 entry */
  4595. st = si = i = j = szb_case = 0;
  4596. do {
  4597. switch (st) {
  4598. case 0:
  4599. ch = ff_wtoupper(si); /* Get an up-case char */
  4600. if (ch != si) {
  4601. si++; break; /* Store the up-case char if exist */
  4602. }
  4603. for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
  4604. if (j >= 128) {
  4605. ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */
  4606. }
  4607. st = 1; /* Do not compress short run */
  4608. /* continue */
  4609. case 1:
  4610. ch = si++; /* Fill the short run */
  4611. if (--j == 0) st = 0;
  4612. break;
  4613. default:
  4614. ch = (WCHAR)j; si += j; /* Number of chars to skip */
  4615. st = 0;
  4616. }
  4617. sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
  4618. sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
  4619. i += 2; szb_case += 2;
  4620. if (!si || i == szb_buf) { /* Write buffered data when buffer full or end of process */
  4621. n = (i + ss - 1) / ss;
  4622. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4623. sect += n; i = 0;
  4624. }
  4625. } while (si);
  4626. tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */
  4627. tbl[2] = 1; /* Number of root dir clusters */
  4628. /* Initialize the allocation bitmap */
  4629. sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */
  4630. nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */
  4631. do {
  4632. mem_set(buf, 0, szb_buf);
  4633. for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;
  4634. for (b = 1; nb && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;
  4635. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  4636. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4637. sect += n; nsect -= n;
  4638. } while (nsect);
  4639. /* Initialize the FAT */
  4640. sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
  4641. j = nb = cl = 0;
  4642. do {
  4643. mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */
  4644. if (cl == 0) { /* Set entry 0 and 1 */
  4645. st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;
  4646. st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;
  4647. }
  4648. do { /* Create chains of bitmap, up-case and root dir */
  4649. while (nb && i < szb_buf) { /* Create a chain */
  4650. st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);
  4651. i += 4; cl++; nb--;
  4652. }
  4653. if (!nb && j < 3) nb = tbl[j++]; /* Next chain */
  4654. } while (nb && i < szb_buf);
  4655. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  4656. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4657. sect += n; nsect -= n;
  4658. } while (nsect);
  4659. /* Initialize the root directory */
  4660. mem_set(buf, 0, szb_buf);
  4661. buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */
  4662. buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */
  4663. st_dword(buf + SZDIRE * 1 + 20, 2);
  4664. st_dword(buf + SZDIRE * 1 + 24, szb_bit);
  4665. buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */
  4666. st_dword(buf + SZDIRE * 2 + 4, sum);
  4667. st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]);
  4668. st_dword(buf + SZDIRE * 2 + 24, szb_case);
  4669. sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */
  4670. do { /* Fill root directory sectors */
  4671. n = (nsect > sz_buf) ? sz_buf : nsect;
  4672. if (disk_write(pdrv, buf, sect, n) != RES_OK) return FR_DISK_ERR;
  4673. mem_set(buf, 0, ss);
  4674. sect += n; nsect -= n;
  4675. } while (nsect);
  4676. /* Create two set of the exFAT VBR blocks */
  4677. sect = b_vol;
  4678. for (n = 0; n < 2; n++) {
  4679. /* Main record (+0) */
  4680. mem_set(buf, 0, ss);
  4681. mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
  4682. st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
  4683. st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
  4684. st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */
  4685. st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
  4686. st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */
  4687. st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
  4688. st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */
  4689. st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */
  4690. st_word(buf + BPB_FSVerEx, 0x100); /* File system version (1.00) */
  4691. for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
  4692. for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
  4693. buf[BPB_NumFATsEx] = 1; /* Number of FATs */
  4694. buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
  4695. st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
  4696. st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
  4697. for (i = sum = 0; i < ss; i++) { /* VBR checksum */
  4698. if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
  4699. }
  4700. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4701. /* Extended bootstrap record (+1..+8) */
  4702. mem_set(buf, 0, ss);
  4703. st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
  4704. for (j = 1; j < 9; j++) {
  4705. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  4706. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4707. }
  4708. /* OEM/Reserved record (+9..+10) */
  4709. mem_set(buf, 0, ss);
  4710. for ( ; j < 11; j++) {
  4711. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  4712. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4713. }
  4714. /* Sum record (+11) */
  4715. for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
  4716. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) return FR_DISK_ERR;
  4717. }
  4718. } else
  4719. #endif /* _FS_EXFAT */
  4720. { /* Create an FAT12/16/32 volume */
  4721. do {
  4722. pau = au;
  4723. /* Pre-determine number of clusters and FAT sub-type */
  4724. if (fmt == FS_FAT32) { /* FAT32 volume */
  4725. if (!pau) { /* au auto-selection */
  4726. n = sz_vol / 0x20000; /* Volume size in unit of 128KS */
  4727. for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
  4728. }
  4729. n_clst = sz_vol / pau; /* Number of clusters */
  4730. sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
  4731. sz_rsv = 32; /* Number of reserved sectors */
  4732. sz_dir = 0; /* No static directory */
  4733. if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) return FR_MKFS_ABORTED;
  4734. } else { /* FAT12/16 volume */
  4735. if (!pau) { /* au auto-selection */
  4736. n = sz_vol / 0x1000; /* Volume size in unit of 4KS */
  4737. for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
  4738. }
  4739. n_clst = sz_vol / pau;
  4740. if (n_clst > MAX_FAT12) {
  4741. n = n_clst * 2 + 4; /* FAT size [byte] */
  4742. } else {
  4743. fmt = FS_FAT12;
  4744. n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
  4745. }
  4746. sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
  4747. sz_rsv = 1; /* Number of reserved sectors */
  4748. sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */
  4749. }
  4750. b_fat = b_vol + sz_rsv; /* FAT base */
  4751. b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */
  4752. /* Align data base to erase block boundary (for flash memory media) */
  4753. n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */
  4754. if (fmt == FS_FAT32) { /* FAT32: Move FAT base */
  4755. sz_rsv += n; b_fat += n;
  4756. } else { /* FAT12/16: Expand FAT size */
  4757. sz_fat += n / n_fats;
  4758. }
  4759. /* Determine number of clusters and final check of validity of the FAT sub-type */
  4760. if (sz_vol < b_data + pau * 16 - b_vol) return FR_MKFS_ABORTED; /* Too small volume */
  4761. n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;
  4762. if (fmt == FS_FAT32) {
  4763. if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */
  4764. if (!au && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
  4765. return FR_MKFS_ABORTED;
  4766. }
  4767. }
  4768. if (fmt == FS_FAT16) {
  4769. if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
  4770. if (!au && (pau * 2) <= 64) {
  4771. au = pau * 2; continue; /* Adjust cluster size and retry */
  4772. }
  4773. if ((opt & FM_FAT32)) {
  4774. fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */
  4775. }
  4776. if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  4777. return FR_MKFS_ABORTED;
  4778. }
  4779. if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
  4780. if (!au && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  4781. return FR_MKFS_ABORTED;
  4782. }
  4783. }
  4784. if (fmt == FS_FAT12 && n_clst > MAX_FAT12) return FR_MKFS_ABORTED; /* Too many clusters for FAT12 */
  4785. /* Ok, it is the valid cluster configuration */
  4786. break;
  4787. } while (1);
  4788. #if _USE_TRIM
  4789. tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */
  4790. disk_ioctl(pdrv, CTRL_TRIM, tbl);
  4791. #endif
  4792. /* Create FAT VBR */
  4793. mem_set(buf, 0, ss);
  4794. mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */
  4795. st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
  4796. buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
  4797. st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
  4798. buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */
  4799. st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */
  4800. if (sz_vol < 0x10000) {
  4801. st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
  4802. } else {
  4803. st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */
  4804. }
  4805. buf[BPB_Media] = 0xF8; /* Media descriptor byte */
  4806. st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
  4807. st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
  4808. st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */
  4809. if (fmt == FS_FAT32) {
  4810. st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */
  4811. st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
  4812. st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
  4813. st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
  4814. st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
  4815. buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
  4816. buf[BS_BootSig32] = 0x29; /* Extended boot signature */
  4817. mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  4818. } else {
  4819. st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */
  4820. st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
  4821. buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
  4822. buf[BS_BootSig] = 0x29; /* Extended boot signature */
  4823. mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  4824. }
  4825. st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
  4826. if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the VBR sector */
  4827. /* Create FSINFO record if needed */
  4828. if (fmt == FS_FAT32) {
  4829. disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
  4830. mem_set(buf, 0, ss);
  4831. st_dword(buf + FSI_LeadSig, 0x41615252);
  4832. st_dword(buf + FSI_StrucSig, 0x61417272);
  4833. st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  4834. st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
  4835. st_word(buf + BS_55AA, 0xAA55);
  4836. disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
  4837. disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
  4838. }
  4839. /* Initialize FAT area */
  4840. mem_set(buf, 0, (UINT)szb_buf);
  4841. sect = b_fat; /* FAT start sector */
  4842. for (i = 0; i < n_fats; i++) { /* Initialize FATs each */
  4843. if (fmt == FS_FAT32) {
  4844. st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */
  4845. st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */
  4846. st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */
  4847. } else {
  4848. st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */
  4849. }
  4850. nsect = sz_fat; /* Number of FAT sectors */
  4851. do { /* Fill FAT sectors */
  4852. n = (nsect > sz_buf) ? sz_buf : nsect;
  4853. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
  4854. mem_set(buf, 0, ss);
  4855. sect += n; nsect -= n;
  4856. } while (nsect);
  4857. }
  4858. /* Initialize root directory (fill with zero) */
  4859. nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
  4860. do {
  4861. n = (nsect > sz_buf) ? sz_buf : nsect;
  4862. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) return FR_DISK_ERR;
  4863. sect += n; nsect -= n;
  4864. } while (nsect);
  4865. }
  4866. /* Determine system ID in the partition table */
  4867. if (_FS_EXFAT && fmt == FS_EXFAT) {
  4868. sys = 0x07; /* HPFS/NTFS/exFAT */
  4869. } else {
  4870. if (fmt == FS_FAT32) {
  4871. sys = 0x0C; /* FAT32X */
  4872. } else {
  4873. if (sz_vol >= 0x10000) {
  4874. sys = 0x06; /* FAT12/16 (>=64KS) */
  4875. } else {
  4876. sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 (<64KS) : FAT12 (<64KS) */
  4877. }
  4878. }
  4879. }
  4880. if (_MULTI_PARTITION && part != 0) {
  4881. /* Update system ID in the partition table */
  4882. if (disk_read(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Read the MBR */
  4883. buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system type */
  4884. if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it back to the MBR */
  4885. } else {
  4886. if (!(opt & FM_SFD)) {
  4887. /* Create partition table in FDISK format */
  4888. mem_set(buf, 0, ss);
  4889. st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
  4890. pte = buf + MBR_Table; /* Create partition table for single partition in the drive */
  4891. pte[PTE_Boot] = 0; /* Boot indicator */
  4892. pte[PTE_StHead] = 1; /* Start head */
  4893. pte[PTE_StSec] = 1; /* Start sector */
  4894. pte[PTE_StCyl] = 0; /* Start cylinder */
  4895. pte[PTE_System] = sys; /* System type */
  4896. n = (b_vol + sz_vol) / (63 * 255); /* (End CHS is incorrect) */
  4897. pte[PTE_EdHead] = 254; /* End head */
  4898. pte[PTE_EdSec] = (BYTE)(n >> 2 | 63); /* End sector */
  4899. pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */
  4900. st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */
  4901. st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */
  4902. if (disk_write(pdrv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
  4903. }
  4904. }
  4905. if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) return FR_DISK_ERR;
  4906. return FR_OK;
  4907. }
  4908. #if _MULTI_PARTITION
  4909. /*-----------------------------------------------------------------------*/
  4910. /* Create partition table on the physical drive */
  4911. /*-----------------------------------------------------------------------*/
  4912. FRESULT f_fdisk (
  4913. BYTE pdrv, /* Physical drive number */
  4914. const DWORD* szt, /* Pointer to the size table for each partitions */
  4915. void* work /* Pointer to the working buffer */
  4916. )
  4917. {
  4918. UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;
  4919. BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;
  4920. DSTATUS stat;
  4921. DWORD sz_disk, sz_part, s_part;
  4922. stat = disk_initialize(pdrv);
  4923. if (stat & STA_NOINIT) return FR_NOT_READY;
  4924. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  4925. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;
  4926. /* Determine the CHS without any care of the drive geometry */
  4927. for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;
  4928. if (n == 256) n--;
  4929. e_hd = n - 1;
  4930. sz_cyl = 63 * n;
  4931. tot_cyl = sz_disk / sz_cyl;
  4932. /* Create partition table */
  4933. mem_set(buf, 0, _MAX_SS);
  4934. p = buf + MBR_Table; b_cyl = 0;
  4935. for (i = 0; i < 4; i++, p += SZ_PTE) {
  4936. p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl;
  4937. if (!p_cyl) continue;
  4938. s_part = (DWORD)sz_cyl * b_cyl;
  4939. sz_part = (DWORD)sz_cyl * p_cyl;
  4940. if (i == 0) { /* Exclude first track of cylinder 0 */
  4941. s_hd = 1;
  4942. s_part += 63; sz_part -= 63;
  4943. } else {
  4944. s_hd = 0;
  4945. }
  4946. e_cyl = b_cyl + p_cyl - 1;
  4947. if (e_cyl >= tot_cyl) return FR_INVALID_PARAMETER;
  4948. /* Set partition table */
  4949. p[1] = s_hd; /* Start head */
  4950. p[2] = (BYTE)((b_cyl >> 2) + 1); /* Start sector */
  4951. p[3] = (BYTE)b_cyl; /* Start cylinder */
  4952. p[4] = 0x06; /* System type (temporary setting) */
  4953. p[5] = e_hd; /* End head */
  4954. p[6] = (BYTE)((e_cyl >> 2) + 63); /* End sector */
  4955. p[7] = (BYTE)e_cyl; /* End cylinder */
  4956. st_dword(p + 8, s_part); /* Start sector in LBA */
  4957. st_dword(p + 12, sz_part); /* Partition size */
  4958. /* Next partition */
  4959. b_cyl += p_cyl;
  4960. }
  4961. st_word(p, 0xAA55);
  4962. /* Write it to the MBR */
  4963. return (disk_write(pdrv, buf, 0, 1) != RES_OK || disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) ? FR_DISK_ERR : FR_OK;
  4964. }
  4965. #endif /* _MULTI_PARTITION */
  4966. #endif /* _USE_MKFS && !_FS_READONLY */
  4967. #if _USE_STRFUNC
  4968. /*-----------------------------------------------------------------------*/
  4969. /* Get a string from the file */
  4970. /*-----------------------------------------------------------------------*/
  4971. TCHAR* f_gets (
  4972. TCHAR* buff, /* Pointer to the string buffer to read */
  4973. int len, /* Size of string buffer (characters) */
  4974. FIL* fp /* Pointer to the file object */
  4975. )
  4976. {
  4977. int n = 0;
  4978. TCHAR c, *p = buff;
  4979. BYTE s[2];
  4980. UINT rc;
  4981. while (n < len - 1) { /* Read characters until buffer gets filled */
  4982. #if _LFN_UNICODE
  4983. #if _STRF_ENCODE == 3 /* Read a character in UTF-8 */
  4984. f_read(fp, s, 1, &rc);
  4985. if (rc != 1) break;
  4986. c = s[0];
  4987. if (c >= 0x80) {
  4988. if (c < 0xC0) continue; /* Skip stray trailer */
  4989. if (c < 0xE0) { /* Two-byte sequence */
  4990. f_read(fp, s, 1, &rc);
  4991. if (rc != 1) break;
  4992. c = (c & 0x1F) << 6 | (s[0] & 0x3F);
  4993. if (c < 0x80) c = '?';
  4994. } else {
  4995. if (c < 0xF0) { /* Three-byte sequence */
  4996. f_read(fp, s, 2, &rc);
  4997. if (rc != 2) break;
  4998. c = c << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F);
  4999. if (c < 0x800) c = '?';
  5000. } else { /* Reject four-byte sequence */
  5001. c = '?';
  5002. }
  5003. }
  5004. }
  5005. #elif _STRF_ENCODE == 2 /* Read a character in UTF-16BE */
  5006. f_read(fp, s, 2, &rc);
  5007. if (rc != 2) break;
  5008. c = s[1] + (s[0] << 8);
  5009. #elif _STRF_ENCODE == 1 /* Read a character in UTF-16LE */
  5010. f_read(fp, s, 2, &rc);
  5011. if (rc != 2) break;
  5012. c = s[0] + (s[1] << 8);
  5013. #else /* Read a character in ANSI/OEM */
  5014. f_read(fp, s, 1, &rc);
  5015. if (rc != 1) break;
  5016. c = s[0];
  5017. if (IsDBCS1(c)) {
  5018. f_read(fp, s, 1, &rc);
  5019. if (rc != 1) break;
  5020. c = (c << 8) + s[0];
  5021. }
  5022. c = ff_convert(c, 1); /* OEM -> Unicode */
  5023. if (!c) c = '?';
  5024. #endif
  5025. #else /* Read a character without conversion */
  5026. f_read(fp, s, 1, &rc);
  5027. if (rc != 1) break;
  5028. c = s[0];
  5029. #endif
  5030. if (_USE_STRFUNC == 2 && c == '\r') continue; /* Strip '\r' */
  5031. *p++ = c;
  5032. n++;
  5033. if (c == '\n') break; /* Break on EOL */
  5034. }
  5035. *p = 0;
  5036. return n ? buff : 0; /* When no data read (eof or error), return with error. */
  5037. }
  5038. #if !_FS_READONLY
  5039. #include <stdarg.h>
  5040. /*-----------------------------------------------------------------------*/
  5041. /* Put a character to the file */
  5042. /*-----------------------------------------------------------------------*/
  5043. typedef struct {
  5044. FIL *fp; /* Ptr to the writing file */
  5045. int idx, nchr; /* Write index of buf[] (-1:error), number of chars written */
  5046. BYTE buf[64]; /* Write buffer */
  5047. } putbuff;
  5048. static
  5049. void putc_bfd ( /* Buffered write with code conversion */
  5050. putbuff* pb,
  5051. TCHAR c
  5052. )
  5053. {
  5054. UINT bw;
  5055. int i;
  5056. if (_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
  5057. putc_bfd(pb, '\r');
  5058. }
  5059. i = pb->idx; /* Write index of pb->buf[] */
  5060. if (i < 0) return;
  5061. #if _LFN_UNICODE
  5062. #if _STRF_ENCODE == 3 /* Write a character in UTF-8 */
  5063. if (c < 0x80) { /* 7-bit */
  5064. pb->buf[i++] = (BYTE)c;
  5065. } else {
  5066. if (c < 0x800) { /* 11-bit */
  5067. pb->buf[i++] = (BYTE)(0xC0 | c >> 6);
  5068. } else { /* 16-bit */
  5069. pb->buf[i++] = (BYTE)(0xE0 | c >> 12);
  5070. pb->buf[i++] = (BYTE)(0x80 | (c >> 6 & 0x3F));
  5071. }
  5072. pb->buf[i++] = (BYTE)(0x80 | (c & 0x3F));
  5073. }
  5074. #elif _STRF_ENCODE == 2 /* Write a character in UTF-16BE */
  5075. pb->buf[i++] = (BYTE)(c >> 8);
  5076. pb->buf[i++] = (BYTE)c;
  5077. #elif _STRF_ENCODE == 1 /* Write a character in UTF-16LE */
  5078. pb->buf[i++] = (BYTE)c;
  5079. pb->buf[i++] = (BYTE)(c >> 8);
  5080. #else /* Write a character in ANSI/OEM */
  5081. c = ff_convert(c, 0); /* Unicode -> OEM */
  5082. if (!c) c = '?';
  5083. if (c >= 0x100)
  5084. pb->buf[i++] = (BYTE)(c >> 8);
  5085. pb->buf[i++] = (BYTE)c;
  5086. #endif
  5087. #else /* Write a character without conversion */
  5088. pb->buf[i++] = (BYTE)c;
  5089. #endif
  5090. if (i >= (int)(sizeof pb->buf) - 3) { /* Write buffered characters to the file */
  5091. f_write(pb->fp, pb->buf, (UINT)i, &bw);
  5092. i = (bw == (UINT)i) ? 0 : -1;
  5093. }
  5094. pb->idx = i;
  5095. pb->nchr++;
  5096. }
  5097. static
  5098. int putc_flush ( /* Flush left characters in the buffer */
  5099. putbuff* pb
  5100. )
  5101. {
  5102. UINT nw;
  5103. if ( pb->idx >= 0 /* Flush buffered characters to the file */
  5104. && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
  5105. && (UINT)pb->idx == nw) return pb->nchr;
  5106. return EOF;
  5107. }
  5108. static
  5109. void putc_init ( /* Initialize write buffer */
  5110. putbuff* pb,
  5111. FIL* fp
  5112. )
  5113. {
  5114. pb->fp = fp;
  5115. pb->nchr = pb->idx = 0;
  5116. }
  5117. int f_putc (
  5118. TCHAR c, /* A character to be output */
  5119. FIL* fp /* Pointer to the file object */
  5120. )
  5121. {
  5122. putbuff pb;
  5123. putc_init(&pb, fp);
  5124. putc_bfd(&pb, c); /* Put the character */
  5125. return putc_flush(&pb);
  5126. }
  5127. /*-----------------------------------------------------------------------*/
  5128. /* Put a string to the file */
  5129. /*-----------------------------------------------------------------------*/
  5130. int f_puts (
  5131. const TCHAR* str, /* Pointer to the string to be output */
  5132. FIL* fp /* Pointer to the file object */
  5133. )
  5134. {
  5135. putbuff pb;
  5136. putc_init(&pb, fp);
  5137. while (*str) putc_bfd(&pb, *str++); /* Put the string */
  5138. return putc_flush(&pb);
  5139. }
  5140. /*-----------------------------------------------------------------------*/
  5141. /* Put a formatted string to the file */
  5142. /*-----------------------------------------------------------------------*/
  5143. int f_printf (
  5144. FIL* fp, /* Pointer to the file object */
  5145. const TCHAR* fmt, /* Pointer to the format string */
  5146. ... /* Optional arguments... */
  5147. )
  5148. {
  5149. va_list arp;
  5150. putbuff pb;
  5151. BYTE f, r;
  5152. UINT i, j, w;
  5153. DWORD v;
  5154. TCHAR c, d, str[32], *p;
  5155. putc_init(&pb, fp);
  5156. va_start(arp, fmt);
  5157. for (;;) {
  5158. c = *fmt++;
  5159. if (c == 0) break; /* End of string */
  5160. if (c != '%') { /* Non escape character */
  5161. putc_bfd(&pb, c);
  5162. continue;
  5163. }
  5164. w = f = 0;
  5165. c = *fmt++;
  5166. if (c == '0') { /* Flag: '0' padding */
  5167. f = 1; c = *fmt++;
  5168. } else {
  5169. if (c == '-') { /* Flag: left justified */
  5170. f = 2; c = *fmt++;
  5171. }
  5172. }
  5173. while (IsDigit(c)) { /* Precision */
  5174. w = w * 10 + c - '0';
  5175. c = *fmt++;
  5176. }
  5177. if (c == 'l' || c == 'L') { /* Prefix: Size is long int */
  5178. f |= 4; c = *fmt++;
  5179. }
  5180. if (!c) break;
  5181. d = c;
  5182. if (IsLower(d)) d -= 0x20;
  5183. switch (d) { /* Type is... */
  5184. case 'S' : /* String */
  5185. p = va_arg(arp, TCHAR*);
  5186. for (j = 0; p[j]; j++) ;
  5187. if (!(f & 2)) {
  5188. while (j++ < w) putc_bfd(&pb, ' ');
  5189. }
  5190. while (*p) putc_bfd(&pb, *p++);
  5191. while (j++ < w) putc_bfd(&pb, ' ');
  5192. continue;
  5193. case 'C' : /* Character */
  5194. putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;
  5195. case 'B' : /* Binary */
  5196. r = 2; break;
  5197. case 'O' : /* Octal */
  5198. r = 8; break;
  5199. case 'D' : /* Signed decimal */
  5200. case 'U' : /* Unsigned decimal */
  5201. r = 10; break;
  5202. case 'X' : /* Hexdecimal */
  5203. r = 16; break;
  5204. default: /* Unknown type (pass-through) */
  5205. putc_bfd(&pb, c); continue;
  5206. }
  5207. /* Get an argument and put it in numeral */
  5208. v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));
  5209. if (d == 'D' && (v & 0x80000000)) {
  5210. v = 0 - v;
  5211. f |= 8;
  5212. }
  5213. i = 0;
  5214. do {
  5215. d = (TCHAR)(v % r); v /= r;
  5216. if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
  5217. str[i++] = d + '0';
  5218. } while (v && i < sizeof str / sizeof str[0]);
  5219. if (f & 8) str[i++] = '-';
  5220. j = i; d = (f & 1) ? '0' : ' ';
  5221. while (!(f & 2) && j++ < w) putc_bfd(&pb, d);
  5222. do putc_bfd(&pb, str[--i]); while (i);
  5223. while (j++ < w) putc_bfd(&pb, d);
  5224. }
  5225. va_end(arp);
  5226. return putc_flush(&pb);
  5227. }
  5228. #endif /* !_FS_READONLY */
  5229. #endif /* _USE_STRFUNC */
  5230. #include <rtthread.h>
  5231. #if _VOLUMES > 1
  5232. int elm_get_vol(FATFS *fat)
  5233. {
  5234. int vol;
  5235. for (vol = 0; vol < _VOLUMES; vol ++)
  5236. {
  5237. if (FatFs[vol] == fat) return vol;
  5238. }
  5239. return -1;
  5240. }
  5241. #endif