2
0

ff.c 244 KB

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