2
0

ff.c 241 KB

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