ff.c 236 KB

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