My Marlin configs for Fabrikator Mini and CTC i3 Pro B
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ff.c 208KB

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