lfs.c 186 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312
  1. /*
  2. * The little filesystem
  3. *
  4. * Copyright (c) 2022, The littlefs authors.
  5. * Copyright (c) 2017, Arm Limited. All rights reserved.
  6. * SPDX-License-Identifier: BSD-3-Clause
  7. */
  8. #include "lfs.h"
  9. #include "lfs_util.h"
  10. // some constants used throughout the code
  11. #define LFS_BLOCK_NULL ((lfs_block_t)-1)
  12. #define LFS_BLOCK_INLINE ((lfs_block_t)-2)
  13. enum {
  14. LFS_OK_RELOCATED = 1,
  15. LFS_OK_DROPPED = 2,
  16. LFS_OK_ORPHANED = 3,
  17. };
  18. enum {
  19. LFS_CMP_EQ = 0,
  20. LFS_CMP_LT = 1,
  21. LFS_CMP_GT = 2,
  22. };
  23. /// Caching block device operations ///
  24. static inline void lfs_cache_drop(lfs_t *lfs, lfs_cache_t *rcache) {
  25. // do not zero, cheaper if cache is readonly or only going to be
  26. // written with identical data (during relocates)
  27. (void)lfs;
  28. rcache->block = LFS_BLOCK_NULL;
  29. }
  30. static inline void lfs_cache_zero(lfs_t *lfs, lfs_cache_t *pcache) {
  31. // zero to avoid information leak
  32. memset(pcache->buffer, 0xff, lfs->cfg->cache_size);
  33. pcache->block = LFS_BLOCK_NULL;
  34. }
  35. static int lfs_bd_read(lfs_t *lfs,
  36. const lfs_cache_t *pcache, lfs_cache_t *rcache, lfs_size_t hint,
  37. lfs_block_t block, lfs_off_t off,
  38. void *buffer, lfs_size_t size) {
  39. uint8_t *data = buffer;
  40. if (off+size > lfs->cfg->block_size
  41. || (lfs->block_count && block >= lfs->block_count)) {
  42. return LFS_ERR_CORRUPT;
  43. }
  44. while (size > 0) {
  45. lfs_size_t diff = size;
  46. if (pcache && block == pcache->block &&
  47. off < pcache->off + pcache->size) {
  48. if (off >= pcache->off) {
  49. // is already in pcache?
  50. diff = lfs_min(diff, pcache->size - (off-pcache->off));
  51. memcpy(data, &pcache->buffer[off-pcache->off], diff);
  52. data += diff;
  53. off += diff;
  54. size -= diff;
  55. continue;
  56. }
  57. // pcache takes priority
  58. diff = lfs_min(diff, pcache->off-off);
  59. }
  60. if (block == rcache->block &&
  61. off < rcache->off + rcache->size) {
  62. if (off >= rcache->off) {
  63. // is already in rcache?
  64. diff = lfs_min(diff, rcache->size - (off-rcache->off));
  65. memcpy(data, &rcache->buffer[off-rcache->off], diff);
  66. data += diff;
  67. off += diff;
  68. size -= diff;
  69. continue;
  70. }
  71. // rcache takes priority
  72. diff = lfs_min(diff, rcache->off-off);
  73. }
  74. if (size >= hint && off % lfs->cfg->read_size == 0 &&
  75. size >= lfs->cfg->read_size) {
  76. // bypass cache?
  77. diff = lfs_aligndown(diff, lfs->cfg->read_size);
  78. int err = lfs->cfg->read(lfs->cfg, block, off, data, diff);
  79. if (err) {
  80. return err;
  81. }
  82. data += diff;
  83. off += diff;
  84. size -= diff;
  85. continue;
  86. }
  87. // load to cache, first condition can no longer fail
  88. LFS_ASSERT(!lfs->block_count || block < lfs->block_count);
  89. rcache->block = block;
  90. rcache->off = lfs_aligndown(off, lfs->cfg->read_size);
  91. rcache->size = lfs_min(
  92. lfs_min(
  93. lfs_alignup(off+hint, lfs->cfg->read_size),
  94. lfs->cfg->block_size)
  95. - rcache->off,
  96. lfs->cfg->cache_size);
  97. int err = lfs->cfg->read(lfs->cfg, rcache->block,
  98. rcache->off, rcache->buffer, rcache->size);
  99. LFS_ASSERT(err <= 0);
  100. if (err) {
  101. return err;
  102. }
  103. }
  104. return 0;
  105. }
  106. static int lfs_bd_cmp(lfs_t *lfs,
  107. const lfs_cache_t *pcache, lfs_cache_t *rcache, lfs_size_t hint,
  108. lfs_block_t block, lfs_off_t off,
  109. const void *buffer, lfs_size_t size) {
  110. const uint8_t *data = buffer;
  111. lfs_size_t diff = 0;
  112. for (lfs_off_t i = 0; i < size; i += diff) {
  113. uint8_t dat[8];
  114. diff = lfs_min(size-i, sizeof(dat));
  115. int err = lfs_bd_read(lfs,
  116. pcache, rcache, hint-i,
  117. block, off+i, &dat, diff);
  118. if (err) {
  119. return err;
  120. }
  121. int res = memcmp(dat, data + i, diff);
  122. if (res) {
  123. return res < 0 ? LFS_CMP_LT : LFS_CMP_GT;
  124. }
  125. }
  126. return LFS_CMP_EQ;
  127. }
  128. static int lfs_bd_crc(lfs_t *lfs,
  129. const lfs_cache_t *pcache, lfs_cache_t *rcache, lfs_size_t hint,
  130. lfs_block_t block, lfs_off_t off, lfs_size_t size, uint32_t *crc) {
  131. lfs_size_t diff = 0;
  132. for (lfs_off_t i = 0; i < size; i += diff) {
  133. uint8_t dat[8];
  134. diff = lfs_min(size-i, sizeof(dat));
  135. int err = lfs_bd_read(lfs,
  136. pcache, rcache, hint-i,
  137. block, off+i, &dat, diff);
  138. if (err) {
  139. return err;
  140. }
  141. *crc = lfs_crc(*crc, &dat, diff);
  142. }
  143. return 0;
  144. }
  145. #ifndef LFS_READONLY
  146. static int lfs_bd_flush(lfs_t *lfs,
  147. lfs_cache_t *pcache, lfs_cache_t *rcache, bool validate) {
  148. if (pcache->block != LFS_BLOCK_NULL && pcache->block != LFS_BLOCK_INLINE) {
  149. LFS_ASSERT(pcache->block < lfs->block_count);
  150. lfs_size_t diff = lfs_alignup(pcache->size, lfs->cfg->prog_size);
  151. int err = lfs->cfg->prog(lfs->cfg, pcache->block,
  152. pcache->off, pcache->buffer, diff);
  153. LFS_ASSERT(err <= 0);
  154. if (err) {
  155. return err;
  156. }
  157. if (validate) {
  158. // check data on disk
  159. lfs_cache_drop(lfs, rcache);
  160. int res = lfs_bd_cmp(lfs,
  161. NULL, rcache, diff,
  162. pcache->block, pcache->off, pcache->buffer, diff);
  163. if (res < 0) {
  164. return res;
  165. }
  166. if (res != LFS_CMP_EQ) {
  167. return LFS_ERR_CORRUPT;
  168. }
  169. }
  170. lfs_cache_zero(lfs, pcache);
  171. }
  172. return 0;
  173. }
  174. #endif
  175. #ifndef LFS_READONLY
  176. static int lfs_bd_sync(lfs_t *lfs,
  177. lfs_cache_t *pcache, lfs_cache_t *rcache, bool validate) {
  178. lfs_cache_drop(lfs, rcache);
  179. int err = lfs_bd_flush(lfs, pcache, rcache, validate);
  180. if (err) {
  181. return err;
  182. }
  183. err = lfs->cfg->sync(lfs->cfg);
  184. LFS_ASSERT(err <= 0);
  185. return err;
  186. }
  187. #endif
  188. #ifndef LFS_READONLY
  189. static int lfs_bd_prog(lfs_t *lfs,
  190. lfs_cache_t *pcache, lfs_cache_t *rcache, bool validate,
  191. lfs_block_t block, lfs_off_t off,
  192. const void *buffer, lfs_size_t size) {
  193. const uint8_t *data = buffer;
  194. LFS_ASSERT(block == LFS_BLOCK_INLINE || block < lfs->block_count);
  195. LFS_ASSERT(off + size <= lfs->cfg->block_size);
  196. while (size > 0) {
  197. if (block == pcache->block &&
  198. off >= pcache->off &&
  199. off < pcache->off + lfs->cfg->cache_size) {
  200. // already fits in pcache?
  201. lfs_size_t diff = lfs_min(size,
  202. lfs->cfg->cache_size - (off-pcache->off));
  203. memcpy(&pcache->buffer[off-pcache->off], data, diff);
  204. data += diff;
  205. off += diff;
  206. size -= diff;
  207. pcache->size = lfs_max(pcache->size, off - pcache->off);
  208. if (pcache->size == lfs->cfg->cache_size) {
  209. // eagerly flush out pcache if we fill up
  210. int err = lfs_bd_flush(lfs, pcache, rcache, validate);
  211. if (err) {
  212. return err;
  213. }
  214. }
  215. continue;
  216. }
  217. // pcache must have been flushed, either by programming and
  218. // entire block or manually flushing the pcache
  219. LFS_ASSERT(pcache->block == LFS_BLOCK_NULL);
  220. // prepare pcache, first condition can no longer fail
  221. pcache->block = block;
  222. pcache->off = lfs_aligndown(off, lfs->cfg->prog_size);
  223. pcache->size = 0;
  224. }
  225. return 0;
  226. }
  227. #endif
  228. #ifndef LFS_READONLY
  229. static int lfs_bd_erase(lfs_t *lfs, lfs_block_t block) {
  230. LFS_ASSERT(block < lfs->block_count);
  231. int err = lfs->cfg->erase(lfs->cfg, block);
  232. LFS_ASSERT(err <= 0);
  233. return err;
  234. }
  235. #endif
  236. /// Small type-level utilities ///
  237. // operations on block pairs
  238. static inline void lfs_pair_swap(lfs_block_t pair[2]) {
  239. lfs_block_t t = pair[0];
  240. pair[0] = pair[1];
  241. pair[1] = t;
  242. }
  243. static inline bool lfs_pair_isnull(const lfs_block_t pair[2]) {
  244. return pair[0] == LFS_BLOCK_NULL || pair[1] == LFS_BLOCK_NULL;
  245. }
  246. static inline int lfs_pair_cmp(
  247. const lfs_block_t paira[2],
  248. const lfs_block_t pairb[2]) {
  249. return !(paira[0] == pairb[0] || paira[1] == pairb[1] ||
  250. paira[0] == pairb[1] || paira[1] == pairb[0]);
  251. }
  252. static inline bool lfs_pair_issync(
  253. const lfs_block_t paira[2],
  254. const lfs_block_t pairb[2]) {
  255. return (paira[0] == pairb[0] && paira[1] == pairb[1]) ||
  256. (paira[0] == pairb[1] && paira[1] == pairb[0]);
  257. }
  258. static inline void lfs_pair_fromle32(lfs_block_t pair[2]) {
  259. pair[0] = lfs_fromle32(pair[0]);
  260. pair[1] = lfs_fromle32(pair[1]);
  261. }
  262. #ifndef LFS_READONLY
  263. static inline void lfs_pair_tole32(lfs_block_t pair[2]) {
  264. pair[0] = lfs_tole32(pair[0]);
  265. pair[1] = lfs_tole32(pair[1]);
  266. }
  267. #endif
  268. // operations on 32-bit entry tags
  269. typedef uint32_t lfs_tag_t;
  270. typedef int32_t lfs_stag_t;
  271. #define LFS_MKTAG(type, id, size) \
  272. (((lfs_tag_t)(type) << 20) | ((lfs_tag_t)(id) << 10) | (lfs_tag_t)(size))
  273. #define LFS_MKTAG_IF(cond, type, id, size) \
  274. ((cond) ? LFS_MKTAG(type, id, size) : LFS_MKTAG(LFS_FROM_NOOP, 0, 0))
  275. #define LFS_MKTAG_IF_ELSE(cond, type1, id1, size1, type2, id2, size2) \
  276. ((cond) ? LFS_MKTAG(type1, id1, size1) : LFS_MKTAG(type2, id2, size2))
  277. static inline bool lfs_tag_isvalid(lfs_tag_t tag) {
  278. return !(tag & 0x80000000);
  279. }
  280. static inline bool lfs_tag_isdelete(lfs_tag_t tag) {
  281. return ((int32_t)(tag << 22) >> 22) == -1;
  282. }
  283. static inline uint16_t lfs_tag_type1(lfs_tag_t tag) {
  284. return (tag & 0x70000000) >> 20;
  285. }
  286. static inline uint16_t lfs_tag_type2(lfs_tag_t tag) {
  287. return (tag & 0x78000000) >> 20;
  288. }
  289. static inline uint16_t lfs_tag_type3(lfs_tag_t tag) {
  290. return (tag & 0x7ff00000) >> 20;
  291. }
  292. static inline uint8_t lfs_tag_chunk(lfs_tag_t tag) {
  293. return (tag & 0x0ff00000) >> 20;
  294. }
  295. static inline int8_t lfs_tag_splice(lfs_tag_t tag) {
  296. return (int8_t)lfs_tag_chunk(tag);
  297. }
  298. static inline uint16_t lfs_tag_id(lfs_tag_t tag) {
  299. return (tag & 0x000ffc00) >> 10;
  300. }
  301. static inline lfs_size_t lfs_tag_size(lfs_tag_t tag) {
  302. return tag & 0x000003ff;
  303. }
  304. static inline lfs_size_t lfs_tag_dsize(lfs_tag_t tag) {
  305. return sizeof(tag) + lfs_tag_size(tag + lfs_tag_isdelete(tag));
  306. }
  307. // operations on attributes in attribute lists
  308. struct lfs_mattr {
  309. lfs_tag_t tag;
  310. const void *buffer;
  311. };
  312. struct lfs_diskoff {
  313. lfs_block_t block;
  314. lfs_off_t off;
  315. };
  316. #define LFS_MKATTRS(...) \
  317. (struct lfs_mattr[]){__VA_ARGS__}, \
  318. sizeof((struct lfs_mattr[]){__VA_ARGS__}) / sizeof(struct lfs_mattr)
  319. // operations on global state
  320. static inline void lfs_gstate_xor(lfs_gstate_t *a, const lfs_gstate_t *b) {
  321. for (int i = 0; i < 3; i++) {
  322. ((uint32_t*)a)[i] ^= ((const uint32_t*)b)[i];
  323. }
  324. }
  325. static inline bool lfs_gstate_iszero(const lfs_gstate_t *a) {
  326. for (int i = 0; i < 3; i++) {
  327. if (((uint32_t*)a)[i] != 0) {
  328. return false;
  329. }
  330. }
  331. return true;
  332. }
  333. #ifndef LFS_READONLY
  334. static inline bool lfs_gstate_hasorphans(const lfs_gstate_t *a) {
  335. return lfs_tag_size(a->tag);
  336. }
  337. static inline uint8_t lfs_gstate_getorphans(const lfs_gstate_t *a) {
  338. return lfs_tag_size(a->tag) & 0x1ff;
  339. }
  340. static inline bool lfs_gstate_hasmove(const lfs_gstate_t *a) {
  341. return lfs_tag_type1(a->tag);
  342. }
  343. #endif
  344. static inline bool lfs_gstate_needssuperblock(const lfs_gstate_t *a) {
  345. return lfs_tag_size(a->tag) >> 9;
  346. }
  347. static inline bool lfs_gstate_hasmovehere(const lfs_gstate_t *a,
  348. const lfs_block_t *pair) {
  349. return lfs_tag_type1(a->tag) && lfs_pair_cmp(a->pair, pair) == 0;
  350. }
  351. static inline void lfs_gstate_fromle32(lfs_gstate_t *a) {
  352. a->tag = lfs_fromle32(a->tag);
  353. a->pair[0] = lfs_fromle32(a->pair[0]);
  354. a->pair[1] = lfs_fromle32(a->pair[1]);
  355. }
  356. #ifndef LFS_READONLY
  357. static inline void lfs_gstate_tole32(lfs_gstate_t *a) {
  358. a->tag = lfs_tole32(a->tag);
  359. a->pair[0] = lfs_tole32(a->pair[0]);
  360. a->pair[1] = lfs_tole32(a->pair[1]);
  361. }
  362. #endif
  363. // operations on forward-CRCs used to track erased state
  364. struct lfs_fcrc {
  365. lfs_size_t size;
  366. uint32_t crc;
  367. };
  368. static void lfs_fcrc_fromle32(struct lfs_fcrc *fcrc) {
  369. fcrc->size = lfs_fromle32(fcrc->size);
  370. fcrc->crc = lfs_fromle32(fcrc->crc);
  371. }
  372. #ifndef LFS_READONLY
  373. static void lfs_fcrc_tole32(struct lfs_fcrc *fcrc) {
  374. fcrc->size = lfs_tole32(fcrc->size);
  375. fcrc->crc = lfs_tole32(fcrc->crc);
  376. }
  377. #endif
  378. // other endianness operations
  379. static void lfs_ctz_fromle32(struct lfs_ctz *ctz) {
  380. ctz->head = lfs_fromle32(ctz->head);
  381. ctz->size = lfs_fromle32(ctz->size);
  382. }
  383. #ifndef LFS_READONLY
  384. static void lfs_ctz_tole32(struct lfs_ctz *ctz) {
  385. ctz->head = lfs_tole32(ctz->head);
  386. ctz->size = lfs_tole32(ctz->size);
  387. }
  388. #endif
  389. static inline void lfs_superblock_fromle32(lfs_superblock_t *superblock) {
  390. superblock->version = lfs_fromle32(superblock->version);
  391. superblock->block_size = lfs_fromle32(superblock->block_size);
  392. superblock->block_count = lfs_fromle32(superblock->block_count);
  393. superblock->name_max = lfs_fromle32(superblock->name_max);
  394. superblock->file_max = lfs_fromle32(superblock->file_max);
  395. superblock->attr_max = lfs_fromle32(superblock->attr_max);
  396. }
  397. #ifndef LFS_READONLY
  398. static inline void lfs_superblock_tole32(lfs_superblock_t *superblock) {
  399. superblock->version = lfs_tole32(superblock->version);
  400. superblock->block_size = lfs_tole32(superblock->block_size);
  401. superblock->block_count = lfs_tole32(superblock->block_count);
  402. superblock->name_max = lfs_tole32(superblock->name_max);
  403. superblock->file_max = lfs_tole32(superblock->file_max);
  404. superblock->attr_max = lfs_tole32(superblock->attr_max);
  405. }
  406. #endif
  407. #ifndef LFS_NO_ASSERT
  408. static bool lfs_mlist_isopen(struct lfs_mlist *head,
  409. struct lfs_mlist *node) {
  410. for (struct lfs_mlist **p = &head; *p; p = &(*p)->next) {
  411. if (*p == (struct lfs_mlist*)node) {
  412. return true;
  413. }
  414. }
  415. return false;
  416. }
  417. #endif
  418. static void lfs_mlist_remove(lfs_t *lfs, struct lfs_mlist *mlist) {
  419. for (struct lfs_mlist **p = &lfs->mlist; *p; p = &(*p)->next) {
  420. if (*p == mlist) {
  421. *p = (*p)->next;
  422. break;
  423. }
  424. }
  425. }
  426. static void lfs_mlist_append(lfs_t *lfs, struct lfs_mlist *mlist) {
  427. mlist->next = lfs->mlist;
  428. lfs->mlist = mlist;
  429. }
  430. // some other filesystem operations
  431. static uint32_t lfs_fs_disk_version(lfs_t *lfs) {
  432. (void)lfs;
  433. #ifdef LFS_MULTIVERSION
  434. if (lfs->cfg->disk_version) {
  435. return lfs->cfg->disk_version;
  436. } else
  437. #endif
  438. {
  439. return LFS_DISK_VERSION;
  440. }
  441. }
  442. static uint16_t lfs_fs_disk_version_major(lfs_t *lfs) {
  443. return 0xffff & (lfs_fs_disk_version(lfs) >> 16);
  444. }
  445. static uint16_t lfs_fs_disk_version_minor(lfs_t *lfs) {
  446. return 0xffff & (lfs_fs_disk_version(lfs) >> 0);
  447. }
  448. /// Internal operations predeclared here ///
  449. #ifndef LFS_READONLY
  450. static int lfs_dir_commit(lfs_t *lfs, lfs_mdir_t *dir,
  451. const struct lfs_mattr *attrs, int attrcount);
  452. static int lfs_dir_compact(lfs_t *lfs,
  453. lfs_mdir_t *dir, const struct lfs_mattr *attrs, int attrcount,
  454. lfs_mdir_t *source, uint16_t begin, uint16_t end);
  455. static lfs_ssize_t lfs_file_flushedwrite(lfs_t *lfs, lfs_file_t *file,
  456. const void *buffer, lfs_size_t size);
  457. static lfs_ssize_t lfs_file_rawwrite(lfs_t *lfs, lfs_file_t *file,
  458. const void *buffer, lfs_size_t size);
  459. static int lfs_file_rawsync(lfs_t *lfs, lfs_file_t *file);
  460. static int lfs_file_outline(lfs_t *lfs, lfs_file_t *file);
  461. static int lfs_file_flush(lfs_t *lfs, lfs_file_t *file);
  462. static int lfs_fs_deorphan(lfs_t *lfs, bool powerloss);
  463. static int lfs_fs_preporphans(lfs_t *lfs, int8_t orphans);
  464. static void lfs_fs_prepmove(lfs_t *lfs,
  465. uint16_t id, const lfs_block_t pair[2]);
  466. static int lfs_fs_pred(lfs_t *lfs, const lfs_block_t dir[2],
  467. lfs_mdir_t *pdir);
  468. static lfs_stag_t lfs_fs_parent(lfs_t *lfs, const lfs_block_t dir[2],
  469. lfs_mdir_t *parent);
  470. static int lfs_fs_forceconsistency(lfs_t *lfs);
  471. #endif
  472. static void lfs_fs_prepsuperblock(lfs_t *lfs, bool needssuperblock);
  473. #ifdef LFS_MIGRATE
  474. static int lfs1_traverse(lfs_t *lfs,
  475. int (*cb)(void*, lfs_block_t), void *data);
  476. #endif
  477. static int lfs_dir_rawrewind(lfs_t *lfs, lfs_dir_t *dir);
  478. static lfs_ssize_t lfs_file_flushedread(lfs_t *lfs, lfs_file_t *file,
  479. void *buffer, lfs_size_t size);
  480. static lfs_ssize_t lfs_file_rawread(lfs_t *lfs, lfs_file_t *file,
  481. void *buffer, lfs_size_t size);
  482. static int lfs_file_rawclose(lfs_t *lfs, lfs_file_t *file);
  483. static lfs_soff_t lfs_file_rawsize(lfs_t *lfs, lfs_file_t *file);
  484. static lfs_ssize_t lfs_fs_rawsize(lfs_t *lfs);
  485. static int lfs_fs_rawtraverse(lfs_t *lfs,
  486. int (*cb)(void *data, lfs_block_t block), void *data,
  487. bool includeorphans);
  488. static int lfs_deinit(lfs_t *lfs);
  489. static int lfs_rawunmount(lfs_t *lfs);
  490. /// Block allocator ///
  491. #ifndef LFS_READONLY
  492. static int lfs_alloc_lookahead(void *p, lfs_block_t block) {
  493. lfs_t *lfs = (lfs_t*)p;
  494. lfs_block_t off = ((block - lfs->free.off)
  495. + lfs->block_count) % lfs->block_count;
  496. if (off < lfs->free.size) {
  497. lfs->free.buffer[off / 32] |= 1U << (off % 32);
  498. }
  499. return 0;
  500. }
  501. #endif
  502. // indicate allocated blocks have been committed into the filesystem, this
  503. // is to prevent blocks from being garbage collected in the middle of a
  504. // commit operation
  505. static void lfs_alloc_ack(lfs_t *lfs) {
  506. lfs->free.ack = lfs->block_count;
  507. }
  508. // drop the lookahead buffer, this is done during mounting and failed
  509. // traversals in order to avoid invalid lookahead state
  510. static void lfs_alloc_drop(lfs_t *lfs) {
  511. lfs->free.size = 0;
  512. lfs->free.i = 0;
  513. lfs_alloc_ack(lfs);
  514. }
  515. #ifndef LFS_READONLY
  516. static int lfs_alloc(lfs_t *lfs, lfs_block_t *block) {
  517. while (true) {
  518. while (lfs->free.i != lfs->free.size) {
  519. lfs_block_t off = lfs->free.i;
  520. lfs->free.i += 1;
  521. lfs->free.ack -= 1;
  522. if (!(lfs->free.buffer[off / 32] & (1U << (off % 32)))) {
  523. // found a free block
  524. *block = (lfs->free.off + off) % lfs->block_count;
  525. // eagerly find next off so an alloc ack can
  526. // discredit old lookahead blocks
  527. while (lfs->free.i != lfs->free.size &&
  528. (lfs->free.buffer[lfs->free.i / 32]
  529. & (1U << (lfs->free.i % 32)))) {
  530. lfs->free.i += 1;
  531. lfs->free.ack -= 1;
  532. }
  533. return 0;
  534. }
  535. }
  536. // check if we have looked at all blocks since last ack
  537. if (lfs->free.ack == 0) {
  538. LFS_ERROR("No more free space %"PRIu32,
  539. lfs->free.i + lfs->free.off);
  540. return LFS_ERR_NOSPC;
  541. }
  542. int err = lfs_find_free_blocks(lfs);
  543. if(err) {
  544. return err;
  545. }
  546. }
  547. }
  548. int lfs_find_free_blocks(lfs_t *lfs){
  549. // Move free offset at the first unused block (lfs->free.i)
  550. // lfs->free.i is equal lfs->free.size when all blocks are used
  551. lfs->free.off = (lfs->free.off + lfs->free.i)
  552. % lfs->block_count;
  553. lfs->free.size = lfs_min(8*lfs->cfg->lookahead_size, lfs->free.ack);
  554. lfs->free.i = 0;
  555. // find mask of free blocks from tree
  556. memset(lfs->free.buffer, 0, lfs->cfg->lookahead_size);
  557. int const err = lfs_fs_rawtraverse(lfs, lfs_alloc_lookahead, lfs, true);
  558. if (err) {
  559. lfs_alloc_drop(lfs);
  560. }
  561. return err;
  562. }
  563. #endif
  564. /// Metadata pair and directory operations ///
  565. static lfs_stag_t lfs_dir_getslice(lfs_t *lfs, const lfs_mdir_t *dir,
  566. lfs_tag_t gmask, lfs_tag_t gtag,
  567. lfs_off_t goff, void *gbuffer, lfs_size_t gsize) {
  568. lfs_off_t off = dir->off;
  569. lfs_tag_t ntag = dir->etag;
  570. lfs_stag_t gdiff = 0;
  571. if (lfs_gstate_hasmovehere(&lfs->gdisk, dir->pair) &&
  572. lfs_tag_id(gmask) != 0 &&
  573. lfs_tag_id(lfs->gdisk.tag) <= lfs_tag_id(gtag)) {
  574. // synthetic moves
  575. gdiff -= LFS_MKTAG(0, 1, 0);
  576. }
  577. // iterate over dir block backwards (for faster lookups)
  578. while (off >= sizeof(lfs_tag_t) + lfs_tag_dsize(ntag)) {
  579. off -= lfs_tag_dsize(ntag);
  580. lfs_tag_t tag = ntag;
  581. int err = lfs_bd_read(lfs,
  582. NULL, &lfs->rcache, sizeof(ntag),
  583. dir->pair[0], off, &ntag, sizeof(ntag));
  584. if (err) {
  585. return err;
  586. }
  587. ntag = (lfs_frombe32(ntag) ^ tag) & 0x7fffffff;
  588. if (lfs_tag_id(gmask) != 0 &&
  589. lfs_tag_type1(tag) == LFS_TYPE_SPLICE &&
  590. lfs_tag_id(tag) <= lfs_tag_id(gtag - gdiff)) {
  591. if (tag == (LFS_MKTAG(LFS_TYPE_CREATE, 0, 0) |
  592. (LFS_MKTAG(0, 0x3ff, 0) & (gtag - gdiff)))) {
  593. // found where we were created
  594. return LFS_ERR_NOENT;
  595. }
  596. // move around splices
  597. gdiff += LFS_MKTAG(0, lfs_tag_splice(tag), 0);
  598. }
  599. if ((gmask & tag) == (gmask & (gtag - gdiff))) {
  600. if (lfs_tag_isdelete(tag)) {
  601. return LFS_ERR_NOENT;
  602. }
  603. lfs_size_t diff = lfs_min(lfs_tag_size(tag), gsize);
  604. err = lfs_bd_read(lfs,
  605. NULL, &lfs->rcache, diff,
  606. dir->pair[0], off+sizeof(tag)+goff, gbuffer, diff);
  607. if (err) {
  608. return err;
  609. }
  610. memset((uint8_t*)gbuffer + diff, 0, gsize - diff);
  611. return tag + gdiff;
  612. }
  613. }
  614. return LFS_ERR_NOENT;
  615. }
  616. static lfs_stag_t lfs_dir_get(lfs_t *lfs, const lfs_mdir_t *dir,
  617. lfs_tag_t gmask, lfs_tag_t gtag, void *buffer) {
  618. return lfs_dir_getslice(lfs, dir,
  619. gmask, gtag,
  620. 0, buffer, lfs_tag_size(gtag));
  621. }
  622. static int lfs_dir_getread(lfs_t *lfs, const lfs_mdir_t *dir,
  623. const lfs_cache_t *pcache, lfs_cache_t *rcache, lfs_size_t hint,
  624. lfs_tag_t gmask, lfs_tag_t gtag,
  625. lfs_off_t off, void *buffer, lfs_size_t size) {
  626. uint8_t *data = buffer;
  627. if (off+size > lfs->cfg->block_size) {
  628. return LFS_ERR_CORRUPT;
  629. }
  630. while (size > 0) {
  631. lfs_size_t diff = size;
  632. if (pcache && pcache->block == LFS_BLOCK_INLINE &&
  633. off < pcache->off + pcache->size) {
  634. if (off >= pcache->off) {
  635. // is already in pcache?
  636. diff = lfs_min(diff, pcache->size - (off-pcache->off));
  637. memcpy(data, &pcache->buffer[off-pcache->off], diff);
  638. data += diff;
  639. off += diff;
  640. size -= diff;
  641. continue;
  642. }
  643. // pcache takes priority
  644. diff = lfs_min(diff, pcache->off-off);
  645. }
  646. if (rcache->block == LFS_BLOCK_INLINE &&
  647. off < rcache->off + rcache->size) {
  648. if (off >= rcache->off) {
  649. // is already in rcache?
  650. diff = lfs_min(diff, rcache->size - (off-rcache->off));
  651. memcpy(data, &rcache->buffer[off-rcache->off], diff);
  652. data += diff;
  653. off += diff;
  654. size -= diff;
  655. continue;
  656. }
  657. // rcache takes priority
  658. diff = lfs_min(diff, rcache->off-off);
  659. }
  660. // load to cache, first condition can no longer fail
  661. rcache->block = LFS_BLOCK_INLINE;
  662. rcache->off = lfs_aligndown(off, lfs->cfg->read_size);
  663. rcache->size = lfs_min(lfs_alignup(off+hint, lfs->cfg->read_size),
  664. lfs->cfg->cache_size);
  665. int err = lfs_dir_getslice(lfs, dir, gmask, gtag,
  666. rcache->off, rcache->buffer, rcache->size);
  667. if (err < 0) {
  668. return err;
  669. }
  670. }
  671. return 0;
  672. }
  673. #ifndef LFS_READONLY
  674. static int lfs_dir_traverse_filter(void *p,
  675. lfs_tag_t tag, const void *buffer) {
  676. lfs_tag_t *filtertag = p;
  677. (void)buffer;
  678. // which mask depends on unique bit in tag structure
  679. uint32_t mask = (tag & LFS_MKTAG(0x100, 0, 0))
  680. ? LFS_MKTAG(0x7ff, 0x3ff, 0)
  681. : LFS_MKTAG(0x700, 0x3ff, 0);
  682. // check for redundancy
  683. if ((mask & tag) == (mask & *filtertag) ||
  684. lfs_tag_isdelete(*filtertag) ||
  685. (LFS_MKTAG(0x7ff, 0x3ff, 0) & tag) == (
  686. LFS_MKTAG(LFS_TYPE_DELETE, 0, 0) |
  687. (LFS_MKTAG(0, 0x3ff, 0) & *filtertag))) {
  688. *filtertag = LFS_MKTAG(LFS_FROM_NOOP, 0, 0);
  689. return true;
  690. }
  691. // check if we need to adjust for created/deleted tags
  692. if (lfs_tag_type1(tag) == LFS_TYPE_SPLICE &&
  693. lfs_tag_id(tag) <= lfs_tag_id(*filtertag)) {
  694. *filtertag += LFS_MKTAG(0, lfs_tag_splice(tag), 0);
  695. }
  696. return false;
  697. }
  698. #endif
  699. #ifndef LFS_READONLY
  700. // maximum recursive depth of lfs_dir_traverse, the deepest call:
  701. //
  702. // traverse with commit
  703. // '-> traverse with move
  704. // '-> traverse with filter
  705. //
  706. #define LFS_DIR_TRAVERSE_DEPTH 3
  707. struct lfs_dir_traverse {
  708. const lfs_mdir_t *dir;
  709. lfs_off_t off;
  710. lfs_tag_t ptag;
  711. const struct lfs_mattr *attrs;
  712. int attrcount;
  713. lfs_tag_t tmask;
  714. lfs_tag_t ttag;
  715. uint16_t begin;
  716. uint16_t end;
  717. int16_t diff;
  718. int (*cb)(void *data, lfs_tag_t tag, const void *buffer);
  719. void *data;
  720. lfs_tag_t tag;
  721. const void *buffer;
  722. struct lfs_diskoff disk;
  723. };
  724. static int lfs_dir_traverse(lfs_t *lfs,
  725. const lfs_mdir_t *dir, lfs_off_t off, lfs_tag_t ptag,
  726. const struct lfs_mattr *attrs, int attrcount,
  727. lfs_tag_t tmask, lfs_tag_t ttag,
  728. uint16_t begin, uint16_t end, int16_t diff,
  729. int (*cb)(void *data, lfs_tag_t tag, const void *buffer), void *data) {
  730. // This function in inherently recursive, but bounded. To allow tool-based
  731. // analysis without unnecessary code-cost we use an explicit stack
  732. struct lfs_dir_traverse stack[LFS_DIR_TRAVERSE_DEPTH-1];
  733. unsigned sp = 0;
  734. int res;
  735. // iterate over directory and attrs
  736. lfs_tag_t tag;
  737. const void *buffer;
  738. struct lfs_diskoff disk = {0};
  739. while (true) {
  740. {
  741. if (off+lfs_tag_dsize(ptag) < dir->off) {
  742. off += lfs_tag_dsize(ptag);
  743. int err = lfs_bd_read(lfs,
  744. NULL, &lfs->rcache, sizeof(tag),
  745. dir->pair[0], off, &tag, sizeof(tag));
  746. if (err) {
  747. return err;
  748. }
  749. tag = (lfs_frombe32(tag) ^ ptag) | 0x80000000;
  750. disk.block = dir->pair[0];
  751. disk.off = off+sizeof(lfs_tag_t);
  752. buffer = &disk;
  753. ptag = tag;
  754. } else if (attrcount > 0) {
  755. tag = attrs[0].tag;
  756. buffer = attrs[0].buffer;
  757. attrs += 1;
  758. attrcount -= 1;
  759. } else {
  760. // finished traversal, pop from stack?
  761. res = 0;
  762. break;
  763. }
  764. // do we need to filter?
  765. lfs_tag_t mask = LFS_MKTAG(0x7ff, 0, 0);
  766. if ((mask & tmask & tag) != (mask & tmask & ttag)) {
  767. continue;
  768. }
  769. if (lfs_tag_id(tmask) != 0) {
  770. LFS_ASSERT(sp < LFS_DIR_TRAVERSE_DEPTH);
  771. // recurse, scan for duplicates, and update tag based on
  772. // creates/deletes
  773. stack[sp] = (struct lfs_dir_traverse){
  774. .dir = dir,
  775. .off = off,
  776. .ptag = ptag,
  777. .attrs = attrs,
  778. .attrcount = attrcount,
  779. .tmask = tmask,
  780. .ttag = ttag,
  781. .begin = begin,
  782. .end = end,
  783. .diff = diff,
  784. .cb = cb,
  785. .data = data,
  786. .tag = tag,
  787. .buffer = buffer,
  788. .disk = disk,
  789. };
  790. sp += 1;
  791. tmask = 0;
  792. ttag = 0;
  793. begin = 0;
  794. end = 0;
  795. diff = 0;
  796. cb = lfs_dir_traverse_filter;
  797. data = &stack[sp-1].tag;
  798. continue;
  799. }
  800. }
  801. popped:
  802. // in filter range?
  803. if (lfs_tag_id(tmask) != 0 &&
  804. !(lfs_tag_id(tag) >= begin && lfs_tag_id(tag) < end)) {
  805. continue;
  806. }
  807. // handle special cases for mcu-side operations
  808. if (lfs_tag_type3(tag) == LFS_FROM_NOOP) {
  809. // do nothing
  810. } else if (lfs_tag_type3(tag) == LFS_FROM_MOVE) {
  811. // Without this condition, lfs_dir_traverse can exhibit an
  812. // extremely expensive O(n^3) of nested loops when renaming.
  813. // This happens because lfs_dir_traverse tries to filter tags by
  814. // the tags in the source directory, triggering a second
  815. // lfs_dir_traverse with its own filter operation.
  816. //
  817. // traverse with commit
  818. // '-> traverse with filter
  819. // '-> traverse with move
  820. // '-> traverse with filter
  821. //
  822. // However we don't actually care about filtering the second set of
  823. // tags, since duplicate tags have no effect when filtering.
  824. //
  825. // This check skips this unnecessary recursive filtering explicitly,
  826. // reducing this runtime from O(n^3) to O(n^2).
  827. if (cb == lfs_dir_traverse_filter) {
  828. continue;
  829. }
  830. // recurse into move
  831. stack[sp] = (struct lfs_dir_traverse){
  832. .dir = dir,
  833. .off = off,
  834. .ptag = ptag,
  835. .attrs = attrs,
  836. .attrcount = attrcount,
  837. .tmask = tmask,
  838. .ttag = ttag,
  839. .begin = begin,
  840. .end = end,
  841. .diff = diff,
  842. .cb = cb,
  843. .data = data,
  844. .tag = LFS_MKTAG(LFS_FROM_NOOP, 0, 0),
  845. };
  846. sp += 1;
  847. uint16_t fromid = lfs_tag_size(tag);
  848. uint16_t toid = lfs_tag_id(tag);
  849. dir = buffer;
  850. off = 0;
  851. ptag = 0xffffffff;
  852. attrs = NULL;
  853. attrcount = 0;
  854. tmask = LFS_MKTAG(0x600, 0x3ff, 0);
  855. ttag = LFS_MKTAG(LFS_TYPE_STRUCT, 0, 0);
  856. begin = fromid;
  857. end = fromid+1;
  858. diff = toid-fromid+diff;
  859. } else if (lfs_tag_type3(tag) == LFS_FROM_USERATTRS) {
  860. for (unsigned i = 0; i < lfs_tag_size(tag); i++) {
  861. const struct lfs_attr *a = buffer;
  862. res = cb(data, LFS_MKTAG(LFS_TYPE_USERATTR + a[i].type,
  863. lfs_tag_id(tag) + diff, a[i].size), a[i].buffer);
  864. if (res < 0) {
  865. return res;
  866. }
  867. if (res) {
  868. break;
  869. }
  870. }
  871. } else {
  872. res = cb(data, tag + LFS_MKTAG(0, diff, 0), buffer);
  873. if (res < 0) {
  874. return res;
  875. }
  876. if (res) {
  877. break;
  878. }
  879. }
  880. }
  881. if (sp > 0) {
  882. // pop from the stack and return, fortunately all pops share
  883. // a destination
  884. dir = stack[sp-1].dir;
  885. off = stack[sp-1].off;
  886. ptag = stack[sp-1].ptag;
  887. attrs = stack[sp-1].attrs;
  888. attrcount = stack[sp-1].attrcount;
  889. tmask = stack[sp-1].tmask;
  890. ttag = stack[sp-1].ttag;
  891. begin = stack[sp-1].begin;
  892. end = stack[sp-1].end;
  893. diff = stack[sp-1].diff;
  894. cb = stack[sp-1].cb;
  895. data = stack[sp-1].data;
  896. tag = stack[sp-1].tag;
  897. buffer = stack[sp-1].buffer;
  898. disk = stack[sp-1].disk;
  899. sp -= 1;
  900. goto popped;
  901. } else {
  902. return res;
  903. }
  904. }
  905. #endif
  906. static lfs_stag_t lfs_dir_fetchmatch(lfs_t *lfs,
  907. lfs_mdir_t *dir, const lfs_block_t pair[2],
  908. lfs_tag_t fmask, lfs_tag_t ftag, uint16_t *id,
  909. int (*cb)(void *data, lfs_tag_t tag, const void *buffer), void *data) {
  910. // we can find tag very efficiently during a fetch, since we're already
  911. // scanning the entire directory
  912. lfs_stag_t besttag = -1;
  913. // if either block address is invalid we return LFS_ERR_CORRUPT here,
  914. // otherwise later writes to the pair could fail
  915. if (lfs->block_count
  916. && (pair[0] >= lfs->block_count || pair[1] >= lfs->block_count)) {
  917. return LFS_ERR_CORRUPT;
  918. }
  919. // find the block with the most recent revision
  920. uint32_t revs[2] = {0, 0};
  921. int r = 0;
  922. for (int i = 0; i < 2; i++) {
  923. int err = lfs_bd_read(lfs,
  924. NULL, &lfs->rcache, sizeof(revs[i]),
  925. pair[i], 0, &revs[i], sizeof(revs[i]));
  926. revs[i] = lfs_fromle32(revs[i]);
  927. if (err && err != LFS_ERR_CORRUPT) {
  928. return err;
  929. }
  930. if (err != LFS_ERR_CORRUPT &&
  931. lfs_scmp(revs[i], revs[(i+1)%2]) > 0) {
  932. r = i;
  933. }
  934. }
  935. dir->pair[0] = pair[(r+0)%2];
  936. dir->pair[1] = pair[(r+1)%2];
  937. dir->rev = revs[(r+0)%2];
  938. dir->off = 0; // nonzero = found some commits
  939. // now scan tags to fetch the actual dir and find possible match
  940. for (int i = 0; i < 2; i++) {
  941. lfs_off_t off = 0;
  942. lfs_tag_t ptag = 0xffffffff;
  943. uint16_t tempcount = 0;
  944. lfs_block_t temptail[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  945. bool tempsplit = false;
  946. lfs_stag_t tempbesttag = besttag;
  947. // assume not erased until proven otherwise
  948. bool maybeerased = false;
  949. bool hasfcrc = false;
  950. struct lfs_fcrc fcrc;
  951. dir->rev = lfs_tole32(dir->rev);
  952. uint32_t crc = lfs_crc(0xffffffff, &dir->rev, sizeof(dir->rev));
  953. dir->rev = lfs_fromle32(dir->rev);
  954. while (true) {
  955. // extract next tag
  956. lfs_tag_t tag;
  957. off += lfs_tag_dsize(ptag);
  958. int err = lfs_bd_read(lfs,
  959. NULL, &lfs->rcache, lfs->cfg->block_size,
  960. dir->pair[0], off, &tag, sizeof(tag));
  961. if (err) {
  962. if (err == LFS_ERR_CORRUPT) {
  963. // can't continue?
  964. break;
  965. }
  966. return err;
  967. }
  968. crc = lfs_crc(crc, &tag, sizeof(tag));
  969. tag = lfs_frombe32(tag) ^ ptag;
  970. // next commit not yet programmed?
  971. if (!lfs_tag_isvalid(tag)) {
  972. // we only might be erased if the last tag was a crc
  973. maybeerased = (lfs_tag_type2(ptag) == LFS_TYPE_CCRC);
  974. break;
  975. // out of range?
  976. } else if (off + lfs_tag_dsize(tag) > lfs->cfg->block_size) {
  977. break;
  978. }
  979. ptag = tag;
  980. if (lfs_tag_type2(tag) == LFS_TYPE_CCRC) {
  981. // check the crc attr
  982. uint32_t dcrc;
  983. err = lfs_bd_read(lfs,
  984. NULL, &lfs->rcache, lfs->cfg->block_size,
  985. dir->pair[0], off+sizeof(tag), &dcrc, sizeof(dcrc));
  986. if (err) {
  987. if (err == LFS_ERR_CORRUPT) {
  988. break;
  989. }
  990. return err;
  991. }
  992. dcrc = lfs_fromle32(dcrc);
  993. if (crc != dcrc) {
  994. break;
  995. }
  996. // reset the next bit if we need to
  997. ptag ^= (lfs_tag_t)(lfs_tag_chunk(tag) & 1U) << 31;
  998. // toss our crc into the filesystem seed for
  999. // pseudorandom numbers, note we use another crc here
  1000. // as a collection function because it is sufficiently
  1001. // random and convenient
  1002. lfs->seed = lfs_crc(lfs->seed, &crc, sizeof(crc));
  1003. // update with what's found so far
  1004. besttag = tempbesttag;
  1005. dir->off = off + lfs_tag_dsize(tag);
  1006. dir->etag = ptag;
  1007. dir->count = tempcount;
  1008. dir->tail[0] = temptail[0];
  1009. dir->tail[1] = temptail[1];
  1010. dir->split = tempsplit;
  1011. // reset crc, hasfcrc
  1012. crc = 0xffffffff;
  1013. continue;
  1014. }
  1015. // crc the entry first, hopefully leaving it in the cache
  1016. err = lfs_bd_crc(lfs,
  1017. NULL, &lfs->rcache, lfs->cfg->block_size,
  1018. dir->pair[0], off+sizeof(tag),
  1019. lfs_tag_dsize(tag)-sizeof(tag), &crc);
  1020. if (err) {
  1021. if (err == LFS_ERR_CORRUPT) {
  1022. break;
  1023. }
  1024. return err;
  1025. }
  1026. // directory modification tags?
  1027. if (lfs_tag_type1(tag) == LFS_TYPE_NAME) {
  1028. // increase count of files if necessary
  1029. if (lfs_tag_id(tag) >= tempcount) {
  1030. tempcount = lfs_tag_id(tag) + 1;
  1031. }
  1032. } else if (lfs_tag_type1(tag) == LFS_TYPE_SPLICE) {
  1033. tempcount += lfs_tag_splice(tag);
  1034. if (tag == (LFS_MKTAG(LFS_TYPE_DELETE, 0, 0) |
  1035. (LFS_MKTAG(0, 0x3ff, 0) & tempbesttag))) {
  1036. tempbesttag |= 0x80000000;
  1037. } else if (tempbesttag != -1 &&
  1038. lfs_tag_id(tag) <= lfs_tag_id(tempbesttag)) {
  1039. tempbesttag += LFS_MKTAG(0, lfs_tag_splice(tag), 0);
  1040. }
  1041. } else if (lfs_tag_type1(tag) == LFS_TYPE_TAIL) {
  1042. tempsplit = (lfs_tag_chunk(tag) & 1);
  1043. err = lfs_bd_read(lfs,
  1044. NULL, &lfs->rcache, lfs->cfg->block_size,
  1045. dir->pair[0], off+sizeof(tag), &temptail, 8);
  1046. if (err) {
  1047. if (err == LFS_ERR_CORRUPT) {
  1048. break;
  1049. }
  1050. return err;
  1051. }
  1052. lfs_pair_fromle32(temptail);
  1053. } else if (lfs_tag_type3(tag) == LFS_TYPE_FCRC) {
  1054. err = lfs_bd_read(lfs,
  1055. NULL, &lfs->rcache, lfs->cfg->block_size,
  1056. dir->pair[0], off+sizeof(tag),
  1057. &fcrc, sizeof(fcrc));
  1058. if (err) {
  1059. if (err == LFS_ERR_CORRUPT) {
  1060. break;
  1061. }
  1062. }
  1063. lfs_fcrc_fromle32(&fcrc);
  1064. hasfcrc = true;
  1065. }
  1066. // found a match for our fetcher?
  1067. if ((fmask & tag) == (fmask & ftag)) {
  1068. int res = cb(data, tag, &(struct lfs_diskoff){
  1069. dir->pair[0], off+sizeof(tag)});
  1070. if (res < 0) {
  1071. if (res == LFS_ERR_CORRUPT) {
  1072. break;
  1073. }
  1074. return res;
  1075. }
  1076. if (res == LFS_CMP_EQ) {
  1077. // found a match
  1078. tempbesttag = tag;
  1079. } else if ((LFS_MKTAG(0x7ff, 0x3ff, 0) & tag) ==
  1080. (LFS_MKTAG(0x7ff, 0x3ff, 0) & tempbesttag)) {
  1081. // found an identical tag, but contents didn't match
  1082. // this must mean that our besttag has been overwritten
  1083. tempbesttag = -1;
  1084. } else if (res == LFS_CMP_GT &&
  1085. lfs_tag_id(tag) <= lfs_tag_id(tempbesttag)) {
  1086. // found a greater match, keep track to keep things sorted
  1087. tempbesttag = tag | 0x80000000;
  1088. }
  1089. }
  1090. }
  1091. // found no valid commits?
  1092. if (dir->off == 0) {
  1093. // try the other block?
  1094. lfs_pair_swap(dir->pair);
  1095. dir->rev = revs[(r+1)%2];
  1096. continue;
  1097. }
  1098. // did we end on a valid commit? we may have an erased block
  1099. dir->erased = false;
  1100. if (maybeerased && dir->off % lfs->cfg->prog_size == 0) {
  1101. #ifdef LFS_MULTIVERSION
  1102. // note versions < lfs2.1 did not have fcrc tags, if
  1103. // we're < lfs2.1 treat missing fcrc as erased data
  1104. //
  1105. // we don't strictly need to do this, but otherwise writing
  1106. // to lfs2.0 disks becomes very inefficient
  1107. if (lfs_fs_disk_version(lfs) < 0x00020001) {
  1108. dir->erased = true;
  1109. } else
  1110. #endif
  1111. if (hasfcrc) {
  1112. // check for an fcrc matching the next prog's erased state, if
  1113. // this failed most likely a previous prog was interrupted, we
  1114. // need a new erase
  1115. uint32_t fcrc_ = 0xffffffff;
  1116. int err = lfs_bd_crc(lfs,
  1117. NULL, &lfs->rcache, lfs->cfg->block_size,
  1118. dir->pair[0], dir->off, fcrc.size, &fcrc_);
  1119. if (err && err != LFS_ERR_CORRUPT) {
  1120. return err;
  1121. }
  1122. // found beginning of erased part?
  1123. dir->erased = (fcrc_ == fcrc.crc);
  1124. }
  1125. }
  1126. // synthetic move
  1127. if (lfs_gstate_hasmovehere(&lfs->gdisk, dir->pair)) {
  1128. if (lfs_tag_id(lfs->gdisk.tag) == lfs_tag_id(besttag)) {
  1129. besttag |= 0x80000000;
  1130. } else if (besttag != -1 &&
  1131. lfs_tag_id(lfs->gdisk.tag) < lfs_tag_id(besttag)) {
  1132. besttag -= LFS_MKTAG(0, 1, 0);
  1133. }
  1134. }
  1135. // found tag? or found best id?
  1136. if (id) {
  1137. *id = lfs_min(lfs_tag_id(besttag), dir->count);
  1138. }
  1139. if (lfs_tag_isvalid(besttag)) {
  1140. return besttag;
  1141. } else if (lfs_tag_id(besttag) < dir->count) {
  1142. return LFS_ERR_NOENT;
  1143. } else {
  1144. return 0;
  1145. }
  1146. }
  1147. LFS_ERROR("Corrupted dir pair at {0x%"PRIx32", 0x%"PRIx32"}",
  1148. dir->pair[0], dir->pair[1]);
  1149. return LFS_ERR_CORRUPT;
  1150. }
  1151. static int lfs_dir_fetch(lfs_t *lfs,
  1152. lfs_mdir_t *dir, const lfs_block_t pair[2]) {
  1153. // note, mask=-1, tag=-1 can never match a tag since this
  1154. // pattern has the invalid bit set
  1155. return (int)lfs_dir_fetchmatch(lfs, dir, pair,
  1156. (lfs_tag_t)-1, (lfs_tag_t)-1, NULL, NULL, NULL);
  1157. }
  1158. static int lfs_dir_getgstate(lfs_t *lfs, const lfs_mdir_t *dir,
  1159. lfs_gstate_t *gstate) {
  1160. lfs_gstate_t temp;
  1161. lfs_stag_t res = lfs_dir_get(lfs, dir, LFS_MKTAG(0x7ff, 0, 0),
  1162. LFS_MKTAG(LFS_TYPE_MOVESTATE, 0, sizeof(temp)), &temp);
  1163. if (res < 0 && res != LFS_ERR_NOENT) {
  1164. return res;
  1165. }
  1166. if (res != LFS_ERR_NOENT) {
  1167. // xor together to find resulting gstate
  1168. lfs_gstate_fromle32(&temp);
  1169. lfs_gstate_xor(gstate, &temp);
  1170. }
  1171. return 0;
  1172. }
  1173. static int lfs_dir_getinfo(lfs_t *lfs, lfs_mdir_t *dir,
  1174. uint16_t id, struct lfs_info *info) {
  1175. if (id == 0x3ff) {
  1176. // special case for root
  1177. strcpy(info->name, "/");
  1178. info->type = LFS_TYPE_DIR;
  1179. return 0;
  1180. }
  1181. lfs_stag_t tag = lfs_dir_get(lfs, dir, LFS_MKTAG(0x780, 0x3ff, 0),
  1182. LFS_MKTAG(LFS_TYPE_NAME, id, lfs->name_max+1), info->name);
  1183. if (tag < 0) {
  1184. return (int)tag;
  1185. }
  1186. info->type = lfs_tag_type3(tag);
  1187. struct lfs_ctz ctz;
  1188. tag = lfs_dir_get(lfs, dir, LFS_MKTAG(0x700, 0x3ff, 0),
  1189. LFS_MKTAG(LFS_TYPE_STRUCT, id, sizeof(ctz)), &ctz);
  1190. if (tag < 0) {
  1191. return (int)tag;
  1192. }
  1193. lfs_ctz_fromle32(&ctz);
  1194. if (lfs_tag_type3(tag) == LFS_TYPE_CTZSTRUCT) {
  1195. info->size = ctz.size;
  1196. } else if (lfs_tag_type3(tag) == LFS_TYPE_INLINESTRUCT) {
  1197. info->size = lfs_tag_size(tag);
  1198. }
  1199. return 0;
  1200. }
  1201. struct lfs_dir_find_match {
  1202. lfs_t *lfs;
  1203. const void *name;
  1204. lfs_size_t size;
  1205. };
  1206. static int lfs_dir_find_match(void *data,
  1207. lfs_tag_t tag, const void *buffer) {
  1208. struct lfs_dir_find_match *name = data;
  1209. lfs_t *lfs = name->lfs;
  1210. const struct lfs_diskoff *disk = buffer;
  1211. // compare with disk
  1212. lfs_size_t diff = lfs_min(name->size, lfs_tag_size(tag));
  1213. int res = lfs_bd_cmp(lfs,
  1214. NULL, &lfs->rcache, diff,
  1215. disk->block, disk->off, name->name, diff);
  1216. if (res != LFS_CMP_EQ) {
  1217. return res;
  1218. }
  1219. // only equal if our size is still the same
  1220. if (name->size != lfs_tag_size(tag)) {
  1221. return (name->size < lfs_tag_size(tag)) ? LFS_CMP_LT : LFS_CMP_GT;
  1222. }
  1223. // found a match!
  1224. return LFS_CMP_EQ;
  1225. }
  1226. static lfs_stag_t lfs_dir_find(lfs_t *lfs, lfs_mdir_t *dir,
  1227. const char **path, uint16_t *id) {
  1228. // we reduce path to a single name if we can find it
  1229. const char *name = *path;
  1230. if (id) {
  1231. *id = 0x3ff;
  1232. }
  1233. // default to root dir
  1234. lfs_stag_t tag = LFS_MKTAG(LFS_TYPE_DIR, 0x3ff, 0);
  1235. dir->tail[0] = lfs->root[0];
  1236. dir->tail[1] = lfs->root[1];
  1237. while (true) {
  1238. nextname:
  1239. // skip slashes
  1240. name += strspn(name, "/");
  1241. lfs_size_t namelen = strcspn(name, "/");
  1242. // skip '.' and root '..'
  1243. if ((namelen == 1 && memcmp(name, ".", 1) == 0) ||
  1244. (namelen == 2 && memcmp(name, "..", 2) == 0)) {
  1245. name += namelen;
  1246. goto nextname;
  1247. }
  1248. // skip if matched by '..' in name
  1249. const char *suffix = name + namelen;
  1250. lfs_size_t sufflen;
  1251. int depth = 1;
  1252. while (true) {
  1253. suffix += strspn(suffix, "/");
  1254. sufflen = strcspn(suffix, "/");
  1255. if (sufflen == 0) {
  1256. break;
  1257. }
  1258. if (sufflen == 2 && memcmp(suffix, "..", 2) == 0) {
  1259. depth -= 1;
  1260. if (depth == 0) {
  1261. name = suffix + sufflen;
  1262. goto nextname;
  1263. }
  1264. } else {
  1265. depth += 1;
  1266. }
  1267. suffix += sufflen;
  1268. }
  1269. // found path
  1270. if (name[0] == '\0') {
  1271. return tag;
  1272. }
  1273. // update what we've found so far
  1274. *path = name;
  1275. // only continue if we hit a directory
  1276. if (lfs_tag_type3(tag) != LFS_TYPE_DIR) {
  1277. return LFS_ERR_NOTDIR;
  1278. }
  1279. // grab the entry data
  1280. if (lfs_tag_id(tag) != 0x3ff) {
  1281. lfs_stag_t res = lfs_dir_get(lfs, dir, LFS_MKTAG(0x700, 0x3ff, 0),
  1282. LFS_MKTAG(LFS_TYPE_STRUCT, lfs_tag_id(tag), 8), dir->tail);
  1283. if (res < 0) {
  1284. return res;
  1285. }
  1286. lfs_pair_fromle32(dir->tail);
  1287. }
  1288. // find entry matching name
  1289. while (true) {
  1290. tag = lfs_dir_fetchmatch(lfs, dir, dir->tail,
  1291. LFS_MKTAG(0x780, 0, 0),
  1292. LFS_MKTAG(LFS_TYPE_NAME, 0, namelen),
  1293. // are we last name?
  1294. (strchr(name, '/') == NULL) ? id : NULL,
  1295. lfs_dir_find_match, &(struct lfs_dir_find_match){
  1296. lfs, name, namelen});
  1297. if (tag < 0) {
  1298. return tag;
  1299. }
  1300. if (tag) {
  1301. break;
  1302. }
  1303. if (!dir->split) {
  1304. return LFS_ERR_NOENT;
  1305. }
  1306. }
  1307. // to next name
  1308. name += namelen;
  1309. }
  1310. }
  1311. // commit logic
  1312. struct lfs_commit {
  1313. lfs_block_t block;
  1314. lfs_off_t off;
  1315. lfs_tag_t ptag;
  1316. uint32_t crc;
  1317. lfs_off_t begin;
  1318. lfs_off_t end;
  1319. };
  1320. #ifndef LFS_READONLY
  1321. static int lfs_dir_commitprog(lfs_t *lfs, struct lfs_commit *commit,
  1322. const void *buffer, lfs_size_t size) {
  1323. int err = lfs_bd_prog(lfs,
  1324. &lfs->pcache, &lfs->rcache, false,
  1325. commit->block, commit->off ,
  1326. (const uint8_t*)buffer, size);
  1327. if (err) {
  1328. return err;
  1329. }
  1330. commit->crc = lfs_crc(commit->crc, buffer, size);
  1331. commit->off += size;
  1332. return 0;
  1333. }
  1334. #endif
  1335. #ifndef LFS_READONLY
  1336. static int lfs_dir_commitattr(lfs_t *lfs, struct lfs_commit *commit,
  1337. lfs_tag_t tag, const void *buffer) {
  1338. // check if we fit
  1339. lfs_size_t dsize = lfs_tag_dsize(tag);
  1340. if (commit->off + dsize > commit->end) {
  1341. return LFS_ERR_NOSPC;
  1342. }
  1343. // write out tag
  1344. lfs_tag_t ntag = lfs_tobe32((tag & 0x7fffffff) ^ commit->ptag);
  1345. int err = lfs_dir_commitprog(lfs, commit, &ntag, sizeof(ntag));
  1346. if (err) {
  1347. return err;
  1348. }
  1349. if (!(tag & 0x80000000)) {
  1350. // from memory
  1351. err = lfs_dir_commitprog(lfs, commit, buffer, dsize-sizeof(tag));
  1352. if (err) {
  1353. return err;
  1354. }
  1355. } else {
  1356. // from disk
  1357. const struct lfs_diskoff *disk = buffer;
  1358. for (lfs_off_t i = 0; i < dsize-sizeof(tag); i++) {
  1359. // rely on caching to make this efficient
  1360. uint8_t dat;
  1361. err = lfs_bd_read(lfs,
  1362. NULL, &lfs->rcache, dsize-sizeof(tag)-i,
  1363. disk->block, disk->off+i, &dat, 1);
  1364. if (err) {
  1365. return err;
  1366. }
  1367. err = lfs_dir_commitprog(lfs, commit, &dat, 1);
  1368. if (err) {
  1369. return err;
  1370. }
  1371. }
  1372. }
  1373. commit->ptag = tag & 0x7fffffff;
  1374. return 0;
  1375. }
  1376. #endif
  1377. #ifndef LFS_READONLY
  1378. static int lfs_dir_commitcrc(lfs_t *lfs, struct lfs_commit *commit) {
  1379. // align to program units
  1380. //
  1381. // this gets a bit complex as we have two types of crcs:
  1382. // - 5-word crc with fcrc to check following prog (middle of block)
  1383. // - 2-word crc with no following prog (end of block)
  1384. const lfs_off_t end = lfs_alignup(
  1385. lfs_min(commit->off + 5*sizeof(uint32_t), lfs->cfg->block_size),
  1386. lfs->cfg->prog_size);
  1387. lfs_off_t off1 = 0;
  1388. uint32_t crc1 = 0;
  1389. // create crc tags to fill up remainder of commit, note that
  1390. // padding is not crced, which lets fetches skip padding but
  1391. // makes committing a bit more complicated
  1392. while (commit->off < end) {
  1393. lfs_off_t noff = (
  1394. lfs_min(end - (commit->off+sizeof(lfs_tag_t)), 0x3fe)
  1395. + (commit->off+sizeof(lfs_tag_t)));
  1396. // too large for crc tag? need padding commits
  1397. if (noff < end) {
  1398. noff = lfs_min(noff, end - 5*sizeof(uint32_t));
  1399. }
  1400. // space for fcrc?
  1401. uint8_t eperturb = (uint8_t)-1;
  1402. if (noff >= end && noff <= lfs->cfg->block_size - lfs->cfg->prog_size) {
  1403. // first read the leading byte, this always contains a bit
  1404. // we can perturb to avoid writes that don't change the fcrc
  1405. int err = lfs_bd_read(lfs,
  1406. NULL, &lfs->rcache, lfs->cfg->prog_size,
  1407. commit->block, noff, &eperturb, 1);
  1408. if (err && err != LFS_ERR_CORRUPT) {
  1409. return err;
  1410. }
  1411. #ifdef LFS_MULTIVERSION
  1412. // unfortunately fcrcs break mdir fetching < lfs2.1, so only write
  1413. // these if we're a >= lfs2.1 filesystem
  1414. if (lfs_fs_disk_version(lfs) <= 0x00020000) {
  1415. // don't write fcrc
  1416. } else
  1417. #endif
  1418. {
  1419. // find the expected fcrc, don't bother avoiding a reread
  1420. // of the eperturb, it should still be in our cache
  1421. struct lfs_fcrc fcrc = {
  1422. .size = lfs->cfg->prog_size,
  1423. .crc = 0xffffffff
  1424. };
  1425. err = lfs_bd_crc(lfs,
  1426. NULL, &lfs->rcache, lfs->cfg->prog_size,
  1427. commit->block, noff, fcrc.size, &fcrc.crc);
  1428. if (err && err != LFS_ERR_CORRUPT) {
  1429. return err;
  1430. }
  1431. lfs_fcrc_tole32(&fcrc);
  1432. err = lfs_dir_commitattr(lfs, commit,
  1433. LFS_MKTAG(LFS_TYPE_FCRC, 0x3ff, sizeof(struct lfs_fcrc)),
  1434. &fcrc);
  1435. if (err) {
  1436. return err;
  1437. }
  1438. }
  1439. }
  1440. // build commit crc
  1441. struct {
  1442. lfs_tag_t tag;
  1443. uint32_t crc;
  1444. } ccrc;
  1445. lfs_tag_t ntag = LFS_MKTAG(
  1446. LFS_TYPE_CCRC + (((uint8_t)~eperturb) >> 7), 0x3ff,
  1447. noff - (commit->off+sizeof(lfs_tag_t)));
  1448. ccrc.tag = lfs_tobe32(ntag ^ commit->ptag);
  1449. commit->crc = lfs_crc(commit->crc, &ccrc.tag, sizeof(lfs_tag_t));
  1450. ccrc.crc = lfs_tole32(commit->crc);
  1451. int err = lfs_bd_prog(lfs,
  1452. &lfs->pcache, &lfs->rcache, false,
  1453. commit->block, commit->off, &ccrc, sizeof(ccrc));
  1454. if (err) {
  1455. return err;
  1456. }
  1457. // keep track of non-padding checksum to verify
  1458. if (off1 == 0) {
  1459. off1 = commit->off + sizeof(lfs_tag_t);
  1460. crc1 = commit->crc;
  1461. }
  1462. commit->off = noff;
  1463. // perturb valid bit?
  1464. commit->ptag = ntag ^ ((0x80UL & ~eperturb) << 24);
  1465. // reset crc for next commit
  1466. commit->crc = 0xffffffff;
  1467. // manually flush here since we don't prog the padding, this confuses
  1468. // the caching layer
  1469. if (noff >= end || noff >= lfs->pcache.off + lfs->cfg->cache_size) {
  1470. // flush buffers
  1471. int err = lfs_bd_sync(lfs, &lfs->pcache, &lfs->rcache, false);
  1472. if (err) {
  1473. return err;
  1474. }
  1475. }
  1476. }
  1477. // successful commit, check checksums to make sure
  1478. //
  1479. // note that we don't need to check padding commits, worst
  1480. // case if they are corrupted we would have had to compact anyways
  1481. lfs_off_t off = commit->begin;
  1482. uint32_t crc = 0xffffffff;
  1483. int err = lfs_bd_crc(lfs,
  1484. NULL, &lfs->rcache, off1+sizeof(uint32_t),
  1485. commit->block, off, off1-off, &crc);
  1486. if (err) {
  1487. return err;
  1488. }
  1489. // check non-padding commits against known crc
  1490. if (crc != crc1) {
  1491. return LFS_ERR_CORRUPT;
  1492. }
  1493. // make sure to check crc in case we happen to pick
  1494. // up an unrelated crc (frozen block?)
  1495. err = lfs_bd_crc(lfs,
  1496. NULL, &lfs->rcache, sizeof(uint32_t),
  1497. commit->block, off1, sizeof(uint32_t), &crc);
  1498. if (err) {
  1499. return err;
  1500. }
  1501. if (crc != 0) {
  1502. return LFS_ERR_CORRUPT;
  1503. }
  1504. return 0;
  1505. }
  1506. #endif
  1507. #ifndef LFS_READONLY
  1508. static int lfs_dir_alloc(lfs_t *lfs, lfs_mdir_t *dir) {
  1509. // allocate pair of dir blocks (backwards, so we write block 1 first)
  1510. for (int i = 0; i < 2; i++) {
  1511. int err = lfs_alloc(lfs, &dir->pair[(i+1)%2]);
  1512. if (err) {
  1513. return err;
  1514. }
  1515. }
  1516. // zero for reproducibility in case initial block is unreadable
  1517. dir->rev = 0;
  1518. // rather than clobbering one of the blocks we just pretend
  1519. // the revision may be valid
  1520. int err = lfs_bd_read(lfs,
  1521. NULL, &lfs->rcache, sizeof(dir->rev),
  1522. dir->pair[0], 0, &dir->rev, sizeof(dir->rev));
  1523. dir->rev = lfs_fromle32(dir->rev);
  1524. if (err && err != LFS_ERR_CORRUPT) {
  1525. return err;
  1526. }
  1527. // to make sure we don't immediately evict, align the new revision count
  1528. // to our block_cycles modulus, see lfs_dir_compact for why our modulus
  1529. // is tweaked this way
  1530. if (lfs->cfg->block_cycles > 0) {
  1531. dir->rev = lfs_alignup(dir->rev, ((lfs->cfg->block_cycles+1)|1));
  1532. }
  1533. // set defaults
  1534. dir->off = sizeof(dir->rev);
  1535. dir->etag = 0xffffffff;
  1536. dir->count = 0;
  1537. dir->tail[0] = LFS_BLOCK_NULL;
  1538. dir->tail[1] = LFS_BLOCK_NULL;
  1539. dir->erased = false;
  1540. dir->split = false;
  1541. // don't write out yet, let caller take care of that
  1542. return 0;
  1543. }
  1544. #endif
  1545. #ifndef LFS_READONLY
  1546. static int lfs_dir_drop(lfs_t *lfs, lfs_mdir_t *dir, lfs_mdir_t *tail) {
  1547. // steal state
  1548. int err = lfs_dir_getgstate(lfs, tail, &lfs->gdelta);
  1549. if (err) {
  1550. return err;
  1551. }
  1552. // steal tail
  1553. lfs_pair_tole32(tail->tail);
  1554. err = lfs_dir_commit(lfs, dir, LFS_MKATTRS(
  1555. {LFS_MKTAG(LFS_TYPE_TAIL + tail->split, 0x3ff, 8), tail->tail}));
  1556. lfs_pair_fromle32(tail->tail);
  1557. if (err) {
  1558. return err;
  1559. }
  1560. return 0;
  1561. }
  1562. #endif
  1563. #ifndef LFS_READONLY
  1564. static int lfs_dir_split(lfs_t *lfs,
  1565. lfs_mdir_t *dir, const struct lfs_mattr *attrs, int attrcount,
  1566. lfs_mdir_t *source, uint16_t split, uint16_t end) {
  1567. // create tail metadata pair
  1568. lfs_mdir_t tail;
  1569. int err = lfs_dir_alloc(lfs, &tail);
  1570. if (err) {
  1571. return err;
  1572. }
  1573. tail.split = dir->split;
  1574. tail.tail[0] = dir->tail[0];
  1575. tail.tail[1] = dir->tail[1];
  1576. // note we don't care about LFS_OK_RELOCATED
  1577. int res = lfs_dir_compact(lfs, &tail, attrs, attrcount, source, split, end);
  1578. if (res < 0) {
  1579. return res;
  1580. }
  1581. dir->tail[0] = tail.pair[0];
  1582. dir->tail[1] = tail.pair[1];
  1583. dir->split = true;
  1584. // update root if needed
  1585. if (lfs_pair_cmp(dir->pair, lfs->root) == 0 && split == 0) {
  1586. lfs->root[0] = tail.pair[0];
  1587. lfs->root[1] = tail.pair[1];
  1588. }
  1589. return 0;
  1590. }
  1591. #endif
  1592. #ifndef LFS_READONLY
  1593. static int lfs_dir_commit_size(void *p, lfs_tag_t tag, const void *buffer) {
  1594. lfs_size_t *size = p;
  1595. (void)buffer;
  1596. *size += lfs_tag_dsize(tag);
  1597. return 0;
  1598. }
  1599. #endif
  1600. #ifndef LFS_READONLY
  1601. struct lfs_dir_commit_commit {
  1602. lfs_t *lfs;
  1603. struct lfs_commit *commit;
  1604. };
  1605. #endif
  1606. #ifndef LFS_READONLY
  1607. static int lfs_dir_commit_commit(void *p, lfs_tag_t tag, const void *buffer) {
  1608. struct lfs_dir_commit_commit *commit = p;
  1609. return lfs_dir_commitattr(commit->lfs, commit->commit, tag, buffer);
  1610. }
  1611. #endif
  1612. #ifndef LFS_READONLY
  1613. static bool lfs_dir_needsrelocation(lfs_t *lfs, lfs_mdir_t *dir) {
  1614. // If our revision count == n * block_cycles, we should force a relocation,
  1615. // this is how littlefs wear-levels at the metadata-pair level. Note that we
  1616. // actually use (block_cycles+1)|1, this is to avoid two corner cases:
  1617. // 1. block_cycles = 1, which would prevent relocations from terminating
  1618. // 2. block_cycles = 2n, which, due to aliasing, would only ever relocate
  1619. // one metadata block in the pair, effectively making this useless
  1620. return (lfs->cfg->block_cycles > 0
  1621. && ((dir->rev + 1) % ((lfs->cfg->block_cycles+1)|1) == 0));
  1622. }
  1623. #endif
  1624. #ifndef LFS_READONLY
  1625. static int lfs_dir_compact(lfs_t *lfs,
  1626. lfs_mdir_t *dir, const struct lfs_mattr *attrs, int attrcount,
  1627. lfs_mdir_t *source, uint16_t begin, uint16_t end) {
  1628. // save some state in case block is bad
  1629. bool relocated = false;
  1630. bool tired = lfs_dir_needsrelocation(lfs, dir);
  1631. // increment revision count
  1632. dir->rev += 1;
  1633. // do not proactively relocate blocks during migrations, this
  1634. // can cause a number of failure states such: clobbering the
  1635. // v1 superblock if we relocate root, and invalidating directory
  1636. // pointers if we relocate the head of a directory. On top of
  1637. // this, relocations increase the overall complexity of
  1638. // lfs_migration, which is already a delicate operation.
  1639. #ifdef LFS_MIGRATE
  1640. if (lfs->lfs1) {
  1641. tired = false;
  1642. }
  1643. #endif
  1644. if (tired && lfs_pair_cmp(dir->pair, (const lfs_block_t[2]){0, 1}) != 0) {
  1645. // we're writing too much, time to relocate
  1646. goto relocate;
  1647. }
  1648. // begin loop to commit compaction to blocks until a compact sticks
  1649. while (true) {
  1650. {
  1651. // setup commit state
  1652. struct lfs_commit commit = {
  1653. .block = dir->pair[1],
  1654. .off = 0,
  1655. .ptag = 0xffffffff,
  1656. .crc = 0xffffffff,
  1657. .begin = 0,
  1658. .end = (lfs->cfg->metadata_max ?
  1659. lfs->cfg->metadata_max : lfs->cfg->block_size) - 8,
  1660. };
  1661. // erase block to write to
  1662. int err = lfs_bd_erase(lfs, dir->pair[1]);
  1663. if (err) {
  1664. if (err == LFS_ERR_CORRUPT) {
  1665. goto relocate;
  1666. }
  1667. return err;
  1668. }
  1669. // write out header
  1670. dir->rev = lfs_tole32(dir->rev);
  1671. err = lfs_dir_commitprog(lfs, &commit,
  1672. &dir->rev, sizeof(dir->rev));
  1673. dir->rev = lfs_fromle32(dir->rev);
  1674. if (err) {
  1675. if (err == LFS_ERR_CORRUPT) {
  1676. goto relocate;
  1677. }
  1678. return err;
  1679. }
  1680. // traverse the directory, this time writing out all unique tags
  1681. err = lfs_dir_traverse(lfs,
  1682. source, 0, 0xffffffff, attrs, attrcount,
  1683. LFS_MKTAG(0x400, 0x3ff, 0),
  1684. LFS_MKTAG(LFS_TYPE_NAME, 0, 0),
  1685. begin, end, -begin,
  1686. lfs_dir_commit_commit, &(struct lfs_dir_commit_commit){
  1687. lfs, &commit});
  1688. if (err) {
  1689. if (err == LFS_ERR_CORRUPT) {
  1690. goto relocate;
  1691. }
  1692. return err;
  1693. }
  1694. // commit tail, which may be new after last size check
  1695. if (!lfs_pair_isnull(dir->tail)) {
  1696. lfs_pair_tole32(dir->tail);
  1697. err = lfs_dir_commitattr(lfs, &commit,
  1698. LFS_MKTAG(LFS_TYPE_TAIL + dir->split, 0x3ff, 8),
  1699. dir->tail);
  1700. lfs_pair_fromle32(dir->tail);
  1701. if (err) {
  1702. if (err == LFS_ERR_CORRUPT) {
  1703. goto relocate;
  1704. }
  1705. return err;
  1706. }
  1707. }
  1708. // bring over gstate?
  1709. lfs_gstate_t delta = {0};
  1710. if (!relocated) {
  1711. lfs_gstate_xor(&delta, &lfs->gdisk);
  1712. lfs_gstate_xor(&delta, &lfs->gstate);
  1713. }
  1714. lfs_gstate_xor(&delta, &lfs->gdelta);
  1715. delta.tag &= ~LFS_MKTAG(0, 0, 0x3ff);
  1716. err = lfs_dir_getgstate(lfs, dir, &delta);
  1717. if (err) {
  1718. return err;
  1719. }
  1720. if (!lfs_gstate_iszero(&delta)) {
  1721. lfs_gstate_tole32(&delta);
  1722. err = lfs_dir_commitattr(lfs, &commit,
  1723. LFS_MKTAG(LFS_TYPE_MOVESTATE, 0x3ff,
  1724. sizeof(delta)), &delta);
  1725. if (err) {
  1726. if (err == LFS_ERR_CORRUPT) {
  1727. goto relocate;
  1728. }
  1729. return err;
  1730. }
  1731. }
  1732. // complete commit with crc
  1733. err = lfs_dir_commitcrc(lfs, &commit);
  1734. if (err) {
  1735. if (err == LFS_ERR_CORRUPT) {
  1736. goto relocate;
  1737. }
  1738. return err;
  1739. }
  1740. // successful compaction, swap dir pair to indicate most recent
  1741. LFS_ASSERT(commit.off % lfs->cfg->prog_size == 0);
  1742. lfs_pair_swap(dir->pair);
  1743. dir->count = end - begin;
  1744. dir->off = commit.off;
  1745. dir->etag = commit.ptag;
  1746. // update gstate
  1747. lfs->gdelta = (lfs_gstate_t){0};
  1748. if (!relocated) {
  1749. lfs->gdisk = lfs->gstate;
  1750. }
  1751. }
  1752. break;
  1753. relocate:
  1754. // commit was corrupted, drop caches and prepare to relocate block
  1755. relocated = true;
  1756. lfs_cache_drop(lfs, &lfs->pcache);
  1757. if (!tired) {
  1758. LFS_DEBUG("Bad block at 0x%"PRIx32, dir->pair[1]);
  1759. }
  1760. // can't relocate superblock, filesystem is now frozen
  1761. if (lfs_pair_cmp(dir->pair, (const lfs_block_t[2]){0, 1}) == 0) {
  1762. LFS_WARN("Superblock 0x%"PRIx32" has become unwritable",
  1763. dir->pair[1]);
  1764. return LFS_ERR_NOSPC;
  1765. }
  1766. // relocate half of pair
  1767. int err = lfs_alloc(lfs, &dir->pair[1]);
  1768. if (err && (err != LFS_ERR_NOSPC || !tired)) {
  1769. return err;
  1770. }
  1771. tired = false;
  1772. continue;
  1773. }
  1774. return relocated ? LFS_OK_RELOCATED : 0;
  1775. }
  1776. #endif
  1777. #ifndef LFS_READONLY
  1778. static int lfs_dir_splittingcompact(lfs_t *lfs, lfs_mdir_t *dir,
  1779. const struct lfs_mattr *attrs, int attrcount,
  1780. lfs_mdir_t *source, uint16_t begin, uint16_t end) {
  1781. while (true) {
  1782. // find size of first split, we do this by halving the split until
  1783. // the metadata is guaranteed to fit
  1784. //
  1785. // Note that this isn't a true binary search, we never increase the
  1786. // split size. This may result in poorly distributed metadata but isn't
  1787. // worth the extra code size or performance hit to fix.
  1788. lfs_size_t split = begin;
  1789. while (end - split > 1) {
  1790. lfs_size_t size = 0;
  1791. int err = lfs_dir_traverse(lfs,
  1792. source, 0, 0xffffffff, attrs, attrcount,
  1793. LFS_MKTAG(0x400, 0x3ff, 0),
  1794. LFS_MKTAG(LFS_TYPE_NAME, 0, 0),
  1795. split, end, -split,
  1796. lfs_dir_commit_size, &size);
  1797. if (err) {
  1798. return err;
  1799. }
  1800. // space is complicated, we need room for:
  1801. //
  1802. // - tail: 4+2*4 = 12 bytes
  1803. // - gstate: 4+3*4 = 16 bytes
  1804. // - move delete: 4 = 4 bytes
  1805. // - crc: 4+4 = 8 bytes
  1806. // total = 40 bytes
  1807. //
  1808. // And we cap at half a block to avoid degenerate cases with
  1809. // nearly-full metadata blocks.
  1810. //
  1811. if (end - split < 0xff
  1812. && size <= lfs_min(
  1813. lfs->cfg->block_size - 40,
  1814. lfs_alignup(
  1815. (lfs->cfg->metadata_max
  1816. ? lfs->cfg->metadata_max
  1817. : lfs->cfg->block_size)/2,
  1818. lfs->cfg->prog_size))) {
  1819. break;
  1820. }
  1821. split = split + ((end - split) / 2);
  1822. }
  1823. if (split == begin) {
  1824. // no split needed
  1825. break;
  1826. }
  1827. // split into two metadata pairs and continue
  1828. int err = lfs_dir_split(lfs, dir, attrs, attrcount,
  1829. source, split, end);
  1830. if (err && err != LFS_ERR_NOSPC) {
  1831. return err;
  1832. }
  1833. if (err) {
  1834. // we can't allocate a new block, try to compact with degraded
  1835. // performance
  1836. LFS_WARN("Unable to split {0x%"PRIx32", 0x%"PRIx32"}",
  1837. dir->pair[0], dir->pair[1]);
  1838. break;
  1839. } else {
  1840. end = split;
  1841. }
  1842. }
  1843. if (lfs_dir_needsrelocation(lfs, dir)
  1844. && lfs_pair_cmp(dir->pair, (const lfs_block_t[2]){0, 1}) == 0) {
  1845. // oh no! we're writing too much to the superblock,
  1846. // should we expand?
  1847. lfs_ssize_t size = lfs_fs_rawsize(lfs);
  1848. if (size < 0) {
  1849. return size;
  1850. }
  1851. // do we have extra space? littlefs can't reclaim this space
  1852. // by itself, so expand cautiously
  1853. if ((lfs_size_t)size < lfs->block_count/2) {
  1854. LFS_DEBUG("Expanding superblock at rev %"PRIu32, dir->rev);
  1855. int err = lfs_dir_split(lfs, dir, attrs, attrcount,
  1856. source, begin, end);
  1857. if (err && err != LFS_ERR_NOSPC) {
  1858. return err;
  1859. }
  1860. if (err) {
  1861. // welp, we tried, if we ran out of space there's not much
  1862. // we can do, we'll error later if we've become frozen
  1863. LFS_WARN("Unable to expand superblock");
  1864. } else {
  1865. end = begin;
  1866. }
  1867. }
  1868. }
  1869. return lfs_dir_compact(lfs, dir, attrs, attrcount, source, begin, end);
  1870. }
  1871. #endif
  1872. #ifndef LFS_READONLY
  1873. static int lfs_dir_relocatingcommit(lfs_t *lfs, lfs_mdir_t *dir,
  1874. const lfs_block_t pair[2],
  1875. const struct lfs_mattr *attrs, int attrcount,
  1876. lfs_mdir_t *pdir) {
  1877. int state = 0;
  1878. // calculate changes to the directory
  1879. bool hasdelete = false;
  1880. for (int i = 0; i < attrcount; i++) {
  1881. if (lfs_tag_type3(attrs[i].tag) == LFS_TYPE_CREATE) {
  1882. dir->count += 1;
  1883. } else if (lfs_tag_type3(attrs[i].tag) == LFS_TYPE_DELETE) {
  1884. LFS_ASSERT(dir->count > 0);
  1885. dir->count -= 1;
  1886. hasdelete = true;
  1887. } else if (lfs_tag_type1(attrs[i].tag) == LFS_TYPE_TAIL) {
  1888. dir->tail[0] = ((lfs_block_t*)attrs[i].buffer)[0];
  1889. dir->tail[1] = ((lfs_block_t*)attrs[i].buffer)[1];
  1890. dir->split = (lfs_tag_chunk(attrs[i].tag) & 1);
  1891. lfs_pair_fromle32(dir->tail);
  1892. }
  1893. }
  1894. // should we actually drop the directory block?
  1895. if (hasdelete && dir->count == 0) {
  1896. LFS_ASSERT(pdir);
  1897. int err = lfs_fs_pred(lfs, dir->pair, pdir);
  1898. if (err && err != LFS_ERR_NOENT) {
  1899. return err;
  1900. }
  1901. if (err != LFS_ERR_NOENT && pdir->split) {
  1902. state = LFS_OK_DROPPED;
  1903. goto fixmlist;
  1904. }
  1905. }
  1906. if (dir->erased) {
  1907. // try to commit
  1908. struct lfs_commit commit = {
  1909. .block = dir->pair[0],
  1910. .off = dir->off,
  1911. .ptag = dir->etag,
  1912. .crc = 0xffffffff,
  1913. .begin = dir->off,
  1914. .end = (lfs->cfg->metadata_max ?
  1915. lfs->cfg->metadata_max : lfs->cfg->block_size) - 8,
  1916. };
  1917. // traverse attrs that need to be written out
  1918. lfs_pair_tole32(dir->tail);
  1919. int err = lfs_dir_traverse(lfs,
  1920. dir, dir->off, dir->etag, attrs, attrcount,
  1921. 0, 0, 0, 0, 0,
  1922. lfs_dir_commit_commit, &(struct lfs_dir_commit_commit){
  1923. lfs, &commit});
  1924. lfs_pair_fromle32(dir->tail);
  1925. if (err) {
  1926. if (err == LFS_ERR_NOSPC || err == LFS_ERR_CORRUPT) {
  1927. goto compact;
  1928. }
  1929. return err;
  1930. }
  1931. // commit any global diffs if we have any
  1932. lfs_gstate_t delta = {0};
  1933. lfs_gstate_xor(&delta, &lfs->gstate);
  1934. lfs_gstate_xor(&delta, &lfs->gdisk);
  1935. lfs_gstate_xor(&delta, &lfs->gdelta);
  1936. delta.tag &= ~LFS_MKTAG(0, 0, 0x3ff);
  1937. if (!lfs_gstate_iszero(&delta)) {
  1938. err = lfs_dir_getgstate(lfs, dir, &delta);
  1939. if (err) {
  1940. return err;
  1941. }
  1942. lfs_gstate_tole32(&delta);
  1943. err = lfs_dir_commitattr(lfs, &commit,
  1944. LFS_MKTAG(LFS_TYPE_MOVESTATE, 0x3ff,
  1945. sizeof(delta)), &delta);
  1946. if (err) {
  1947. if (err == LFS_ERR_NOSPC || err == LFS_ERR_CORRUPT) {
  1948. goto compact;
  1949. }
  1950. return err;
  1951. }
  1952. }
  1953. // finalize commit with the crc
  1954. err = lfs_dir_commitcrc(lfs, &commit);
  1955. if (err) {
  1956. if (err == LFS_ERR_NOSPC || err == LFS_ERR_CORRUPT) {
  1957. goto compact;
  1958. }
  1959. return err;
  1960. }
  1961. // successful commit, update dir
  1962. LFS_ASSERT(commit.off % lfs->cfg->prog_size == 0);
  1963. dir->off = commit.off;
  1964. dir->etag = commit.ptag;
  1965. // and update gstate
  1966. lfs->gdisk = lfs->gstate;
  1967. lfs->gdelta = (lfs_gstate_t){0};
  1968. goto fixmlist;
  1969. }
  1970. compact:
  1971. // fall back to compaction
  1972. lfs_cache_drop(lfs, &lfs->pcache);
  1973. state = lfs_dir_splittingcompact(lfs, dir, attrs, attrcount,
  1974. dir, 0, dir->count);
  1975. if (state < 0) {
  1976. return state;
  1977. }
  1978. goto fixmlist;
  1979. fixmlist:;
  1980. // this complicated bit of logic is for fixing up any active
  1981. // metadata-pairs that we may have affected
  1982. //
  1983. // note we have to make two passes since the mdir passed to
  1984. // lfs_dir_commit could also be in this list, and even then
  1985. // we need to copy the pair so they don't get clobbered if we refetch
  1986. // our mdir.
  1987. lfs_block_t oldpair[2] = {pair[0], pair[1]};
  1988. for (struct lfs_mlist *d = lfs->mlist; d; d = d->next) {
  1989. if (lfs_pair_cmp(d->m.pair, oldpair) == 0) {
  1990. d->m = *dir;
  1991. if (d->m.pair != pair) {
  1992. for (int i = 0; i < attrcount; i++) {
  1993. if (lfs_tag_type3(attrs[i].tag) == LFS_TYPE_DELETE &&
  1994. d->id == lfs_tag_id(attrs[i].tag)) {
  1995. d->m.pair[0] = LFS_BLOCK_NULL;
  1996. d->m.pair[1] = LFS_BLOCK_NULL;
  1997. } else if (lfs_tag_type3(attrs[i].tag) == LFS_TYPE_DELETE &&
  1998. d->id > lfs_tag_id(attrs[i].tag)) {
  1999. d->id -= 1;
  2000. if (d->type == LFS_TYPE_DIR) {
  2001. ((lfs_dir_t*)d)->pos -= 1;
  2002. }
  2003. } else if (lfs_tag_type3(attrs[i].tag) == LFS_TYPE_CREATE &&
  2004. d->id >= lfs_tag_id(attrs[i].tag)) {
  2005. d->id += 1;
  2006. if (d->type == LFS_TYPE_DIR) {
  2007. ((lfs_dir_t*)d)->pos += 1;
  2008. }
  2009. }
  2010. }
  2011. }
  2012. while (d->id >= d->m.count && d->m.split) {
  2013. // we split and id is on tail now
  2014. d->id -= d->m.count;
  2015. int err = lfs_dir_fetch(lfs, &d->m, d->m.tail);
  2016. if (err) {
  2017. return err;
  2018. }
  2019. }
  2020. }
  2021. }
  2022. return state;
  2023. }
  2024. #endif
  2025. #ifndef LFS_READONLY
  2026. static int lfs_dir_orphaningcommit(lfs_t *lfs, lfs_mdir_t *dir,
  2027. const struct lfs_mattr *attrs, int attrcount) {
  2028. // check for any inline files that aren't RAM backed and
  2029. // forcefully evict them, needed for filesystem consistency
  2030. for (lfs_file_t *f = (lfs_file_t*)lfs->mlist; f; f = f->next) {
  2031. if (dir != &f->m && lfs_pair_cmp(f->m.pair, dir->pair) == 0 &&
  2032. f->type == LFS_TYPE_REG && (f->flags & LFS_F_INLINE) &&
  2033. f->ctz.size > lfs->cfg->cache_size) {
  2034. int err = lfs_file_outline(lfs, f);
  2035. if (err) {
  2036. return err;
  2037. }
  2038. err = lfs_file_flush(lfs, f);
  2039. if (err) {
  2040. return err;
  2041. }
  2042. }
  2043. }
  2044. lfs_block_t lpair[2] = {dir->pair[0], dir->pair[1]};
  2045. lfs_mdir_t ldir = *dir;
  2046. lfs_mdir_t pdir;
  2047. int state = lfs_dir_relocatingcommit(lfs, &ldir, dir->pair,
  2048. attrs, attrcount, &pdir);
  2049. if (state < 0) {
  2050. return state;
  2051. }
  2052. // update if we're not in mlist, note we may have already been
  2053. // updated if we are in mlist
  2054. if (lfs_pair_cmp(dir->pair, lpair) == 0) {
  2055. *dir = ldir;
  2056. }
  2057. // commit was successful, but may require other changes in the
  2058. // filesystem, these would normally be tail recursive, but we have
  2059. // flattened them here avoid unbounded stack usage
  2060. // need to drop?
  2061. if (state == LFS_OK_DROPPED) {
  2062. // steal state
  2063. int err = lfs_dir_getgstate(lfs, dir, &lfs->gdelta);
  2064. if (err) {
  2065. return err;
  2066. }
  2067. // steal tail, note that this can't create a recursive drop
  2068. lpair[0] = pdir.pair[0];
  2069. lpair[1] = pdir.pair[1];
  2070. lfs_pair_tole32(dir->tail);
  2071. state = lfs_dir_relocatingcommit(lfs, &pdir, lpair, LFS_MKATTRS(
  2072. {LFS_MKTAG(LFS_TYPE_TAIL + dir->split, 0x3ff, 8),
  2073. dir->tail}),
  2074. NULL);
  2075. lfs_pair_fromle32(dir->tail);
  2076. if (state < 0) {
  2077. return state;
  2078. }
  2079. ldir = pdir;
  2080. }
  2081. // need to relocate?
  2082. bool orphans = false;
  2083. while (state == LFS_OK_RELOCATED) {
  2084. LFS_DEBUG("Relocating {0x%"PRIx32", 0x%"PRIx32"} "
  2085. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  2086. lpair[0], lpair[1], ldir.pair[0], ldir.pair[1]);
  2087. state = 0;
  2088. // update internal root
  2089. if (lfs_pair_cmp(lpair, lfs->root) == 0) {
  2090. lfs->root[0] = ldir.pair[0];
  2091. lfs->root[1] = ldir.pair[1];
  2092. }
  2093. // update internally tracked dirs
  2094. for (struct lfs_mlist *d = lfs->mlist; d; d = d->next) {
  2095. if (lfs_pair_cmp(lpair, d->m.pair) == 0) {
  2096. d->m.pair[0] = ldir.pair[0];
  2097. d->m.pair[1] = ldir.pair[1];
  2098. }
  2099. if (d->type == LFS_TYPE_DIR &&
  2100. lfs_pair_cmp(lpair, ((lfs_dir_t*)d)->head) == 0) {
  2101. ((lfs_dir_t*)d)->head[0] = ldir.pair[0];
  2102. ((lfs_dir_t*)d)->head[1] = ldir.pair[1];
  2103. }
  2104. }
  2105. // find parent
  2106. lfs_stag_t tag = lfs_fs_parent(lfs, lpair, &pdir);
  2107. if (tag < 0 && tag != LFS_ERR_NOENT) {
  2108. return tag;
  2109. }
  2110. bool hasparent = (tag != LFS_ERR_NOENT);
  2111. if (tag != LFS_ERR_NOENT) {
  2112. // note that if we have a parent, we must have a pred, so this will
  2113. // always create an orphan
  2114. int err = lfs_fs_preporphans(lfs, +1);
  2115. if (err) {
  2116. return err;
  2117. }
  2118. // fix pending move in this pair? this looks like an optimization but
  2119. // is in fact _required_ since relocating may outdate the move.
  2120. uint16_t moveid = 0x3ff;
  2121. if (lfs_gstate_hasmovehere(&lfs->gstate, pdir.pair)) {
  2122. moveid = lfs_tag_id(lfs->gstate.tag);
  2123. LFS_DEBUG("Fixing move while relocating "
  2124. "{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
  2125. pdir.pair[0], pdir.pair[1], moveid);
  2126. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  2127. if (moveid < lfs_tag_id(tag)) {
  2128. tag -= LFS_MKTAG(0, 1, 0);
  2129. }
  2130. }
  2131. lfs_block_t ppair[2] = {pdir.pair[0], pdir.pair[1]};
  2132. lfs_pair_tole32(ldir.pair);
  2133. state = lfs_dir_relocatingcommit(lfs, &pdir, ppair, LFS_MKATTRS(
  2134. {LFS_MKTAG_IF(moveid != 0x3ff,
  2135. LFS_TYPE_DELETE, moveid, 0), NULL},
  2136. {tag, ldir.pair}),
  2137. NULL);
  2138. lfs_pair_fromle32(ldir.pair);
  2139. if (state < 0) {
  2140. return state;
  2141. }
  2142. if (state == LFS_OK_RELOCATED) {
  2143. lpair[0] = ppair[0];
  2144. lpair[1] = ppair[1];
  2145. ldir = pdir;
  2146. orphans = true;
  2147. continue;
  2148. }
  2149. }
  2150. // find pred
  2151. int err = lfs_fs_pred(lfs, lpair, &pdir);
  2152. if (err && err != LFS_ERR_NOENT) {
  2153. return err;
  2154. }
  2155. LFS_ASSERT(!(hasparent && err == LFS_ERR_NOENT));
  2156. // if we can't find dir, it must be new
  2157. if (err != LFS_ERR_NOENT) {
  2158. if (lfs_gstate_hasorphans(&lfs->gstate)) {
  2159. // next step, clean up orphans
  2160. err = lfs_fs_preporphans(lfs, -hasparent);
  2161. if (err) {
  2162. return err;
  2163. }
  2164. }
  2165. // fix pending move in this pair? this looks like an optimization
  2166. // but is in fact _required_ since relocating may outdate the move.
  2167. uint16_t moveid = 0x3ff;
  2168. if (lfs_gstate_hasmovehere(&lfs->gstate, pdir.pair)) {
  2169. moveid = lfs_tag_id(lfs->gstate.tag);
  2170. LFS_DEBUG("Fixing move while relocating "
  2171. "{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
  2172. pdir.pair[0], pdir.pair[1], moveid);
  2173. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  2174. }
  2175. // replace bad pair, either we clean up desync, or no desync occured
  2176. lpair[0] = pdir.pair[0];
  2177. lpair[1] = pdir.pair[1];
  2178. lfs_pair_tole32(ldir.pair);
  2179. state = lfs_dir_relocatingcommit(lfs, &pdir, lpair, LFS_MKATTRS(
  2180. {LFS_MKTAG_IF(moveid != 0x3ff,
  2181. LFS_TYPE_DELETE, moveid, 0), NULL},
  2182. {LFS_MKTAG(LFS_TYPE_TAIL + pdir.split, 0x3ff, 8),
  2183. ldir.pair}),
  2184. NULL);
  2185. lfs_pair_fromle32(ldir.pair);
  2186. if (state < 0) {
  2187. return state;
  2188. }
  2189. ldir = pdir;
  2190. }
  2191. }
  2192. return orphans ? LFS_OK_ORPHANED : 0;
  2193. }
  2194. #endif
  2195. #ifndef LFS_READONLY
  2196. static int lfs_dir_commit(lfs_t *lfs, lfs_mdir_t *dir,
  2197. const struct lfs_mattr *attrs, int attrcount) {
  2198. int orphans = lfs_dir_orphaningcommit(lfs, dir, attrs, attrcount);
  2199. if (orphans < 0) {
  2200. return orphans;
  2201. }
  2202. if (orphans) {
  2203. // make sure we've removed all orphans, this is a noop if there
  2204. // are none, but if we had nested blocks failures we may have
  2205. // created some
  2206. int err = lfs_fs_deorphan(lfs, false);
  2207. if (err) {
  2208. return err;
  2209. }
  2210. }
  2211. return 0;
  2212. }
  2213. #endif
  2214. /// Top level directory operations ///
  2215. #ifndef LFS_READONLY
  2216. static int lfs_rawmkdir(lfs_t *lfs, const char *path) {
  2217. // deorphan if we haven't yet, needed at most once after poweron
  2218. int err = lfs_fs_forceconsistency(lfs);
  2219. if (err) {
  2220. return err;
  2221. }
  2222. struct lfs_mlist cwd;
  2223. cwd.next = lfs->mlist;
  2224. uint16_t id;
  2225. err = lfs_dir_find(lfs, &cwd.m, &path, &id);
  2226. if (!(err == LFS_ERR_NOENT && id != 0x3ff)) {
  2227. return (err < 0) ? err : LFS_ERR_EXIST;
  2228. }
  2229. // check that name fits
  2230. lfs_size_t nlen = strlen(path);
  2231. if (nlen > lfs->name_max) {
  2232. return LFS_ERR_NAMETOOLONG;
  2233. }
  2234. // build up new directory
  2235. lfs_alloc_ack(lfs);
  2236. lfs_mdir_t dir;
  2237. err = lfs_dir_alloc(lfs, &dir);
  2238. if (err) {
  2239. return err;
  2240. }
  2241. // find end of list
  2242. lfs_mdir_t pred = cwd.m;
  2243. while (pred.split) {
  2244. err = lfs_dir_fetch(lfs, &pred, pred.tail);
  2245. if (err) {
  2246. return err;
  2247. }
  2248. }
  2249. // setup dir
  2250. lfs_pair_tole32(pred.tail);
  2251. err = lfs_dir_commit(lfs, &dir, LFS_MKATTRS(
  2252. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), pred.tail}));
  2253. lfs_pair_fromle32(pred.tail);
  2254. if (err) {
  2255. return err;
  2256. }
  2257. // current block not end of list?
  2258. if (cwd.m.split) {
  2259. // update tails, this creates a desync
  2260. err = lfs_fs_preporphans(lfs, +1);
  2261. if (err) {
  2262. return err;
  2263. }
  2264. // it's possible our predecessor has to be relocated, and if
  2265. // our parent is our predecessor's predecessor, this could have
  2266. // caused our parent to go out of date, fortunately we can hook
  2267. // ourselves into littlefs to catch this
  2268. cwd.type = 0;
  2269. cwd.id = 0;
  2270. lfs->mlist = &cwd;
  2271. lfs_pair_tole32(dir.pair);
  2272. err = lfs_dir_commit(lfs, &pred, LFS_MKATTRS(
  2273. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir.pair}));
  2274. lfs_pair_fromle32(dir.pair);
  2275. if (err) {
  2276. lfs->mlist = cwd.next;
  2277. return err;
  2278. }
  2279. lfs->mlist = cwd.next;
  2280. err = lfs_fs_preporphans(lfs, -1);
  2281. if (err) {
  2282. return err;
  2283. }
  2284. }
  2285. // now insert into our parent block
  2286. lfs_pair_tole32(dir.pair);
  2287. err = lfs_dir_commit(lfs, &cwd.m, LFS_MKATTRS(
  2288. {LFS_MKTAG(LFS_TYPE_CREATE, id, 0), NULL},
  2289. {LFS_MKTAG(LFS_TYPE_DIR, id, nlen), path},
  2290. {LFS_MKTAG(LFS_TYPE_DIRSTRUCT, id, 8), dir.pair},
  2291. {LFS_MKTAG_IF(!cwd.m.split,
  2292. LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir.pair}));
  2293. lfs_pair_fromle32(dir.pair);
  2294. if (err) {
  2295. return err;
  2296. }
  2297. return 0;
  2298. }
  2299. #endif
  2300. static int lfs_dir_rawopen(lfs_t *lfs, lfs_dir_t *dir, const char *path) {
  2301. lfs_stag_t tag = lfs_dir_find(lfs, &dir->m, &path, NULL);
  2302. if (tag < 0) {
  2303. return tag;
  2304. }
  2305. if (lfs_tag_type3(tag) != LFS_TYPE_DIR) {
  2306. return LFS_ERR_NOTDIR;
  2307. }
  2308. lfs_block_t pair[2];
  2309. if (lfs_tag_id(tag) == 0x3ff) {
  2310. // handle root dir separately
  2311. pair[0] = lfs->root[0];
  2312. pair[1] = lfs->root[1];
  2313. } else {
  2314. // get dir pair from parent
  2315. lfs_stag_t res = lfs_dir_get(lfs, &dir->m, LFS_MKTAG(0x700, 0x3ff, 0),
  2316. LFS_MKTAG(LFS_TYPE_STRUCT, lfs_tag_id(tag), 8), pair);
  2317. if (res < 0) {
  2318. return res;
  2319. }
  2320. lfs_pair_fromle32(pair);
  2321. }
  2322. // fetch first pair
  2323. int err = lfs_dir_fetch(lfs, &dir->m, pair);
  2324. if (err) {
  2325. return err;
  2326. }
  2327. // setup entry
  2328. dir->head[0] = dir->m.pair[0];
  2329. dir->head[1] = dir->m.pair[1];
  2330. dir->id = 0;
  2331. dir->pos = 0;
  2332. // add to list of mdirs
  2333. dir->type = LFS_TYPE_DIR;
  2334. lfs_mlist_append(lfs, (struct lfs_mlist *)dir);
  2335. return 0;
  2336. }
  2337. static int lfs_dir_rawclose(lfs_t *lfs, lfs_dir_t *dir) {
  2338. // remove from list of mdirs
  2339. lfs_mlist_remove(lfs, (struct lfs_mlist *)dir);
  2340. return 0;
  2341. }
  2342. static int lfs_dir_rawread(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info) {
  2343. memset(info, 0, sizeof(*info));
  2344. // special offset for '.' and '..'
  2345. if (dir->pos == 0) {
  2346. info->type = LFS_TYPE_DIR;
  2347. strcpy(info->name, ".");
  2348. dir->pos += 1;
  2349. return true;
  2350. } else if (dir->pos == 1) {
  2351. info->type = LFS_TYPE_DIR;
  2352. strcpy(info->name, "..");
  2353. dir->pos += 1;
  2354. return true;
  2355. }
  2356. while (true) {
  2357. if (dir->id == dir->m.count) {
  2358. if (!dir->m.split) {
  2359. return false;
  2360. }
  2361. int err = lfs_dir_fetch(lfs, &dir->m, dir->m.tail);
  2362. if (err) {
  2363. return err;
  2364. }
  2365. dir->id = 0;
  2366. }
  2367. int err = lfs_dir_getinfo(lfs, &dir->m, dir->id, info);
  2368. if (err && err != LFS_ERR_NOENT) {
  2369. return err;
  2370. }
  2371. dir->id += 1;
  2372. if (err != LFS_ERR_NOENT) {
  2373. break;
  2374. }
  2375. }
  2376. dir->pos += 1;
  2377. return true;
  2378. }
  2379. static int lfs_dir_rawseek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off) {
  2380. // simply walk from head dir
  2381. int err = lfs_dir_rawrewind(lfs, dir);
  2382. if (err) {
  2383. return err;
  2384. }
  2385. // first two for ./..
  2386. dir->pos = lfs_min(2, off);
  2387. off -= dir->pos;
  2388. // skip superblock entry
  2389. dir->id = (off > 0 && lfs_pair_cmp(dir->head, lfs->root) == 0);
  2390. while (off > 0) {
  2391. if (dir->id == dir->m.count) {
  2392. if (!dir->m.split) {
  2393. return LFS_ERR_INVAL;
  2394. }
  2395. err = lfs_dir_fetch(lfs, &dir->m, dir->m.tail);
  2396. if (err) {
  2397. return err;
  2398. }
  2399. dir->id = 0;
  2400. }
  2401. int diff = lfs_min(dir->m.count - dir->id, off);
  2402. dir->id += diff;
  2403. dir->pos += diff;
  2404. off -= diff;
  2405. }
  2406. return 0;
  2407. }
  2408. static lfs_soff_t lfs_dir_rawtell(lfs_t *lfs, lfs_dir_t *dir) {
  2409. (void)lfs;
  2410. return dir->pos;
  2411. }
  2412. static int lfs_dir_rawrewind(lfs_t *lfs, lfs_dir_t *dir) {
  2413. // reload the head dir
  2414. int err = lfs_dir_fetch(lfs, &dir->m, dir->head);
  2415. if (err) {
  2416. return err;
  2417. }
  2418. dir->id = 0;
  2419. dir->pos = 0;
  2420. return 0;
  2421. }
  2422. /// File index list operations ///
  2423. static int lfs_ctz_index(lfs_t *lfs, lfs_off_t *off) {
  2424. lfs_off_t size = *off;
  2425. lfs_off_t b = lfs->cfg->block_size - 2*4;
  2426. lfs_off_t i = size / b;
  2427. if (i == 0) {
  2428. return 0;
  2429. }
  2430. i = (size - 4*(lfs_popc(i-1)+2)) / b;
  2431. *off = size - b*i - 4*lfs_popc(i);
  2432. return i;
  2433. }
  2434. static int lfs_ctz_find(lfs_t *lfs,
  2435. const lfs_cache_t *pcache, lfs_cache_t *rcache,
  2436. lfs_block_t head, lfs_size_t size,
  2437. lfs_size_t pos, lfs_block_t *block, lfs_off_t *off) {
  2438. if (size == 0) {
  2439. *block = LFS_BLOCK_NULL;
  2440. *off = 0;
  2441. return 0;
  2442. }
  2443. lfs_off_t current = lfs_ctz_index(lfs, &(lfs_off_t){size-1});
  2444. lfs_off_t target = lfs_ctz_index(lfs, &pos);
  2445. while (current > target) {
  2446. lfs_size_t skip = lfs_min(
  2447. lfs_npw2(current-target+1) - 1,
  2448. lfs_ctz(current));
  2449. int err = lfs_bd_read(lfs,
  2450. pcache, rcache, sizeof(head),
  2451. head, 4*skip, &head, sizeof(head));
  2452. head = lfs_fromle32(head);
  2453. if (err) {
  2454. return err;
  2455. }
  2456. current -= 1 << skip;
  2457. }
  2458. *block = head;
  2459. *off = pos;
  2460. return 0;
  2461. }
  2462. #ifndef LFS_READONLY
  2463. static int lfs_ctz_extend(lfs_t *lfs,
  2464. lfs_cache_t *pcache, lfs_cache_t *rcache,
  2465. lfs_block_t head, lfs_size_t size,
  2466. lfs_block_t *block, lfs_off_t *off) {
  2467. while (true) {
  2468. // go ahead and grab a block
  2469. lfs_block_t nblock;
  2470. int err = lfs_alloc(lfs, &nblock);
  2471. if (err) {
  2472. return err;
  2473. }
  2474. {
  2475. err = lfs_bd_erase(lfs, nblock);
  2476. if (err) {
  2477. if (err == LFS_ERR_CORRUPT) {
  2478. goto relocate;
  2479. }
  2480. return err;
  2481. }
  2482. if (size == 0) {
  2483. *block = nblock;
  2484. *off = 0;
  2485. return 0;
  2486. }
  2487. lfs_size_t noff = size - 1;
  2488. lfs_off_t index = lfs_ctz_index(lfs, &noff);
  2489. noff = noff + 1;
  2490. // just copy out the last block if it is incomplete
  2491. if (noff != lfs->cfg->block_size) {
  2492. for (lfs_off_t i = 0; i < noff; i++) {
  2493. uint8_t data;
  2494. err = lfs_bd_read(lfs,
  2495. NULL, rcache, noff-i,
  2496. head, i, &data, 1);
  2497. if (err) {
  2498. return err;
  2499. }
  2500. err = lfs_bd_prog(lfs,
  2501. pcache, rcache, true,
  2502. nblock, i, &data, 1);
  2503. if (err) {
  2504. if (err == LFS_ERR_CORRUPT) {
  2505. goto relocate;
  2506. }
  2507. return err;
  2508. }
  2509. }
  2510. *block = nblock;
  2511. *off = noff;
  2512. return 0;
  2513. }
  2514. // append block
  2515. index += 1;
  2516. lfs_size_t skips = lfs_ctz(index) + 1;
  2517. lfs_block_t nhead = head;
  2518. for (lfs_off_t i = 0; i < skips; i++) {
  2519. nhead = lfs_tole32(nhead);
  2520. err = lfs_bd_prog(lfs, pcache, rcache, true,
  2521. nblock, 4*i, &nhead, 4);
  2522. nhead = lfs_fromle32(nhead);
  2523. if (err) {
  2524. if (err == LFS_ERR_CORRUPT) {
  2525. goto relocate;
  2526. }
  2527. return err;
  2528. }
  2529. if (i != skips-1) {
  2530. err = lfs_bd_read(lfs,
  2531. NULL, rcache, sizeof(nhead),
  2532. nhead, 4*i, &nhead, sizeof(nhead));
  2533. nhead = lfs_fromle32(nhead);
  2534. if (err) {
  2535. return err;
  2536. }
  2537. }
  2538. }
  2539. *block = nblock;
  2540. *off = 4*skips;
  2541. return 0;
  2542. }
  2543. relocate:
  2544. LFS_DEBUG("Bad block at 0x%"PRIx32, nblock);
  2545. // just clear cache and try a new block
  2546. lfs_cache_drop(lfs, pcache);
  2547. }
  2548. }
  2549. #endif
  2550. static int lfs_ctz_traverse(lfs_t *lfs,
  2551. const lfs_cache_t *pcache, lfs_cache_t *rcache,
  2552. lfs_block_t head, lfs_size_t size,
  2553. int (*cb)(void*, lfs_block_t), void *data) {
  2554. if (size == 0) {
  2555. return 0;
  2556. }
  2557. lfs_off_t index = lfs_ctz_index(lfs, &(lfs_off_t){size-1});
  2558. while (true) {
  2559. int err = cb(data, head);
  2560. if (err) {
  2561. return err;
  2562. }
  2563. if (index == 0) {
  2564. return 0;
  2565. }
  2566. lfs_block_t heads[2];
  2567. int count = 2 - (index & 1);
  2568. err = lfs_bd_read(lfs,
  2569. pcache, rcache, count*sizeof(head),
  2570. head, 0, &heads, count*sizeof(head));
  2571. heads[0] = lfs_fromle32(heads[0]);
  2572. heads[1] = lfs_fromle32(heads[1]);
  2573. if (err) {
  2574. return err;
  2575. }
  2576. for (int i = 0; i < count-1; i++) {
  2577. err = cb(data, heads[i]);
  2578. if (err) {
  2579. return err;
  2580. }
  2581. }
  2582. head = heads[count-1];
  2583. index -= count;
  2584. }
  2585. }
  2586. /// Top level file operations ///
  2587. static int lfs_file_rawopencfg(lfs_t *lfs, lfs_file_t *file,
  2588. const char *path, int flags,
  2589. const struct lfs_file_config *cfg) {
  2590. #ifndef LFS_READONLY
  2591. // deorphan if we haven't yet, needed at most once after poweron
  2592. if ((flags & LFS_O_WRONLY) == LFS_O_WRONLY) {
  2593. int err = lfs_fs_forceconsistency(lfs);
  2594. if (err) {
  2595. return err;
  2596. }
  2597. }
  2598. #else
  2599. LFS_ASSERT((flags & LFS_O_RDONLY) == LFS_O_RDONLY);
  2600. #endif
  2601. // setup simple file details
  2602. int err;
  2603. file->cfg = cfg;
  2604. file->flags = flags;
  2605. file->pos = 0;
  2606. file->off = 0;
  2607. file->cache.buffer = NULL;
  2608. // allocate entry for file if it doesn't exist
  2609. lfs_stag_t tag = lfs_dir_find(lfs, &file->m, &path, &file->id);
  2610. if (tag < 0 && !(tag == LFS_ERR_NOENT && file->id != 0x3ff)) {
  2611. err = tag;
  2612. goto cleanup;
  2613. }
  2614. // get id, add to list of mdirs to catch update changes
  2615. file->type = LFS_TYPE_REG;
  2616. lfs_mlist_append(lfs, (struct lfs_mlist *)file);
  2617. #ifdef LFS_READONLY
  2618. if (tag == LFS_ERR_NOENT) {
  2619. err = LFS_ERR_NOENT;
  2620. goto cleanup;
  2621. #else
  2622. if (tag == LFS_ERR_NOENT) {
  2623. if (!(flags & LFS_O_CREAT)) {
  2624. err = LFS_ERR_NOENT;
  2625. goto cleanup;
  2626. }
  2627. // check that name fits
  2628. lfs_size_t nlen = strlen(path);
  2629. if (nlen > lfs->name_max) {
  2630. err = LFS_ERR_NAMETOOLONG;
  2631. goto cleanup;
  2632. }
  2633. // get next slot and create entry to remember name
  2634. err = lfs_dir_commit(lfs, &file->m, LFS_MKATTRS(
  2635. {LFS_MKTAG(LFS_TYPE_CREATE, file->id, 0), NULL},
  2636. {LFS_MKTAG(LFS_TYPE_REG, file->id, nlen), path},
  2637. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0), NULL}));
  2638. // it may happen that the file name doesn't fit in the metadata blocks, e.g., a 256 byte file name will
  2639. // not fit in a 128 byte block.
  2640. err = (err == LFS_ERR_NOSPC) ? LFS_ERR_NAMETOOLONG : err;
  2641. if (err) {
  2642. goto cleanup;
  2643. }
  2644. tag = LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, 0);
  2645. } else if (flags & LFS_O_EXCL) {
  2646. err = LFS_ERR_EXIST;
  2647. goto cleanup;
  2648. #endif
  2649. } else if (lfs_tag_type3(tag) != LFS_TYPE_REG) {
  2650. err = LFS_ERR_ISDIR;
  2651. goto cleanup;
  2652. #ifndef LFS_READONLY
  2653. } else if (flags & LFS_O_TRUNC) {
  2654. // truncate if requested
  2655. tag = LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0);
  2656. file->flags |= LFS_F_DIRTY;
  2657. #endif
  2658. } else {
  2659. // try to load what's on disk, if it's inlined we'll fix it later
  2660. tag = lfs_dir_get(lfs, &file->m, LFS_MKTAG(0x700, 0x3ff, 0),
  2661. LFS_MKTAG(LFS_TYPE_STRUCT, file->id, 8), &file->ctz);
  2662. if (tag < 0) {
  2663. err = tag;
  2664. goto cleanup;
  2665. }
  2666. lfs_ctz_fromle32(&file->ctz);
  2667. }
  2668. // fetch attrs
  2669. for (unsigned i = 0; i < file->cfg->attr_count; i++) {
  2670. // if opened for read / read-write operations
  2671. if ((file->flags & LFS_O_RDONLY) == LFS_O_RDONLY) {
  2672. lfs_stag_t res = lfs_dir_get(lfs, &file->m,
  2673. LFS_MKTAG(0x7ff, 0x3ff, 0),
  2674. LFS_MKTAG(LFS_TYPE_USERATTR + file->cfg->attrs[i].type,
  2675. file->id, file->cfg->attrs[i].size),
  2676. file->cfg->attrs[i].buffer);
  2677. if (res < 0 && res != LFS_ERR_NOENT) {
  2678. err = res;
  2679. goto cleanup;
  2680. }
  2681. }
  2682. #ifndef LFS_READONLY
  2683. // if opened for write / read-write operations
  2684. if ((file->flags & LFS_O_WRONLY) == LFS_O_WRONLY) {
  2685. if (file->cfg->attrs[i].size > lfs->attr_max) {
  2686. err = LFS_ERR_NOSPC;
  2687. goto cleanup;
  2688. }
  2689. file->flags |= LFS_F_DIRTY;
  2690. }
  2691. #endif
  2692. }
  2693. // allocate buffer if needed
  2694. if (file->cfg->buffer) {
  2695. file->cache.buffer = file->cfg->buffer;
  2696. } else {
  2697. file->cache.buffer = lfs_malloc(lfs->cfg->cache_size);
  2698. if (!file->cache.buffer) {
  2699. err = LFS_ERR_NOMEM;
  2700. goto cleanup;
  2701. }
  2702. }
  2703. // zero to avoid information leak
  2704. lfs_cache_zero(lfs, &file->cache);
  2705. if (lfs_tag_type3(tag) == LFS_TYPE_INLINESTRUCT) {
  2706. // load inline files
  2707. file->ctz.head = LFS_BLOCK_INLINE;
  2708. file->ctz.size = lfs_tag_size(tag);
  2709. file->flags |= LFS_F_INLINE;
  2710. file->cache.block = file->ctz.head;
  2711. file->cache.off = 0;
  2712. file->cache.size = lfs->cfg->cache_size;
  2713. // don't always read (may be new/trunc file)
  2714. if (file->ctz.size > 0) {
  2715. lfs_stag_t res = lfs_dir_get(lfs, &file->m,
  2716. LFS_MKTAG(0x700, 0x3ff, 0),
  2717. LFS_MKTAG(LFS_TYPE_STRUCT, file->id,
  2718. lfs_min(file->cache.size, 0x3fe)),
  2719. file->cache.buffer);
  2720. if (res < 0) {
  2721. err = res;
  2722. goto cleanup;
  2723. }
  2724. }
  2725. }
  2726. return 0;
  2727. cleanup:
  2728. // clean up lingering resources
  2729. #ifndef LFS_READONLY
  2730. file->flags |= LFS_F_ERRED;
  2731. #endif
  2732. lfs_file_rawclose(lfs, file);
  2733. return err;
  2734. }
  2735. #ifndef LFS_NO_MALLOC
  2736. static int lfs_file_rawopen(lfs_t *lfs, lfs_file_t *file,
  2737. const char *path, int flags) {
  2738. static const struct lfs_file_config defaults = {0};
  2739. int err = lfs_file_rawopencfg(lfs, file, path, flags, &defaults);
  2740. return err;
  2741. }
  2742. #endif
  2743. static int lfs_file_rawclose(lfs_t *lfs, lfs_file_t *file) {
  2744. #ifndef LFS_READONLY
  2745. int err = lfs_file_rawsync(lfs, file);
  2746. #else
  2747. int err = 0;
  2748. #endif
  2749. // remove from list of mdirs
  2750. lfs_mlist_remove(lfs, (struct lfs_mlist*)file);
  2751. // clean up memory
  2752. if (!file->cfg->buffer) {
  2753. lfs_free(file->cache.buffer);
  2754. }
  2755. return err;
  2756. }
  2757. #ifndef LFS_READONLY
  2758. static int lfs_file_relocate(lfs_t *lfs, lfs_file_t *file) {
  2759. while (true) {
  2760. // just relocate what exists into new block
  2761. lfs_block_t nblock;
  2762. int err = lfs_alloc(lfs, &nblock);
  2763. if (err) {
  2764. return err;
  2765. }
  2766. err = lfs_bd_erase(lfs, nblock);
  2767. if (err) {
  2768. if (err == LFS_ERR_CORRUPT) {
  2769. goto relocate;
  2770. }
  2771. return err;
  2772. }
  2773. // either read from dirty cache or disk
  2774. for (lfs_off_t i = 0; i < file->off; i++) {
  2775. uint8_t data;
  2776. if (file->flags & LFS_F_INLINE) {
  2777. err = lfs_dir_getread(lfs, &file->m,
  2778. // note we evict inline files before they can be dirty
  2779. NULL, &file->cache, file->off-i,
  2780. LFS_MKTAG(0xfff, 0x1ff, 0),
  2781. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0),
  2782. i, &data, 1);
  2783. if (err) {
  2784. return err;
  2785. }
  2786. } else {
  2787. err = lfs_bd_read(lfs,
  2788. &file->cache, &lfs->rcache, file->off-i,
  2789. file->block, i, &data, 1);
  2790. if (err) {
  2791. return err;
  2792. }
  2793. }
  2794. err = lfs_bd_prog(lfs,
  2795. &lfs->pcache, &lfs->rcache, true,
  2796. nblock, i, &data, 1);
  2797. if (err) {
  2798. if (err == LFS_ERR_CORRUPT) {
  2799. goto relocate;
  2800. }
  2801. return err;
  2802. }
  2803. }
  2804. // copy over new state of file
  2805. memcpy(file->cache.buffer, lfs->pcache.buffer, lfs->cfg->cache_size);
  2806. file->cache.block = lfs->pcache.block;
  2807. file->cache.off = lfs->pcache.off;
  2808. file->cache.size = lfs->pcache.size;
  2809. lfs_cache_zero(lfs, &lfs->pcache);
  2810. file->block = nblock;
  2811. file->flags |= LFS_F_WRITING;
  2812. return 0;
  2813. relocate:
  2814. LFS_DEBUG("Bad block at 0x%"PRIx32, nblock);
  2815. // just clear cache and try a new block
  2816. lfs_cache_drop(lfs, &lfs->pcache);
  2817. }
  2818. }
  2819. #endif
  2820. #ifndef LFS_READONLY
  2821. static int lfs_file_outline(lfs_t *lfs, lfs_file_t *file) {
  2822. file->off = file->pos;
  2823. lfs_alloc_ack(lfs);
  2824. int err = lfs_file_relocate(lfs, file);
  2825. if (err) {
  2826. return err;
  2827. }
  2828. file->flags &= ~LFS_F_INLINE;
  2829. return 0;
  2830. }
  2831. #endif
  2832. static int lfs_file_flush(lfs_t *lfs, lfs_file_t *file) {
  2833. if (file->flags & LFS_F_READING) {
  2834. if (!(file->flags & LFS_F_INLINE)) {
  2835. lfs_cache_drop(lfs, &file->cache);
  2836. }
  2837. file->flags &= ~LFS_F_READING;
  2838. }
  2839. #ifndef LFS_READONLY
  2840. if (file->flags & LFS_F_WRITING) {
  2841. lfs_off_t pos = file->pos;
  2842. if (!(file->flags & LFS_F_INLINE)) {
  2843. // copy over anything after current branch
  2844. lfs_file_t orig = {
  2845. .ctz.head = file->ctz.head,
  2846. .ctz.size = file->ctz.size,
  2847. .flags = LFS_O_RDONLY,
  2848. .pos = file->pos,
  2849. .cache = lfs->rcache,
  2850. };
  2851. lfs_cache_drop(lfs, &lfs->rcache);
  2852. while (file->pos < file->ctz.size) {
  2853. // copy over a byte at a time, leave it up to caching
  2854. // to make this efficient
  2855. uint8_t data;
  2856. lfs_ssize_t res = lfs_file_flushedread(lfs, &orig, &data, 1);
  2857. if (res < 0) {
  2858. return res;
  2859. }
  2860. res = lfs_file_flushedwrite(lfs, file, &data, 1);
  2861. if (res < 0) {
  2862. return res;
  2863. }
  2864. // keep our reference to the rcache in sync
  2865. if (lfs->rcache.block != LFS_BLOCK_NULL) {
  2866. lfs_cache_drop(lfs, &orig.cache);
  2867. lfs_cache_drop(lfs, &lfs->rcache);
  2868. }
  2869. }
  2870. // write out what we have
  2871. while (true) {
  2872. int err = lfs_bd_flush(lfs, &file->cache, &lfs->rcache, true);
  2873. if (err) {
  2874. if (err == LFS_ERR_CORRUPT) {
  2875. goto relocate;
  2876. }
  2877. return err;
  2878. }
  2879. break;
  2880. relocate:
  2881. LFS_DEBUG("Bad block at 0x%"PRIx32, file->block);
  2882. err = lfs_file_relocate(lfs, file);
  2883. if (err) {
  2884. return err;
  2885. }
  2886. }
  2887. } else {
  2888. file->pos = lfs_max(file->pos, file->ctz.size);
  2889. }
  2890. // actual file updates
  2891. file->ctz.head = file->block;
  2892. file->ctz.size = file->pos;
  2893. file->flags &= ~LFS_F_WRITING;
  2894. file->flags |= LFS_F_DIRTY;
  2895. file->pos = pos;
  2896. }
  2897. #endif
  2898. return 0;
  2899. }
  2900. #ifndef LFS_READONLY
  2901. static int lfs_file_rawsync(lfs_t *lfs, lfs_file_t *file) {
  2902. if (file->flags & LFS_F_ERRED) {
  2903. // it's not safe to do anything if our file errored
  2904. return 0;
  2905. }
  2906. int err = lfs_file_flush(lfs, file);
  2907. if (err) {
  2908. file->flags |= LFS_F_ERRED;
  2909. return err;
  2910. }
  2911. if ((file->flags & LFS_F_DIRTY) &&
  2912. !lfs_pair_isnull(file->m.pair)) {
  2913. // update dir entry
  2914. uint16_t type;
  2915. const void *buffer;
  2916. lfs_size_t size;
  2917. struct lfs_ctz ctz;
  2918. if (file->flags & LFS_F_INLINE) {
  2919. // inline the whole file
  2920. type = LFS_TYPE_INLINESTRUCT;
  2921. buffer = file->cache.buffer;
  2922. size = file->ctz.size;
  2923. } else {
  2924. // update the ctz reference
  2925. type = LFS_TYPE_CTZSTRUCT;
  2926. // copy ctz so alloc will work during a relocate
  2927. ctz = file->ctz;
  2928. lfs_ctz_tole32(&ctz);
  2929. buffer = &ctz;
  2930. size = sizeof(ctz);
  2931. }
  2932. // commit file data and attributes
  2933. err = lfs_dir_commit(lfs, &file->m, LFS_MKATTRS(
  2934. {LFS_MKTAG(type, file->id, size), buffer},
  2935. {LFS_MKTAG(LFS_FROM_USERATTRS, file->id,
  2936. file->cfg->attr_count), file->cfg->attrs}));
  2937. if (err) {
  2938. file->flags |= LFS_F_ERRED;
  2939. return err;
  2940. }
  2941. file->flags &= ~LFS_F_DIRTY;
  2942. }
  2943. return 0;
  2944. }
  2945. #endif
  2946. static lfs_ssize_t lfs_file_flushedread(lfs_t *lfs, lfs_file_t *file,
  2947. void *buffer, lfs_size_t size) {
  2948. uint8_t *data = buffer;
  2949. lfs_size_t nsize = size;
  2950. if (file->pos >= file->ctz.size) {
  2951. // eof if past end
  2952. return 0;
  2953. }
  2954. size = lfs_min(size, file->ctz.size - file->pos);
  2955. nsize = size;
  2956. while (nsize > 0) {
  2957. // check if we need a new block
  2958. if (!(file->flags & LFS_F_READING) ||
  2959. file->off == lfs->cfg->block_size) {
  2960. if (!(file->flags & LFS_F_INLINE)) {
  2961. int err = lfs_ctz_find(lfs, NULL, &file->cache,
  2962. file->ctz.head, file->ctz.size,
  2963. file->pos, &file->block, &file->off);
  2964. if (err) {
  2965. return err;
  2966. }
  2967. } else {
  2968. file->block = LFS_BLOCK_INLINE;
  2969. file->off = file->pos;
  2970. }
  2971. file->flags |= LFS_F_READING;
  2972. }
  2973. // read as much as we can in current block
  2974. lfs_size_t diff = lfs_min(nsize, lfs->cfg->block_size - file->off);
  2975. if (file->flags & LFS_F_INLINE) {
  2976. int err = lfs_dir_getread(lfs, &file->m,
  2977. NULL, &file->cache, lfs->cfg->block_size,
  2978. LFS_MKTAG(0xfff, 0x1ff, 0),
  2979. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0),
  2980. file->off, data, diff);
  2981. if (err) {
  2982. return err;
  2983. }
  2984. } else {
  2985. int err = lfs_bd_read(lfs,
  2986. NULL, &file->cache, lfs->cfg->block_size,
  2987. file->block, file->off, data, diff);
  2988. if (err) {
  2989. return err;
  2990. }
  2991. }
  2992. file->pos += diff;
  2993. file->off += diff;
  2994. data += diff;
  2995. nsize -= diff;
  2996. }
  2997. return size;
  2998. }
  2999. static lfs_ssize_t lfs_file_rawread(lfs_t *lfs, lfs_file_t *file,
  3000. void *buffer, lfs_size_t size) {
  3001. LFS_ASSERT((file->flags & LFS_O_RDONLY) == LFS_O_RDONLY);
  3002. #ifndef LFS_READONLY
  3003. if (file->flags & LFS_F_WRITING) {
  3004. // flush out any writes
  3005. int err = lfs_file_flush(lfs, file);
  3006. if (err) {
  3007. return err;
  3008. }
  3009. }
  3010. #endif
  3011. return lfs_file_flushedread(lfs, file, buffer, size);
  3012. }
  3013. #ifndef LFS_READONLY
  3014. static lfs_ssize_t lfs_file_flushedwrite(lfs_t *lfs, lfs_file_t *file,
  3015. const void *buffer, lfs_size_t size) {
  3016. const uint8_t *data = buffer;
  3017. lfs_size_t nsize = size;
  3018. if ((file->flags & LFS_F_INLINE) &&
  3019. lfs_max(file->pos+nsize, file->ctz.size) >
  3020. lfs_min(0x3fe, lfs_min(
  3021. lfs->cfg->cache_size,
  3022. (lfs->cfg->metadata_max ?
  3023. lfs->cfg->metadata_max : lfs->cfg->block_size) / 8))) {
  3024. // inline file doesn't fit anymore
  3025. int err = lfs_file_outline(lfs, file);
  3026. if (err) {
  3027. file->flags |= LFS_F_ERRED;
  3028. return err;
  3029. }
  3030. }
  3031. while (nsize > 0) {
  3032. // check if we need a new block
  3033. if (!(file->flags & LFS_F_WRITING) ||
  3034. file->off == lfs->cfg->block_size) {
  3035. if (!(file->flags & LFS_F_INLINE)) {
  3036. if (!(file->flags & LFS_F_WRITING) && file->pos > 0) {
  3037. // find out which block we're extending from
  3038. int err = lfs_ctz_find(lfs, NULL, &file->cache,
  3039. file->ctz.head, file->ctz.size,
  3040. file->pos-1, &file->block, &(lfs_off_t){0});
  3041. if (err) {
  3042. file->flags |= LFS_F_ERRED;
  3043. return err;
  3044. }
  3045. // mark cache as dirty since we may have read data into it
  3046. lfs_cache_zero(lfs, &file->cache);
  3047. }
  3048. // extend file with new blocks
  3049. lfs_alloc_ack(lfs);
  3050. int err = lfs_ctz_extend(lfs, &file->cache, &lfs->rcache,
  3051. file->block, file->pos,
  3052. &file->block, &file->off);
  3053. if (err) {
  3054. file->flags |= LFS_F_ERRED;
  3055. return err;
  3056. }
  3057. } else {
  3058. file->block = LFS_BLOCK_INLINE;
  3059. file->off = file->pos;
  3060. }
  3061. file->flags |= LFS_F_WRITING;
  3062. }
  3063. // program as much as we can in current block
  3064. lfs_size_t diff = lfs_min(nsize, lfs->cfg->block_size - file->off);
  3065. while (true) {
  3066. int err = lfs_bd_prog(lfs, &file->cache, &lfs->rcache, true,
  3067. file->block, file->off, data, diff);
  3068. if (err) {
  3069. if (err == LFS_ERR_CORRUPT) {
  3070. goto relocate;
  3071. }
  3072. file->flags |= LFS_F_ERRED;
  3073. return err;
  3074. }
  3075. break;
  3076. relocate:
  3077. err = lfs_file_relocate(lfs, file);
  3078. if (err) {
  3079. file->flags |= LFS_F_ERRED;
  3080. return err;
  3081. }
  3082. }
  3083. file->pos += diff;
  3084. file->off += diff;
  3085. data += diff;
  3086. nsize -= diff;
  3087. lfs_alloc_ack(lfs);
  3088. }
  3089. return size;
  3090. }
  3091. static lfs_ssize_t lfs_file_rawwrite(lfs_t *lfs, lfs_file_t *file,
  3092. const void *buffer, lfs_size_t size) {
  3093. LFS_ASSERT((file->flags & LFS_O_WRONLY) == LFS_O_WRONLY);
  3094. if (file->flags & LFS_F_READING) {
  3095. // drop any reads
  3096. int err = lfs_file_flush(lfs, file);
  3097. if (err) {
  3098. return err;
  3099. }
  3100. }
  3101. if ((file->flags & LFS_O_APPEND) && file->pos < file->ctz.size) {
  3102. file->pos = file->ctz.size;
  3103. }
  3104. if (file->pos + size > lfs->file_max) {
  3105. // Larger than file limit?
  3106. return LFS_ERR_FBIG;
  3107. }
  3108. if (!(file->flags & LFS_F_WRITING) && file->pos > file->ctz.size) {
  3109. // fill with zeros
  3110. lfs_off_t pos = file->pos;
  3111. file->pos = file->ctz.size;
  3112. while (file->pos < pos) {
  3113. lfs_ssize_t res = lfs_file_flushedwrite(lfs, file, &(uint8_t){0}, 1);
  3114. if (res < 0) {
  3115. return res;
  3116. }
  3117. }
  3118. }
  3119. lfs_ssize_t nsize = lfs_file_flushedwrite(lfs, file, buffer, size);
  3120. if (nsize < 0) {
  3121. return nsize;
  3122. }
  3123. file->flags &= ~LFS_F_ERRED;
  3124. return nsize;
  3125. }
  3126. #endif
  3127. static lfs_soff_t lfs_file_rawseek(lfs_t *lfs, lfs_file_t *file,
  3128. lfs_soff_t off, int whence) {
  3129. // find new pos
  3130. lfs_off_t npos = file->pos;
  3131. if (whence == LFS_SEEK_SET) {
  3132. npos = off;
  3133. } else if (whence == LFS_SEEK_CUR) {
  3134. if ((lfs_soff_t)file->pos + off < 0) {
  3135. return LFS_ERR_INVAL;
  3136. } else {
  3137. npos = file->pos + off;
  3138. }
  3139. } else if (whence == LFS_SEEK_END) {
  3140. lfs_soff_t res = lfs_file_rawsize(lfs, file) + off;
  3141. if (res < 0) {
  3142. return LFS_ERR_INVAL;
  3143. } else {
  3144. npos = res;
  3145. }
  3146. }
  3147. if (npos > lfs->file_max) {
  3148. // file position out of range
  3149. return LFS_ERR_INVAL;
  3150. }
  3151. if (file->pos == npos) {
  3152. // noop - position has not changed
  3153. return npos;
  3154. }
  3155. // if we're only reading and our new offset is still in the file's cache
  3156. // we can avoid flushing and needing to reread the data
  3157. if (
  3158. #ifndef LFS_READONLY
  3159. !(file->flags & LFS_F_WRITING)
  3160. #else
  3161. true
  3162. #endif
  3163. ) {
  3164. int oindex = lfs_ctz_index(lfs, &(lfs_off_t){file->pos});
  3165. lfs_off_t noff = npos;
  3166. int nindex = lfs_ctz_index(lfs, &noff);
  3167. if (oindex == nindex
  3168. && noff >= file->cache.off
  3169. && noff < file->cache.off + file->cache.size) {
  3170. file->pos = npos;
  3171. file->off = noff;
  3172. return npos;
  3173. }
  3174. }
  3175. // write out everything beforehand, may be noop if rdonly
  3176. int err = lfs_file_flush(lfs, file);
  3177. if (err) {
  3178. return err;
  3179. }
  3180. // update pos
  3181. file->pos = npos;
  3182. return npos;
  3183. }
  3184. #ifndef LFS_READONLY
  3185. static int lfs_file_rawtruncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size) {
  3186. LFS_ASSERT((file->flags & LFS_O_WRONLY) == LFS_O_WRONLY);
  3187. if (size > LFS_FILE_MAX) {
  3188. return LFS_ERR_INVAL;
  3189. }
  3190. lfs_off_t pos = file->pos;
  3191. lfs_off_t oldsize = lfs_file_rawsize(lfs, file);
  3192. if (size < oldsize) {
  3193. // revert to inline file?
  3194. if (size <= lfs_min(0x3fe, lfs_min(
  3195. lfs->cfg->cache_size,
  3196. (lfs->cfg->metadata_max ?
  3197. lfs->cfg->metadata_max : lfs->cfg->block_size) / 8))) {
  3198. // flush+seek to head
  3199. lfs_soff_t res = lfs_file_rawseek(lfs, file, 0, LFS_SEEK_SET);
  3200. if (res < 0) {
  3201. return (int)res;
  3202. }
  3203. // read our data into rcache temporarily
  3204. lfs_cache_drop(lfs, &lfs->rcache);
  3205. res = lfs_file_flushedread(lfs, file,
  3206. lfs->rcache.buffer, size);
  3207. if (res < 0) {
  3208. return (int)res;
  3209. }
  3210. file->ctz.head = LFS_BLOCK_INLINE;
  3211. file->ctz.size = size;
  3212. file->flags |= LFS_F_DIRTY | LFS_F_READING | LFS_F_INLINE;
  3213. file->cache.block = file->ctz.head;
  3214. file->cache.off = 0;
  3215. file->cache.size = lfs->cfg->cache_size;
  3216. memcpy(file->cache.buffer, lfs->rcache.buffer, size);
  3217. } else {
  3218. // need to flush since directly changing metadata
  3219. int err = lfs_file_flush(lfs, file);
  3220. if (err) {
  3221. return err;
  3222. }
  3223. // lookup new head in ctz skip list
  3224. err = lfs_ctz_find(lfs, NULL, &file->cache,
  3225. file->ctz.head, file->ctz.size,
  3226. size-1, &file->block, &(lfs_off_t){0});
  3227. if (err) {
  3228. return err;
  3229. }
  3230. // need to set pos/block/off consistently so seeking back to
  3231. // the old position does not get confused
  3232. file->pos = size;
  3233. file->ctz.head = file->block;
  3234. file->ctz.size = size;
  3235. file->flags |= LFS_F_DIRTY | LFS_F_READING;
  3236. }
  3237. } else if (size > oldsize) {
  3238. // flush+seek if not already at end
  3239. lfs_soff_t res = lfs_file_rawseek(lfs, file, 0, LFS_SEEK_END);
  3240. if (res < 0) {
  3241. return (int)res;
  3242. }
  3243. // fill with zeros
  3244. while (file->pos < size) {
  3245. res = lfs_file_rawwrite(lfs, file, &(uint8_t){0}, 1);
  3246. if (res < 0) {
  3247. return (int)res;
  3248. }
  3249. }
  3250. }
  3251. // restore pos
  3252. lfs_soff_t res = lfs_file_rawseek(lfs, file, pos, LFS_SEEK_SET);
  3253. if (res < 0) {
  3254. return (int)res;
  3255. }
  3256. return 0;
  3257. }
  3258. #endif
  3259. static lfs_soff_t lfs_file_rawtell(lfs_t *lfs, lfs_file_t *file) {
  3260. (void)lfs;
  3261. return file->pos;
  3262. }
  3263. static int lfs_file_rawrewind(lfs_t *lfs, lfs_file_t *file) {
  3264. lfs_soff_t res = lfs_file_rawseek(lfs, file, 0, LFS_SEEK_SET);
  3265. if (res < 0) {
  3266. return (int)res;
  3267. }
  3268. return 0;
  3269. }
  3270. static lfs_soff_t lfs_file_rawsize(lfs_t *lfs, lfs_file_t *file) {
  3271. (void)lfs;
  3272. #ifndef LFS_READONLY
  3273. if (file->flags & LFS_F_WRITING) {
  3274. return lfs_max(file->pos, file->ctz.size);
  3275. }
  3276. #endif
  3277. return file->ctz.size;
  3278. }
  3279. /// General fs operations ///
  3280. static int lfs_rawstat(lfs_t *lfs, const char *path, struct lfs_info *info) {
  3281. lfs_mdir_t cwd;
  3282. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  3283. if (tag < 0) {
  3284. return (int)tag;
  3285. }
  3286. return lfs_dir_getinfo(lfs, &cwd, lfs_tag_id(tag), info);
  3287. }
  3288. #ifndef LFS_READONLY
  3289. static int lfs_rawremove(lfs_t *lfs, const char *path) {
  3290. // deorphan if we haven't yet, needed at most once after poweron
  3291. int err = lfs_fs_forceconsistency(lfs);
  3292. if (err) {
  3293. return err;
  3294. }
  3295. lfs_mdir_t cwd;
  3296. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  3297. if (tag < 0 || lfs_tag_id(tag) == 0x3ff) {
  3298. return (tag < 0) ? (int)tag : LFS_ERR_INVAL;
  3299. }
  3300. struct lfs_mlist dir;
  3301. dir.next = lfs->mlist;
  3302. if (lfs_tag_type3(tag) == LFS_TYPE_DIR) {
  3303. // must be empty before removal
  3304. lfs_block_t pair[2];
  3305. lfs_stag_t res = lfs_dir_get(lfs, &cwd, LFS_MKTAG(0x700, 0x3ff, 0),
  3306. LFS_MKTAG(LFS_TYPE_STRUCT, lfs_tag_id(tag), 8), pair);
  3307. if (res < 0) {
  3308. return (int)res;
  3309. }
  3310. lfs_pair_fromle32(pair);
  3311. err = lfs_dir_fetch(lfs, &dir.m, pair);
  3312. if (err) {
  3313. return err;
  3314. }
  3315. if (dir.m.count > 0 || dir.m.split) {
  3316. return LFS_ERR_NOTEMPTY;
  3317. }
  3318. // mark fs as orphaned
  3319. err = lfs_fs_preporphans(lfs, +1);
  3320. if (err) {
  3321. return err;
  3322. }
  3323. // I know it's crazy but yes, dir can be changed by our parent's
  3324. // commit (if predecessor is child)
  3325. dir.type = 0;
  3326. dir.id = 0;
  3327. lfs->mlist = &dir;
  3328. }
  3329. // delete the entry
  3330. err = lfs_dir_commit(lfs, &cwd, LFS_MKATTRS(
  3331. {LFS_MKTAG(LFS_TYPE_DELETE, lfs_tag_id(tag), 0), NULL}));
  3332. if (err) {
  3333. lfs->mlist = dir.next;
  3334. return err;
  3335. }
  3336. lfs->mlist = dir.next;
  3337. if (lfs_tag_type3(tag) == LFS_TYPE_DIR) {
  3338. // fix orphan
  3339. err = lfs_fs_preporphans(lfs, -1);
  3340. if (err) {
  3341. return err;
  3342. }
  3343. err = lfs_fs_pred(lfs, dir.m.pair, &cwd);
  3344. if (err) {
  3345. return err;
  3346. }
  3347. err = lfs_dir_drop(lfs, &cwd, &dir.m);
  3348. if (err) {
  3349. return err;
  3350. }
  3351. }
  3352. return 0;
  3353. }
  3354. #endif
  3355. #ifndef LFS_READONLY
  3356. static int lfs_rawrename(lfs_t *lfs, const char *oldpath, const char *newpath) {
  3357. // deorphan if we haven't yet, needed at most once after poweron
  3358. int err = lfs_fs_forceconsistency(lfs);
  3359. if (err) {
  3360. return err;
  3361. }
  3362. // find old entry
  3363. lfs_mdir_t oldcwd;
  3364. lfs_stag_t oldtag = lfs_dir_find(lfs, &oldcwd, &oldpath, NULL);
  3365. if (oldtag < 0 || lfs_tag_id(oldtag) == 0x3ff) {
  3366. return (oldtag < 0) ? (int)oldtag : LFS_ERR_INVAL;
  3367. }
  3368. // find new entry
  3369. lfs_mdir_t newcwd;
  3370. uint16_t newid;
  3371. lfs_stag_t prevtag = lfs_dir_find(lfs, &newcwd, &newpath, &newid);
  3372. if ((prevtag < 0 || lfs_tag_id(prevtag) == 0x3ff) &&
  3373. !(prevtag == LFS_ERR_NOENT && newid != 0x3ff)) {
  3374. return (prevtag < 0) ? (int)prevtag : LFS_ERR_INVAL;
  3375. }
  3376. // if we're in the same pair there's a few special cases...
  3377. bool samepair = (lfs_pair_cmp(oldcwd.pair, newcwd.pair) == 0);
  3378. uint16_t newoldid = lfs_tag_id(oldtag);
  3379. struct lfs_mlist prevdir;
  3380. prevdir.next = lfs->mlist;
  3381. if (prevtag == LFS_ERR_NOENT) {
  3382. // check that name fits
  3383. lfs_size_t nlen = strlen(newpath);
  3384. if (nlen > lfs->name_max) {
  3385. return LFS_ERR_NAMETOOLONG;
  3386. }
  3387. // there is a small chance we are being renamed in the same
  3388. // directory/ to an id less than our old id, the global update
  3389. // to handle this is a bit messy
  3390. if (samepair && newid <= newoldid) {
  3391. newoldid += 1;
  3392. }
  3393. } else if (lfs_tag_type3(prevtag) != lfs_tag_type3(oldtag)) {
  3394. return LFS_ERR_ISDIR;
  3395. } else if (samepair && newid == newoldid) {
  3396. // we're renaming to ourselves??
  3397. return 0;
  3398. } else if (lfs_tag_type3(prevtag) == LFS_TYPE_DIR) {
  3399. // must be empty before removal
  3400. lfs_block_t prevpair[2];
  3401. lfs_stag_t res = lfs_dir_get(lfs, &newcwd, LFS_MKTAG(0x700, 0x3ff, 0),
  3402. LFS_MKTAG(LFS_TYPE_STRUCT, newid, 8), prevpair);
  3403. if (res < 0) {
  3404. return (int)res;
  3405. }
  3406. lfs_pair_fromle32(prevpair);
  3407. // must be empty before removal
  3408. err = lfs_dir_fetch(lfs, &prevdir.m, prevpair);
  3409. if (err) {
  3410. return err;
  3411. }
  3412. if (prevdir.m.count > 0 || prevdir.m.split) {
  3413. return LFS_ERR_NOTEMPTY;
  3414. }
  3415. // mark fs as orphaned
  3416. err = lfs_fs_preporphans(lfs, +1);
  3417. if (err) {
  3418. return err;
  3419. }
  3420. // I know it's crazy but yes, dir can be changed by our parent's
  3421. // commit (if predecessor is child)
  3422. prevdir.type = 0;
  3423. prevdir.id = 0;
  3424. lfs->mlist = &prevdir;
  3425. }
  3426. if (!samepair) {
  3427. lfs_fs_prepmove(lfs, newoldid, oldcwd.pair);
  3428. }
  3429. // move over all attributes
  3430. err = lfs_dir_commit(lfs, &newcwd, LFS_MKATTRS(
  3431. {LFS_MKTAG_IF(prevtag != LFS_ERR_NOENT,
  3432. LFS_TYPE_DELETE, newid, 0), NULL},
  3433. {LFS_MKTAG(LFS_TYPE_CREATE, newid, 0), NULL},
  3434. {LFS_MKTAG(lfs_tag_type3(oldtag), newid, strlen(newpath)), newpath},
  3435. {LFS_MKTAG(LFS_FROM_MOVE, newid, lfs_tag_id(oldtag)), &oldcwd},
  3436. {LFS_MKTAG_IF(samepair,
  3437. LFS_TYPE_DELETE, newoldid, 0), NULL}));
  3438. if (err) {
  3439. lfs->mlist = prevdir.next;
  3440. return err;
  3441. }
  3442. // let commit clean up after move (if we're different! otherwise move
  3443. // logic already fixed it for us)
  3444. if (!samepair && lfs_gstate_hasmove(&lfs->gstate)) {
  3445. // prep gstate and delete move id
  3446. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  3447. err = lfs_dir_commit(lfs, &oldcwd, LFS_MKATTRS(
  3448. {LFS_MKTAG(LFS_TYPE_DELETE, lfs_tag_id(oldtag), 0), NULL}));
  3449. if (err) {
  3450. lfs->mlist = prevdir.next;
  3451. return err;
  3452. }
  3453. }
  3454. lfs->mlist = prevdir.next;
  3455. if (prevtag != LFS_ERR_NOENT
  3456. && lfs_tag_type3(prevtag) == LFS_TYPE_DIR) {
  3457. // fix orphan
  3458. err = lfs_fs_preporphans(lfs, -1);
  3459. if (err) {
  3460. return err;
  3461. }
  3462. err = lfs_fs_pred(lfs, prevdir.m.pair, &newcwd);
  3463. if (err) {
  3464. return err;
  3465. }
  3466. err = lfs_dir_drop(lfs, &newcwd, &prevdir.m);
  3467. if (err) {
  3468. return err;
  3469. }
  3470. }
  3471. return 0;
  3472. }
  3473. #endif
  3474. static lfs_ssize_t lfs_rawgetattr(lfs_t *lfs, const char *path,
  3475. uint8_t type, void *buffer, lfs_size_t size) {
  3476. lfs_mdir_t cwd;
  3477. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  3478. if (tag < 0) {
  3479. return tag;
  3480. }
  3481. uint16_t id = lfs_tag_id(tag);
  3482. if (id == 0x3ff) {
  3483. // special case for root
  3484. id = 0;
  3485. int err = lfs_dir_fetch(lfs, &cwd, lfs->root);
  3486. if (err) {
  3487. return err;
  3488. }
  3489. }
  3490. tag = lfs_dir_get(lfs, &cwd, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3491. LFS_MKTAG(LFS_TYPE_USERATTR + type,
  3492. id, lfs_min(size, lfs->attr_max)),
  3493. buffer);
  3494. if (tag < 0) {
  3495. if (tag == LFS_ERR_NOENT) {
  3496. return LFS_ERR_NOATTR;
  3497. }
  3498. return tag;
  3499. }
  3500. return lfs_tag_size(tag);
  3501. }
  3502. #ifndef LFS_READONLY
  3503. static int lfs_commitattr(lfs_t *lfs, const char *path,
  3504. uint8_t type, const void *buffer, lfs_size_t size) {
  3505. lfs_mdir_t cwd;
  3506. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  3507. if (tag < 0) {
  3508. return tag;
  3509. }
  3510. uint16_t id = lfs_tag_id(tag);
  3511. if (id == 0x3ff) {
  3512. // special case for root
  3513. id = 0;
  3514. int err = lfs_dir_fetch(lfs, &cwd, lfs->root);
  3515. if (err) {
  3516. return err;
  3517. }
  3518. }
  3519. return lfs_dir_commit(lfs, &cwd, LFS_MKATTRS(
  3520. {LFS_MKTAG(LFS_TYPE_USERATTR + type, id, size), buffer}));
  3521. }
  3522. #endif
  3523. #ifndef LFS_READONLY
  3524. static int lfs_rawsetattr(lfs_t *lfs, const char *path,
  3525. uint8_t type, const void *buffer, lfs_size_t size) {
  3526. if (size > lfs->attr_max) {
  3527. return LFS_ERR_NOSPC;
  3528. }
  3529. return lfs_commitattr(lfs, path, type, buffer, size);
  3530. }
  3531. #endif
  3532. #ifndef LFS_READONLY
  3533. static int lfs_rawremoveattr(lfs_t *lfs, const char *path, uint8_t type) {
  3534. return lfs_commitattr(lfs, path, type, NULL, 0x3ff);
  3535. }
  3536. #endif
  3537. /// Filesystem operations ///
  3538. static int lfs_init(lfs_t *lfs, const struct lfs_config *cfg) {
  3539. lfs->cfg = cfg;
  3540. lfs->block_count = cfg->block_count; // May be 0
  3541. int err = 0;
  3542. #ifdef LFS_MULTIVERSION
  3543. // this driver only supports minor version < current minor version
  3544. LFS_ASSERT(!lfs->cfg->disk_version || (
  3545. (0xffff & (lfs->cfg->disk_version >> 16))
  3546. == LFS_DISK_VERSION_MAJOR
  3547. && (0xffff & (lfs->cfg->disk_version >> 0))
  3548. <= LFS_DISK_VERSION_MINOR));
  3549. #endif
  3550. // check that bool is a truthy-preserving type
  3551. //
  3552. // note the most common reason for this failure is a before-c99 compiler,
  3553. // which littlefs currently does not support
  3554. LFS_ASSERT((bool)0x80000000);
  3555. // validate that the lfs-cfg sizes were initiated properly before
  3556. // performing any arithmetic logics with them
  3557. LFS_ASSERT(lfs->cfg->read_size != 0);
  3558. LFS_ASSERT(lfs->cfg->prog_size != 0);
  3559. LFS_ASSERT(lfs->cfg->cache_size != 0);
  3560. // check that block size is a multiple of cache size is a multiple
  3561. // of prog and read sizes
  3562. LFS_ASSERT(lfs->cfg->cache_size % lfs->cfg->read_size == 0);
  3563. LFS_ASSERT(lfs->cfg->cache_size % lfs->cfg->prog_size == 0);
  3564. LFS_ASSERT(lfs->cfg->block_size % lfs->cfg->cache_size == 0);
  3565. // check that the block size is large enough to fit all ctz pointers
  3566. LFS_ASSERT(lfs->cfg->block_size >= 128);
  3567. // this is the exact calculation for all ctz pointers, if this fails
  3568. // and the simpler assert above does not, math must be broken
  3569. LFS_ASSERT(4*lfs_npw2(0xffffffff / (lfs->cfg->block_size-2*4))
  3570. <= lfs->cfg->block_size);
  3571. // block_cycles = 0 is no longer supported.
  3572. //
  3573. // block_cycles is the number of erase cycles before littlefs evicts
  3574. // metadata logs as a part of wear leveling. Suggested values are in the
  3575. // range of 100-1000, or set block_cycles to -1 to disable block-level
  3576. // wear-leveling.
  3577. LFS_ASSERT(lfs->cfg->block_cycles != 0);
  3578. // setup read cache
  3579. if (lfs->cfg->read_buffer) {
  3580. lfs->rcache.buffer = lfs->cfg->read_buffer;
  3581. } else {
  3582. lfs->rcache.buffer = lfs_malloc(lfs->cfg->cache_size);
  3583. if (!lfs->rcache.buffer) {
  3584. err = LFS_ERR_NOMEM;
  3585. goto cleanup;
  3586. }
  3587. }
  3588. // setup program cache
  3589. if (lfs->cfg->prog_buffer) {
  3590. lfs->pcache.buffer = lfs->cfg->prog_buffer;
  3591. } else {
  3592. lfs->pcache.buffer = lfs_malloc(lfs->cfg->cache_size);
  3593. if (!lfs->pcache.buffer) {
  3594. err = LFS_ERR_NOMEM;
  3595. goto cleanup;
  3596. }
  3597. }
  3598. // zero to avoid information leaks
  3599. lfs_cache_zero(lfs, &lfs->rcache);
  3600. lfs_cache_zero(lfs, &lfs->pcache);
  3601. // setup lookahead, must be multiple of 64-bits, 32-bit aligned
  3602. LFS_ASSERT(lfs->cfg->lookahead_size > 0);
  3603. LFS_ASSERT(lfs->cfg->lookahead_size % 8 == 0 &&
  3604. (uintptr_t)lfs->cfg->lookahead_buffer % 4 == 0);
  3605. if (lfs->cfg->lookahead_buffer) {
  3606. lfs->free.buffer = lfs->cfg->lookahead_buffer;
  3607. } else {
  3608. lfs->free.buffer = lfs_malloc(lfs->cfg->lookahead_size);
  3609. if (!lfs->free.buffer) {
  3610. err = LFS_ERR_NOMEM;
  3611. goto cleanup;
  3612. }
  3613. }
  3614. // check that the size limits are sane
  3615. LFS_ASSERT(lfs->cfg->name_max <= LFS_NAME_MAX);
  3616. lfs->name_max = lfs->cfg->name_max;
  3617. if (!lfs->name_max) {
  3618. lfs->name_max = LFS_NAME_MAX;
  3619. }
  3620. LFS_ASSERT(lfs->cfg->file_max <= LFS_FILE_MAX);
  3621. lfs->file_max = lfs->cfg->file_max;
  3622. if (!lfs->file_max) {
  3623. lfs->file_max = LFS_FILE_MAX;
  3624. }
  3625. LFS_ASSERT(lfs->cfg->attr_max <= LFS_ATTR_MAX);
  3626. lfs->attr_max = lfs->cfg->attr_max;
  3627. if (!lfs->attr_max) {
  3628. lfs->attr_max = LFS_ATTR_MAX;
  3629. }
  3630. LFS_ASSERT(lfs->cfg->metadata_max <= lfs->cfg->block_size);
  3631. // setup default state
  3632. lfs->root[0] = LFS_BLOCK_NULL;
  3633. lfs->root[1] = LFS_BLOCK_NULL;
  3634. lfs->mlist = NULL;
  3635. lfs->seed = 0;
  3636. lfs->gdisk = (lfs_gstate_t){0};
  3637. lfs->gstate = (lfs_gstate_t){0};
  3638. lfs->gdelta = (lfs_gstate_t){0};
  3639. #ifdef LFS_MIGRATE
  3640. lfs->lfs1 = NULL;
  3641. #endif
  3642. return 0;
  3643. cleanup:
  3644. lfs_deinit(lfs);
  3645. return err;
  3646. }
  3647. static int lfs_deinit(lfs_t *lfs) {
  3648. // free allocated memory
  3649. if (!lfs->cfg->read_buffer) {
  3650. lfs_free(lfs->rcache.buffer);
  3651. }
  3652. if (!lfs->cfg->prog_buffer) {
  3653. lfs_free(lfs->pcache.buffer);
  3654. }
  3655. if (!lfs->cfg->lookahead_buffer) {
  3656. lfs_free(lfs->free.buffer);
  3657. }
  3658. return 0;
  3659. }
  3660. #ifndef LFS_READONLY
  3661. static int lfs_rawformat(lfs_t *lfs, const struct lfs_config *cfg) {
  3662. int err = 0;
  3663. {
  3664. err = lfs_init(lfs, cfg);
  3665. if (err) {
  3666. return err;
  3667. }
  3668. LFS_ASSERT(cfg->block_count != 0);
  3669. // create free lookahead
  3670. memset(lfs->free.buffer, 0, lfs->cfg->lookahead_size);
  3671. lfs->free.off = 0;
  3672. lfs->free.size = lfs_min(8*lfs->cfg->lookahead_size,
  3673. lfs->block_count);
  3674. lfs->free.i = 0;
  3675. lfs_alloc_ack(lfs);
  3676. // create root dir
  3677. lfs_mdir_t root;
  3678. err = lfs_dir_alloc(lfs, &root);
  3679. if (err) {
  3680. goto cleanup;
  3681. }
  3682. // write one superblock
  3683. lfs_superblock_t superblock = {
  3684. .version = lfs_fs_disk_version(lfs),
  3685. .block_size = lfs->cfg->block_size,
  3686. .block_count = lfs->block_count,
  3687. .name_max = lfs->name_max,
  3688. .file_max = lfs->file_max,
  3689. .attr_max = lfs->attr_max,
  3690. };
  3691. lfs_superblock_tole32(&superblock);
  3692. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  3693. {LFS_MKTAG(LFS_TYPE_CREATE, 0, 0), NULL},
  3694. {LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
  3695. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3696. &superblock}));
  3697. if (err) {
  3698. goto cleanup;
  3699. }
  3700. // force compaction to prevent accidentally mounting any
  3701. // older version of littlefs that may live on disk
  3702. root.erased = false;
  3703. err = lfs_dir_commit(lfs, &root, NULL, 0);
  3704. if (err) {
  3705. goto cleanup;
  3706. }
  3707. // sanity check that fetch works
  3708. err = lfs_dir_fetch(lfs, &root, (const lfs_block_t[2]){0, 1});
  3709. if (err) {
  3710. goto cleanup;
  3711. }
  3712. }
  3713. cleanup:
  3714. lfs_deinit(lfs);
  3715. return err;
  3716. }
  3717. #endif
  3718. static int lfs_rawmount(lfs_t *lfs, const struct lfs_config *cfg) {
  3719. int err = lfs_init(lfs, cfg);
  3720. if (err) {
  3721. return err;
  3722. }
  3723. // scan directory blocks for superblock and any global updates
  3724. lfs_mdir_t dir = {.tail = {0, 1}};
  3725. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  3726. lfs_size_t tortoise_i = 1;
  3727. lfs_size_t tortoise_period = 1;
  3728. while (!lfs_pair_isnull(dir.tail)) {
  3729. // detect cycles with Brent's algorithm
  3730. if (lfs_pair_issync(dir.tail, tortoise)) {
  3731. LFS_WARN("Cycle detected in tail list");
  3732. err = LFS_ERR_CORRUPT;
  3733. goto cleanup;
  3734. }
  3735. if (tortoise_i == tortoise_period) {
  3736. tortoise[0] = dir.tail[0];
  3737. tortoise[1] = dir.tail[1];
  3738. tortoise_i = 0;
  3739. tortoise_period *= 2;
  3740. }
  3741. tortoise_i += 1;
  3742. // fetch next block in tail list
  3743. lfs_stag_t tag = lfs_dir_fetchmatch(lfs, &dir, dir.tail,
  3744. LFS_MKTAG(0x7ff, 0x3ff, 0),
  3745. LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8),
  3746. NULL,
  3747. lfs_dir_find_match, &(struct lfs_dir_find_match){
  3748. lfs, "littlefs", 8});
  3749. if (tag < 0) {
  3750. err = tag;
  3751. goto cleanup;
  3752. }
  3753. // has superblock?
  3754. if (tag && !lfs_tag_isdelete(tag)) {
  3755. // update root
  3756. lfs->root[0] = dir.pair[0];
  3757. lfs->root[1] = dir.pair[1];
  3758. // grab superblock
  3759. lfs_superblock_t superblock;
  3760. tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3761. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3762. &superblock);
  3763. if (tag < 0) {
  3764. err = tag;
  3765. goto cleanup;
  3766. }
  3767. lfs_superblock_fromle32(&superblock);
  3768. // check version
  3769. uint16_t major_version = (0xffff & (superblock.version >> 16));
  3770. uint16_t minor_version = (0xffff & (superblock.version >> 0));
  3771. if (major_version != lfs_fs_disk_version_major(lfs)
  3772. || minor_version > lfs_fs_disk_version_minor(lfs)) {
  3773. LFS_ERROR("Invalid version "
  3774. "v%"PRIu16".%"PRIu16" != v%"PRIu16".%"PRIu16,
  3775. major_version,
  3776. minor_version,
  3777. lfs_fs_disk_version_major(lfs),
  3778. lfs_fs_disk_version_minor(lfs));
  3779. err = LFS_ERR_INVAL;
  3780. goto cleanup;
  3781. }
  3782. // found older minor version? set an in-device only bit in the
  3783. // gstate so we know we need to rewrite the superblock before
  3784. // the first write
  3785. if (minor_version < lfs_fs_disk_version_minor(lfs)) {
  3786. LFS_DEBUG("Found older minor version "
  3787. "v%"PRIu16".%"PRIu16" < v%"PRIu16".%"PRIu16,
  3788. major_version,
  3789. minor_version,
  3790. lfs_fs_disk_version_major(lfs),
  3791. lfs_fs_disk_version_minor(lfs));
  3792. // note this bit is reserved on disk, so fetching more gstate
  3793. // will not interfere here
  3794. lfs_fs_prepsuperblock(lfs, true);
  3795. }
  3796. // check superblock configuration
  3797. if (superblock.name_max) {
  3798. if (superblock.name_max > lfs->name_max) {
  3799. LFS_ERROR("Unsupported name_max (%"PRIu32" > %"PRIu32")",
  3800. superblock.name_max, lfs->name_max);
  3801. err = LFS_ERR_INVAL;
  3802. goto cleanup;
  3803. }
  3804. lfs->name_max = superblock.name_max;
  3805. }
  3806. if (superblock.file_max) {
  3807. if (superblock.file_max > lfs->file_max) {
  3808. LFS_ERROR("Unsupported file_max (%"PRIu32" > %"PRIu32")",
  3809. superblock.file_max, lfs->file_max);
  3810. err = LFS_ERR_INVAL;
  3811. goto cleanup;
  3812. }
  3813. lfs->file_max = superblock.file_max;
  3814. }
  3815. if (superblock.attr_max) {
  3816. if (superblock.attr_max > lfs->attr_max) {
  3817. LFS_ERROR("Unsupported attr_max (%"PRIu32" > %"PRIu32")",
  3818. superblock.attr_max, lfs->attr_max);
  3819. err = LFS_ERR_INVAL;
  3820. goto cleanup;
  3821. }
  3822. lfs->attr_max = superblock.attr_max;
  3823. }
  3824. // this is where we get the block_count from disk if block_count=0
  3825. if (lfs->cfg->block_count
  3826. && superblock.block_count != lfs->cfg->block_count) {
  3827. LFS_ERROR("Invalid block count (%"PRIu32" != %"PRIu32")",
  3828. superblock.block_count, lfs->cfg->block_count);
  3829. err = LFS_ERR_INVAL;
  3830. goto cleanup;
  3831. }
  3832. lfs->block_count = superblock.block_count;
  3833. if (superblock.block_size != lfs->cfg->block_size) {
  3834. LFS_ERROR("Invalid block size (%"PRIu32" != %"PRIu32")",
  3835. superblock.block_size, lfs->cfg->block_size);
  3836. err = LFS_ERR_INVAL;
  3837. goto cleanup;
  3838. }
  3839. }
  3840. // has gstate?
  3841. err = lfs_dir_getgstate(lfs, &dir, &lfs->gstate);
  3842. if (err) {
  3843. goto cleanup;
  3844. }
  3845. }
  3846. // update littlefs with gstate
  3847. if (!lfs_gstate_iszero(&lfs->gstate)) {
  3848. LFS_DEBUG("Found pending gstate 0x%08"PRIx32"%08"PRIx32"%08"PRIx32,
  3849. lfs->gstate.tag,
  3850. lfs->gstate.pair[0],
  3851. lfs->gstate.pair[1]);
  3852. }
  3853. lfs->gstate.tag += !lfs_tag_isvalid(lfs->gstate.tag);
  3854. lfs->gdisk = lfs->gstate;
  3855. // setup free lookahead, to distribute allocations uniformly across
  3856. // boots, we start the allocator at a random location
  3857. lfs->free.off = lfs->seed % lfs->block_count;
  3858. lfs_alloc_drop(lfs);
  3859. return 0;
  3860. cleanup:
  3861. lfs_rawunmount(lfs);
  3862. return err;
  3863. }
  3864. static int lfs_rawunmount(lfs_t *lfs) {
  3865. return lfs_deinit(lfs);
  3866. }
  3867. /// Filesystem filesystem operations ///
  3868. static int lfs_fs_rawstat(lfs_t *lfs, struct lfs_fsinfo *fsinfo) {
  3869. // if the superblock is up-to-date, we must be on the most recent
  3870. // minor version of littlefs
  3871. if (!lfs_gstate_needssuperblock(&lfs->gstate)) {
  3872. fsinfo->disk_version = lfs_fs_disk_version(lfs);
  3873. // otherwise we need to read the minor version on disk
  3874. } else {
  3875. // fetch the superblock
  3876. lfs_mdir_t dir;
  3877. int err = lfs_dir_fetch(lfs, &dir, lfs->root);
  3878. if (err) {
  3879. return err;
  3880. }
  3881. lfs_superblock_t superblock;
  3882. lfs_stag_t tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3883. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3884. &superblock);
  3885. if (tag < 0) {
  3886. return tag;
  3887. }
  3888. lfs_superblock_fromle32(&superblock);
  3889. // read the on-disk version
  3890. fsinfo->disk_version = superblock.version;
  3891. }
  3892. // filesystem geometry
  3893. fsinfo->block_size = lfs->cfg->block_size;
  3894. fsinfo->block_count = lfs->block_count;
  3895. // other on-disk configuration, we cache all of these for internal use
  3896. fsinfo->name_max = lfs->name_max;
  3897. fsinfo->file_max = lfs->file_max;
  3898. fsinfo->attr_max = lfs->attr_max;
  3899. return 0;
  3900. }
  3901. int lfs_fs_rawtraverse(lfs_t *lfs,
  3902. int (*cb)(void *data, lfs_block_t block), void *data,
  3903. bool includeorphans) {
  3904. // iterate over metadata pairs
  3905. lfs_mdir_t dir = {.tail = {0, 1}};
  3906. #ifdef LFS_MIGRATE
  3907. // also consider v1 blocks during migration
  3908. if (lfs->lfs1) {
  3909. int err = lfs1_traverse(lfs, cb, data);
  3910. if (err) {
  3911. return err;
  3912. }
  3913. dir.tail[0] = lfs->root[0];
  3914. dir.tail[1] = lfs->root[1];
  3915. }
  3916. #endif
  3917. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  3918. lfs_size_t tortoise_i = 1;
  3919. lfs_size_t tortoise_period = 1;
  3920. while (!lfs_pair_isnull(dir.tail)) {
  3921. // detect cycles with Brent's algorithm
  3922. if (lfs_pair_issync(dir.tail, tortoise)) {
  3923. LFS_WARN("Cycle detected in tail list");
  3924. return LFS_ERR_CORRUPT;
  3925. }
  3926. if (tortoise_i == tortoise_period) {
  3927. tortoise[0] = dir.tail[0];
  3928. tortoise[1] = dir.tail[1];
  3929. tortoise_i = 0;
  3930. tortoise_period *= 2;
  3931. }
  3932. tortoise_i += 1;
  3933. for (int i = 0; i < 2; i++) {
  3934. int err = cb(data, dir.tail[i]);
  3935. if (err) {
  3936. return err;
  3937. }
  3938. }
  3939. // iterate through ids in directory
  3940. int err = lfs_dir_fetch(lfs, &dir, dir.tail);
  3941. if (err) {
  3942. return err;
  3943. }
  3944. for (uint16_t id = 0; id < dir.count; id++) {
  3945. struct lfs_ctz ctz;
  3946. lfs_stag_t tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x700, 0x3ff, 0),
  3947. LFS_MKTAG(LFS_TYPE_STRUCT, id, sizeof(ctz)), &ctz);
  3948. if (tag < 0) {
  3949. if (tag == LFS_ERR_NOENT) {
  3950. continue;
  3951. }
  3952. return tag;
  3953. }
  3954. lfs_ctz_fromle32(&ctz);
  3955. if (lfs_tag_type3(tag) == LFS_TYPE_CTZSTRUCT) {
  3956. err = lfs_ctz_traverse(lfs, NULL, &lfs->rcache,
  3957. ctz.head, ctz.size, cb, data);
  3958. if (err) {
  3959. return err;
  3960. }
  3961. } else if (includeorphans &&
  3962. lfs_tag_type3(tag) == LFS_TYPE_DIRSTRUCT) {
  3963. for (int i = 0; i < 2; i++) {
  3964. err = cb(data, (&ctz.head)[i]);
  3965. if (err) {
  3966. return err;
  3967. }
  3968. }
  3969. }
  3970. }
  3971. }
  3972. #ifndef LFS_READONLY
  3973. // iterate over any open files
  3974. for (lfs_file_t *f = (lfs_file_t*)lfs->mlist; f; f = f->next) {
  3975. if (f->type != LFS_TYPE_REG) {
  3976. continue;
  3977. }
  3978. if ((f->flags & LFS_F_DIRTY) && !(f->flags & LFS_F_INLINE)) {
  3979. int err = lfs_ctz_traverse(lfs, &f->cache, &lfs->rcache,
  3980. f->ctz.head, f->ctz.size, cb, data);
  3981. if (err) {
  3982. return err;
  3983. }
  3984. }
  3985. if ((f->flags & LFS_F_WRITING) && !(f->flags & LFS_F_INLINE)) {
  3986. int err = lfs_ctz_traverse(lfs, &f->cache, &lfs->rcache,
  3987. f->block, f->pos, cb, data);
  3988. if (err) {
  3989. return err;
  3990. }
  3991. }
  3992. }
  3993. #endif
  3994. return 0;
  3995. }
  3996. #ifndef LFS_READONLY
  3997. static int lfs_fs_pred(lfs_t *lfs,
  3998. const lfs_block_t pair[2], lfs_mdir_t *pdir) {
  3999. // iterate over all directory directory entries
  4000. pdir->tail[0] = 0;
  4001. pdir->tail[1] = 1;
  4002. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  4003. lfs_size_t tortoise_i = 1;
  4004. lfs_size_t tortoise_period = 1;
  4005. while (!lfs_pair_isnull(pdir->tail)) {
  4006. // detect cycles with Brent's algorithm
  4007. if (lfs_pair_issync(pdir->tail, tortoise)) {
  4008. LFS_WARN("Cycle detected in tail list");
  4009. return LFS_ERR_CORRUPT;
  4010. }
  4011. if (tortoise_i == tortoise_period) {
  4012. tortoise[0] = pdir->tail[0];
  4013. tortoise[1] = pdir->tail[1];
  4014. tortoise_i = 0;
  4015. tortoise_period *= 2;
  4016. }
  4017. tortoise_i += 1;
  4018. if (lfs_pair_cmp(pdir->tail, pair) == 0) {
  4019. return 0;
  4020. }
  4021. int err = lfs_dir_fetch(lfs, pdir, pdir->tail);
  4022. if (err) {
  4023. return err;
  4024. }
  4025. }
  4026. return LFS_ERR_NOENT;
  4027. }
  4028. #endif
  4029. #ifndef LFS_READONLY
  4030. struct lfs_fs_parent_match {
  4031. lfs_t *lfs;
  4032. const lfs_block_t pair[2];
  4033. };
  4034. #endif
  4035. #ifndef LFS_READONLY
  4036. static int lfs_fs_parent_match(void *data,
  4037. lfs_tag_t tag, const void *buffer) {
  4038. struct lfs_fs_parent_match *find = data;
  4039. lfs_t *lfs = find->lfs;
  4040. const struct lfs_diskoff *disk = buffer;
  4041. (void)tag;
  4042. lfs_block_t child[2];
  4043. int err = lfs_bd_read(lfs,
  4044. &lfs->pcache, &lfs->rcache, lfs->cfg->block_size,
  4045. disk->block, disk->off, &child, sizeof(child));
  4046. if (err) {
  4047. return err;
  4048. }
  4049. lfs_pair_fromle32(child);
  4050. return (lfs_pair_cmp(child, find->pair) == 0) ? LFS_CMP_EQ : LFS_CMP_LT;
  4051. }
  4052. #endif
  4053. #ifndef LFS_READONLY
  4054. static lfs_stag_t lfs_fs_parent(lfs_t *lfs, const lfs_block_t pair[2],
  4055. lfs_mdir_t *parent) {
  4056. // use fetchmatch with callback to find pairs
  4057. parent->tail[0] = 0;
  4058. parent->tail[1] = 1;
  4059. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  4060. lfs_size_t tortoise_i = 1;
  4061. lfs_size_t tortoise_period = 1;
  4062. while (!lfs_pair_isnull(parent->tail)) {
  4063. // detect cycles with Brent's algorithm
  4064. if (lfs_pair_issync(parent->tail, tortoise)) {
  4065. LFS_WARN("Cycle detected in tail list");
  4066. return LFS_ERR_CORRUPT;
  4067. }
  4068. if (tortoise_i == tortoise_period) {
  4069. tortoise[0] = parent->tail[0];
  4070. tortoise[1] = parent->tail[1];
  4071. tortoise_i = 0;
  4072. tortoise_period *= 2;
  4073. }
  4074. tortoise_i += 1;
  4075. lfs_stag_t tag = lfs_dir_fetchmatch(lfs, parent, parent->tail,
  4076. LFS_MKTAG(0x7ff, 0, 0x3ff),
  4077. LFS_MKTAG(LFS_TYPE_DIRSTRUCT, 0, 8),
  4078. NULL,
  4079. lfs_fs_parent_match, &(struct lfs_fs_parent_match){
  4080. lfs, {pair[0], pair[1]}});
  4081. if (tag && tag != LFS_ERR_NOENT) {
  4082. return tag;
  4083. }
  4084. }
  4085. return LFS_ERR_NOENT;
  4086. }
  4087. #endif
  4088. static void lfs_fs_prepsuperblock(lfs_t *lfs, bool needssuperblock) {
  4089. lfs->gstate.tag = (lfs->gstate.tag & ~LFS_MKTAG(0, 0, 0x200))
  4090. | (uint32_t)needssuperblock << 9;
  4091. }
  4092. #ifndef LFS_READONLY
  4093. static int lfs_fs_preporphans(lfs_t *lfs, int8_t orphans) {
  4094. LFS_ASSERT(lfs_tag_size(lfs->gstate.tag) > 0x000 || orphans >= 0);
  4095. LFS_ASSERT(lfs_tag_size(lfs->gstate.tag) < 0x1ff || orphans <= 0);
  4096. lfs->gstate.tag += orphans;
  4097. lfs->gstate.tag = ((lfs->gstate.tag & ~LFS_MKTAG(0x800, 0, 0)) |
  4098. ((uint32_t)lfs_gstate_hasorphans(&lfs->gstate) << 31));
  4099. return 0;
  4100. }
  4101. #endif
  4102. #ifndef LFS_READONLY
  4103. static void lfs_fs_prepmove(lfs_t *lfs,
  4104. uint16_t id, const lfs_block_t pair[2]) {
  4105. lfs->gstate.tag = ((lfs->gstate.tag & ~LFS_MKTAG(0x7ff, 0x3ff, 0)) |
  4106. ((id != 0x3ff) ? LFS_MKTAG(LFS_TYPE_DELETE, id, 0) : 0));
  4107. lfs->gstate.pair[0] = (id != 0x3ff) ? pair[0] : 0;
  4108. lfs->gstate.pair[1] = (id != 0x3ff) ? pair[1] : 0;
  4109. }
  4110. #endif
  4111. #ifndef LFS_READONLY
  4112. static int lfs_fs_desuperblock(lfs_t *lfs) {
  4113. if (!lfs_gstate_needssuperblock(&lfs->gstate)) {
  4114. return 0;
  4115. }
  4116. LFS_DEBUG("Rewriting superblock {0x%"PRIx32", 0x%"PRIx32"}",
  4117. lfs->root[0],
  4118. lfs->root[1]);
  4119. lfs_mdir_t root;
  4120. int err = lfs_dir_fetch(lfs, &root, lfs->root);
  4121. if (err) {
  4122. return err;
  4123. }
  4124. // write a new superblock
  4125. lfs_superblock_t superblock = {
  4126. .version = lfs_fs_disk_version(lfs),
  4127. .block_size = lfs->cfg->block_size,
  4128. .block_count = lfs->block_count,
  4129. .name_max = lfs->name_max,
  4130. .file_max = lfs->file_max,
  4131. .attr_max = lfs->attr_max,
  4132. };
  4133. lfs_superblock_tole32(&superblock);
  4134. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  4135. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4136. &superblock}));
  4137. if (err) {
  4138. return err;
  4139. }
  4140. lfs_fs_prepsuperblock(lfs, false);
  4141. return 0;
  4142. }
  4143. #endif
  4144. #ifndef LFS_READONLY
  4145. static int lfs_fs_demove(lfs_t *lfs) {
  4146. if (!lfs_gstate_hasmove(&lfs->gdisk)) {
  4147. return 0;
  4148. }
  4149. // Fix bad moves
  4150. LFS_DEBUG("Fixing move {0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16,
  4151. lfs->gdisk.pair[0],
  4152. lfs->gdisk.pair[1],
  4153. lfs_tag_id(lfs->gdisk.tag));
  4154. // no other gstate is supported at this time, so if we found something else
  4155. // something most likely went wrong in gstate calculation
  4156. LFS_ASSERT(lfs_tag_type3(lfs->gdisk.tag) == LFS_TYPE_DELETE);
  4157. // fetch and delete the moved entry
  4158. lfs_mdir_t movedir;
  4159. int err = lfs_dir_fetch(lfs, &movedir, lfs->gdisk.pair);
  4160. if (err) {
  4161. return err;
  4162. }
  4163. // prep gstate and delete move id
  4164. uint16_t moveid = lfs_tag_id(lfs->gdisk.tag);
  4165. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  4166. err = lfs_dir_commit(lfs, &movedir, LFS_MKATTRS(
  4167. {LFS_MKTAG(LFS_TYPE_DELETE, moveid, 0), NULL}));
  4168. if (err) {
  4169. return err;
  4170. }
  4171. return 0;
  4172. }
  4173. #endif
  4174. #ifndef LFS_READONLY
  4175. static int lfs_fs_deorphan(lfs_t *lfs, bool powerloss) {
  4176. if (!lfs_gstate_hasorphans(&lfs->gstate)) {
  4177. return 0;
  4178. }
  4179. // Check for orphans in two separate passes:
  4180. // - 1 for half-orphans (relocations)
  4181. // - 2 for full-orphans (removes/renames)
  4182. //
  4183. // Two separate passes are needed as half-orphans can contain outdated
  4184. // references to full-orphans, effectively hiding them from the deorphan
  4185. // search.
  4186. //
  4187. int pass = 0;
  4188. while (pass < 2) {
  4189. // Fix any orphans
  4190. lfs_mdir_t pdir = {.split = true, .tail = {0, 1}};
  4191. lfs_mdir_t dir;
  4192. bool moreorphans = false;
  4193. // iterate over all directory directory entries
  4194. while (!lfs_pair_isnull(pdir.tail)) {
  4195. int err = lfs_dir_fetch(lfs, &dir, pdir.tail);
  4196. if (err) {
  4197. return err;
  4198. }
  4199. // check head blocks for orphans
  4200. if (!pdir.split) {
  4201. // check if we have a parent
  4202. lfs_mdir_t parent;
  4203. lfs_stag_t tag = lfs_fs_parent(lfs, pdir.tail, &parent);
  4204. if (tag < 0 && tag != LFS_ERR_NOENT) {
  4205. return tag;
  4206. }
  4207. if (pass == 0 && tag != LFS_ERR_NOENT) {
  4208. lfs_block_t pair[2];
  4209. lfs_stag_t state = lfs_dir_get(lfs, &parent,
  4210. LFS_MKTAG(0x7ff, 0x3ff, 0), tag, pair);
  4211. if (state < 0) {
  4212. return state;
  4213. }
  4214. lfs_pair_fromle32(pair);
  4215. if (!lfs_pair_issync(pair, pdir.tail)) {
  4216. // we have desynced
  4217. LFS_DEBUG("Fixing half-orphan "
  4218. "{0x%"PRIx32", 0x%"PRIx32"} "
  4219. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  4220. pdir.tail[0], pdir.tail[1], pair[0], pair[1]);
  4221. // fix pending move in this pair? this looks like an
  4222. // optimization but is in fact _required_ since
  4223. // relocating may outdate the move.
  4224. uint16_t moveid = 0x3ff;
  4225. if (lfs_gstate_hasmovehere(&lfs->gstate, pdir.pair)) {
  4226. moveid = lfs_tag_id(lfs->gstate.tag);
  4227. LFS_DEBUG("Fixing move while fixing orphans "
  4228. "{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
  4229. pdir.pair[0], pdir.pair[1], moveid);
  4230. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  4231. }
  4232. lfs_pair_tole32(pair);
  4233. state = lfs_dir_orphaningcommit(lfs, &pdir, LFS_MKATTRS(
  4234. {LFS_MKTAG_IF(moveid != 0x3ff,
  4235. LFS_TYPE_DELETE, moveid, 0), NULL},
  4236. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8),
  4237. pair}));
  4238. lfs_pair_fromle32(pair);
  4239. if (state < 0) {
  4240. return state;
  4241. }
  4242. // did our commit create more orphans?
  4243. if (state == LFS_OK_ORPHANED) {
  4244. moreorphans = true;
  4245. }
  4246. // refetch tail
  4247. continue;
  4248. }
  4249. }
  4250. // note we only check for full orphans if we may have had a
  4251. // power-loss, otherwise orphans are created intentionally
  4252. // during operations such as lfs_mkdir
  4253. if (pass == 1 && tag == LFS_ERR_NOENT && powerloss) {
  4254. // we are an orphan
  4255. LFS_DEBUG("Fixing orphan {0x%"PRIx32", 0x%"PRIx32"}",
  4256. pdir.tail[0], pdir.tail[1]);
  4257. // steal state
  4258. err = lfs_dir_getgstate(lfs, &dir, &lfs->gdelta);
  4259. if (err) {
  4260. return err;
  4261. }
  4262. // steal tail
  4263. lfs_pair_tole32(dir.tail);
  4264. int state = lfs_dir_orphaningcommit(lfs, &pdir, LFS_MKATTRS(
  4265. {LFS_MKTAG(LFS_TYPE_TAIL + dir.split, 0x3ff, 8),
  4266. dir.tail}));
  4267. lfs_pair_fromle32(dir.tail);
  4268. if (state < 0) {
  4269. return state;
  4270. }
  4271. // did our commit create more orphans?
  4272. if (state == LFS_OK_ORPHANED) {
  4273. moreorphans = true;
  4274. }
  4275. // refetch tail
  4276. continue;
  4277. }
  4278. }
  4279. pdir = dir;
  4280. }
  4281. pass = moreorphans ? 0 : pass+1;
  4282. }
  4283. // mark orphans as fixed
  4284. return lfs_fs_preporphans(lfs, -lfs_gstate_getorphans(&lfs->gstate));
  4285. }
  4286. #endif
  4287. #ifndef LFS_READONLY
  4288. static int lfs_fs_forceconsistency(lfs_t *lfs) {
  4289. int err = lfs_fs_desuperblock(lfs);
  4290. if (err) {
  4291. return err;
  4292. }
  4293. err = lfs_fs_demove(lfs);
  4294. if (err) {
  4295. return err;
  4296. }
  4297. err = lfs_fs_deorphan(lfs, true);
  4298. if (err) {
  4299. return err;
  4300. }
  4301. return 0;
  4302. }
  4303. #endif
  4304. #ifndef LFS_READONLY
  4305. int lfs_fs_rawmkconsistent(lfs_t *lfs) {
  4306. // lfs_fs_forceconsistency does most of the work here
  4307. int err = lfs_fs_forceconsistency(lfs);
  4308. if (err) {
  4309. return err;
  4310. }
  4311. // do we have any pending gstate?
  4312. lfs_gstate_t delta = {0};
  4313. lfs_gstate_xor(&delta, &lfs->gdisk);
  4314. lfs_gstate_xor(&delta, &lfs->gstate);
  4315. if (!lfs_gstate_iszero(&delta)) {
  4316. // lfs_dir_commit will implicitly write out any pending gstate
  4317. lfs_mdir_t root;
  4318. err = lfs_dir_fetch(lfs, &root, lfs->root);
  4319. if (err) {
  4320. return err;
  4321. }
  4322. err = lfs_dir_commit(lfs, &root, NULL, 0);
  4323. if (err) {
  4324. return err;
  4325. }
  4326. }
  4327. return 0;
  4328. }
  4329. #endif
  4330. static int lfs_fs_size_count(void *p, lfs_block_t block) {
  4331. (void)block;
  4332. lfs_size_t *size = p;
  4333. *size += 1;
  4334. return 0;
  4335. }
  4336. static lfs_ssize_t lfs_fs_rawsize(lfs_t *lfs) {
  4337. lfs_size_t size = 0;
  4338. int err = lfs_fs_rawtraverse(lfs, lfs_fs_size_count, &size, false);
  4339. if (err) {
  4340. return err;
  4341. }
  4342. return size;
  4343. }
  4344. #ifndef LFS_READONLY
  4345. int lfs_fs_rawgrow(lfs_t *lfs, lfs_size_t block_count) {
  4346. // shrinking is not supported
  4347. LFS_ASSERT(block_count >= lfs->block_count);
  4348. if (block_count > lfs->block_count) {
  4349. lfs->block_count = block_count;
  4350. // fetch the root
  4351. lfs_mdir_t root;
  4352. int err = lfs_dir_fetch(lfs, &root, lfs->root);
  4353. if (err) {
  4354. return err;
  4355. }
  4356. // update the superblock
  4357. lfs_superblock_t superblock;
  4358. lfs_stag_t tag = lfs_dir_get(lfs, &root, LFS_MKTAG(0x7ff, 0x3ff, 0),
  4359. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4360. &superblock);
  4361. if (tag < 0) {
  4362. return tag;
  4363. }
  4364. lfs_superblock_fromle32(&superblock);
  4365. superblock.block_count = lfs->block_count;
  4366. lfs_superblock_tole32(&superblock);
  4367. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  4368. {tag, &superblock}));
  4369. if (err) {
  4370. return err;
  4371. }
  4372. }
  4373. return 0;
  4374. }
  4375. #endif
  4376. #ifdef LFS_MIGRATE
  4377. ////// Migration from littelfs v1 below this //////
  4378. /// Version info ///
  4379. // Software library version
  4380. // Major (top-nibble), incremented on backwards incompatible changes
  4381. // Minor (bottom-nibble), incremented on feature additions
  4382. #define LFS1_VERSION 0x00010007
  4383. #define LFS1_VERSION_MAJOR (0xffff & (LFS1_VERSION >> 16))
  4384. #define LFS1_VERSION_MINOR (0xffff & (LFS1_VERSION >> 0))
  4385. // Version of On-disk data structures
  4386. // Major (top-nibble), incremented on backwards incompatible changes
  4387. // Minor (bottom-nibble), incremented on feature additions
  4388. #define LFS1_DISK_VERSION 0x00010001
  4389. #define LFS1_DISK_VERSION_MAJOR (0xffff & (LFS1_DISK_VERSION >> 16))
  4390. #define LFS1_DISK_VERSION_MINOR (0xffff & (LFS1_DISK_VERSION >> 0))
  4391. /// v1 Definitions ///
  4392. // File types
  4393. enum lfs1_type {
  4394. LFS1_TYPE_REG = 0x11,
  4395. LFS1_TYPE_DIR = 0x22,
  4396. LFS1_TYPE_SUPERBLOCK = 0x2e,
  4397. };
  4398. typedef struct lfs1 {
  4399. lfs_block_t root[2];
  4400. } lfs1_t;
  4401. typedef struct lfs1_entry {
  4402. lfs_off_t off;
  4403. struct lfs1_disk_entry {
  4404. uint8_t type;
  4405. uint8_t elen;
  4406. uint8_t alen;
  4407. uint8_t nlen;
  4408. union {
  4409. struct {
  4410. lfs_block_t head;
  4411. lfs_size_t size;
  4412. } file;
  4413. lfs_block_t dir[2];
  4414. } u;
  4415. } d;
  4416. } lfs1_entry_t;
  4417. typedef struct lfs1_dir {
  4418. struct lfs1_dir *next;
  4419. lfs_block_t pair[2];
  4420. lfs_off_t off;
  4421. lfs_block_t head[2];
  4422. lfs_off_t pos;
  4423. struct lfs1_disk_dir {
  4424. uint32_t rev;
  4425. lfs_size_t size;
  4426. lfs_block_t tail[2];
  4427. } d;
  4428. } lfs1_dir_t;
  4429. typedef struct lfs1_superblock {
  4430. lfs_off_t off;
  4431. struct lfs1_disk_superblock {
  4432. uint8_t type;
  4433. uint8_t elen;
  4434. uint8_t alen;
  4435. uint8_t nlen;
  4436. lfs_block_t root[2];
  4437. uint32_t block_size;
  4438. uint32_t block_count;
  4439. uint32_t version;
  4440. char magic[8];
  4441. } d;
  4442. } lfs1_superblock_t;
  4443. /// Low-level wrappers v1->v2 ///
  4444. static void lfs1_crc(uint32_t *crc, const void *buffer, size_t size) {
  4445. *crc = lfs_crc(*crc, buffer, size);
  4446. }
  4447. static int lfs1_bd_read(lfs_t *lfs, lfs_block_t block,
  4448. lfs_off_t off, void *buffer, lfs_size_t size) {
  4449. // if we ever do more than writes to alternating pairs,
  4450. // this may need to consider pcache
  4451. return lfs_bd_read(lfs, &lfs->pcache, &lfs->rcache, size,
  4452. block, off, buffer, size);
  4453. }
  4454. static int lfs1_bd_crc(lfs_t *lfs, lfs_block_t block,
  4455. lfs_off_t off, lfs_size_t size, uint32_t *crc) {
  4456. for (lfs_off_t i = 0; i < size; i++) {
  4457. uint8_t c;
  4458. int err = lfs1_bd_read(lfs, block, off+i, &c, 1);
  4459. if (err) {
  4460. return err;
  4461. }
  4462. lfs1_crc(crc, &c, 1);
  4463. }
  4464. return 0;
  4465. }
  4466. /// Endian swapping functions ///
  4467. static void lfs1_dir_fromle32(struct lfs1_disk_dir *d) {
  4468. d->rev = lfs_fromle32(d->rev);
  4469. d->size = lfs_fromle32(d->size);
  4470. d->tail[0] = lfs_fromle32(d->tail[0]);
  4471. d->tail[1] = lfs_fromle32(d->tail[1]);
  4472. }
  4473. static void lfs1_dir_tole32(struct lfs1_disk_dir *d) {
  4474. d->rev = lfs_tole32(d->rev);
  4475. d->size = lfs_tole32(d->size);
  4476. d->tail[0] = lfs_tole32(d->tail[0]);
  4477. d->tail[1] = lfs_tole32(d->tail[1]);
  4478. }
  4479. static void lfs1_entry_fromle32(struct lfs1_disk_entry *d) {
  4480. d->u.dir[0] = lfs_fromle32(d->u.dir[0]);
  4481. d->u.dir[1] = lfs_fromle32(d->u.dir[1]);
  4482. }
  4483. static void lfs1_entry_tole32(struct lfs1_disk_entry *d) {
  4484. d->u.dir[0] = lfs_tole32(d->u.dir[0]);
  4485. d->u.dir[1] = lfs_tole32(d->u.dir[1]);
  4486. }
  4487. static void lfs1_superblock_fromle32(struct lfs1_disk_superblock *d) {
  4488. d->root[0] = lfs_fromle32(d->root[0]);
  4489. d->root[1] = lfs_fromle32(d->root[1]);
  4490. d->block_size = lfs_fromle32(d->block_size);
  4491. d->block_count = lfs_fromle32(d->block_count);
  4492. d->version = lfs_fromle32(d->version);
  4493. }
  4494. ///// Metadata pair and directory operations ///
  4495. static inline lfs_size_t lfs1_entry_size(const lfs1_entry_t *entry) {
  4496. return 4 + entry->d.elen + entry->d.alen + entry->d.nlen;
  4497. }
  4498. static int lfs1_dir_fetch(lfs_t *lfs,
  4499. lfs1_dir_t *dir, const lfs_block_t pair[2]) {
  4500. // copy out pair, otherwise may be aliasing dir
  4501. const lfs_block_t tpair[2] = {pair[0], pair[1]};
  4502. bool valid = false;
  4503. // check both blocks for the most recent revision
  4504. for (int i = 0; i < 2; i++) {
  4505. struct lfs1_disk_dir test;
  4506. int err = lfs1_bd_read(lfs, tpair[i], 0, &test, sizeof(test));
  4507. lfs1_dir_fromle32(&test);
  4508. if (err) {
  4509. if (err == LFS_ERR_CORRUPT) {
  4510. continue;
  4511. }
  4512. return err;
  4513. }
  4514. if (valid && lfs_scmp(test.rev, dir->d.rev) < 0) {
  4515. continue;
  4516. }
  4517. if ((0x7fffffff & test.size) < sizeof(test)+4 ||
  4518. (0x7fffffff & test.size) > lfs->cfg->block_size) {
  4519. continue;
  4520. }
  4521. uint32_t crc = 0xffffffff;
  4522. lfs1_dir_tole32(&test);
  4523. lfs1_crc(&crc, &test, sizeof(test));
  4524. lfs1_dir_fromle32(&test);
  4525. err = lfs1_bd_crc(lfs, tpair[i], sizeof(test),
  4526. (0x7fffffff & test.size) - sizeof(test), &crc);
  4527. if (err) {
  4528. if (err == LFS_ERR_CORRUPT) {
  4529. continue;
  4530. }
  4531. return err;
  4532. }
  4533. if (crc != 0) {
  4534. continue;
  4535. }
  4536. valid = true;
  4537. // setup dir in case it's valid
  4538. dir->pair[0] = tpair[(i+0) % 2];
  4539. dir->pair[1] = tpair[(i+1) % 2];
  4540. dir->off = sizeof(dir->d);
  4541. dir->d = test;
  4542. }
  4543. if (!valid) {
  4544. LFS_ERROR("Corrupted dir pair at {0x%"PRIx32", 0x%"PRIx32"}",
  4545. tpair[0], tpair[1]);
  4546. return LFS_ERR_CORRUPT;
  4547. }
  4548. return 0;
  4549. }
  4550. static int lfs1_dir_next(lfs_t *lfs, lfs1_dir_t *dir, lfs1_entry_t *entry) {
  4551. while (dir->off + sizeof(entry->d) > (0x7fffffff & dir->d.size)-4) {
  4552. if (!(0x80000000 & dir->d.size)) {
  4553. entry->off = dir->off;
  4554. return LFS_ERR_NOENT;
  4555. }
  4556. int err = lfs1_dir_fetch(lfs, dir, dir->d.tail);
  4557. if (err) {
  4558. return err;
  4559. }
  4560. dir->off = sizeof(dir->d);
  4561. dir->pos += sizeof(dir->d) + 4;
  4562. }
  4563. int err = lfs1_bd_read(lfs, dir->pair[0], dir->off,
  4564. &entry->d, sizeof(entry->d));
  4565. lfs1_entry_fromle32(&entry->d);
  4566. if (err) {
  4567. return err;
  4568. }
  4569. entry->off = dir->off;
  4570. dir->off += lfs1_entry_size(entry);
  4571. dir->pos += lfs1_entry_size(entry);
  4572. return 0;
  4573. }
  4574. /// littlefs v1 specific operations ///
  4575. int lfs1_traverse(lfs_t *lfs, int (*cb)(void*, lfs_block_t), void *data) {
  4576. if (lfs_pair_isnull(lfs->lfs1->root)) {
  4577. return 0;
  4578. }
  4579. // iterate over metadata pairs
  4580. lfs1_dir_t dir;
  4581. lfs1_entry_t entry;
  4582. lfs_block_t cwd[2] = {0, 1};
  4583. while (true) {
  4584. for (int i = 0; i < 2; i++) {
  4585. int err = cb(data, cwd[i]);
  4586. if (err) {
  4587. return err;
  4588. }
  4589. }
  4590. int err = lfs1_dir_fetch(lfs, &dir, cwd);
  4591. if (err) {
  4592. return err;
  4593. }
  4594. // iterate over contents
  4595. while (dir.off + sizeof(entry.d) <= (0x7fffffff & dir.d.size)-4) {
  4596. err = lfs1_bd_read(lfs, dir.pair[0], dir.off,
  4597. &entry.d, sizeof(entry.d));
  4598. lfs1_entry_fromle32(&entry.d);
  4599. if (err) {
  4600. return err;
  4601. }
  4602. dir.off += lfs1_entry_size(&entry);
  4603. if ((0x70 & entry.d.type) == (0x70 & LFS1_TYPE_REG)) {
  4604. err = lfs_ctz_traverse(lfs, NULL, &lfs->rcache,
  4605. entry.d.u.file.head, entry.d.u.file.size, cb, data);
  4606. if (err) {
  4607. return err;
  4608. }
  4609. }
  4610. }
  4611. // we also need to check if we contain a threaded v2 directory
  4612. lfs_mdir_t dir2 = {.split=true, .tail={cwd[0], cwd[1]}};
  4613. while (dir2.split) {
  4614. err = lfs_dir_fetch(lfs, &dir2, dir2.tail);
  4615. if (err) {
  4616. break;
  4617. }
  4618. for (int i = 0; i < 2; i++) {
  4619. err = cb(data, dir2.pair[i]);
  4620. if (err) {
  4621. return err;
  4622. }
  4623. }
  4624. }
  4625. cwd[0] = dir.d.tail[0];
  4626. cwd[1] = dir.d.tail[1];
  4627. if (lfs_pair_isnull(cwd)) {
  4628. break;
  4629. }
  4630. }
  4631. return 0;
  4632. }
  4633. static int lfs1_moved(lfs_t *lfs, const void *e) {
  4634. if (lfs_pair_isnull(lfs->lfs1->root)) {
  4635. return 0;
  4636. }
  4637. // skip superblock
  4638. lfs1_dir_t cwd;
  4639. int err = lfs1_dir_fetch(lfs, &cwd, (const lfs_block_t[2]){0, 1});
  4640. if (err) {
  4641. return err;
  4642. }
  4643. // iterate over all directory directory entries
  4644. lfs1_entry_t entry;
  4645. while (!lfs_pair_isnull(cwd.d.tail)) {
  4646. err = lfs1_dir_fetch(lfs, &cwd, cwd.d.tail);
  4647. if (err) {
  4648. return err;
  4649. }
  4650. while (true) {
  4651. err = lfs1_dir_next(lfs, &cwd, &entry);
  4652. if (err && err != LFS_ERR_NOENT) {
  4653. return err;
  4654. }
  4655. if (err == LFS_ERR_NOENT) {
  4656. break;
  4657. }
  4658. if (!(0x80 & entry.d.type) &&
  4659. memcmp(&entry.d.u, e, sizeof(entry.d.u)) == 0) {
  4660. return true;
  4661. }
  4662. }
  4663. }
  4664. return false;
  4665. }
  4666. /// Filesystem operations ///
  4667. static int lfs1_mount(lfs_t *lfs, struct lfs1 *lfs1,
  4668. const struct lfs_config *cfg) {
  4669. int err = 0;
  4670. {
  4671. err = lfs_init(lfs, cfg);
  4672. if (err) {
  4673. return err;
  4674. }
  4675. lfs->lfs1 = lfs1;
  4676. lfs->lfs1->root[0] = LFS_BLOCK_NULL;
  4677. lfs->lfs1->root[1] = LFS_BLOCK_NULL;
  4678. // setup free lookahead
  4679. lfs->free.off = 0;
  4680. lfs->free.size = 0;
  4681. lfs->free.i = 0;
  4682. lfs_alloc_ack(lfs);
  4683. // load superblock
  4684. lfs1_dir_t dir;
  4685. lfs1_superblock_t superblock;
  4686. err = lfs1_dir_fetch(lfs, &dir, (const lfs_block_t[2]){0, 1});
  4687. if (err && err != LFS_ERR_CORRUPT) {
  4688. goto cleanup;
  4689. }
  4690. if (!err) {
  4691. err = lfs1_bd_read(lfs, dir.pair[0], sizeof(dir.d),
  4692. &superblock.d, sizeof(superblock.d));
  4693. lfs1_superblock_fromle32(&superblock.d);
  4694. if (err) {
  4695. goto cleanup;
  4696. }
  4697. lfs->lfs1->root[0] = superblock.d.root[0];
  4698. lfs->lfs1->root[1] = superblock.d.root[1];
  4699. }
  4700. if (err || memcmp(superblock.d.magic, "littlefs", 8) != 0) {
  4701. LFS_ERROR("Invalid superblock at {0x%"PRIx32", 0x%"PRIx32"}",
  4702. 0, 1);
  4703. err = LFS_ERR_CORRUPT;
  4704. goto cleanup;
  4705. }
  4706. uint16_t major_version = (0xffff & (superblock.d.version >> 16));
  4707. uint16_t minor_version = (0xffff & (superblock.d.version >> 0));
  4708. if ((major_version != LFS1_DISK_VERSION_MAJOR ||
  4709. minor_version > LFS1_DISK_VERSION_MINOR)) {
  4710. LFS_ERROR("Invalid version v%d.%d", major_version, minor_version);
  4711. err = LFS_ERR_INVAL;
  4712. goto cleanup;
  4713. }
  4714. return 0;
  4715. }
  4716. cleanup:
  4717. lfs_deinit(lfs);
  4718. return err;
  4719. }
  4720. static int lfs1_unmount(lfs_t *lfs) {
  4721. return lfs_deinit(lfs);
  4722. }
  4723. /// v1 migration ///
  4724. static int lfs_rawmigrate(lfs_t *lfs, const struct lfs_config *cfg) {
  4725. struct lfs1 lfs1;
  4726. // Indeterminate filesystem size not allowed for migration.
  4727. LFS_ASSERT(cfg->block_count != 0);
  4728. int err = lfs1_mount(lfs, &lfs1, cfg);
  4729. if (err) {
  4730. return err;
  4731. }
  4732. {
  4733. // iterate through each directory, copying over entries
  4734. // into new directory
  4735. lfs1_dir_t dir1;
  4736. lfs_mdir_t dir2;
  4737. dir1.d.tail[0] = lfs->lfs1->root[0];
  4738. dir1.d.tail[1] = lfs->lfs1->root[1];
  4739. while (!lfs_pair_isnull(dir1.d.tail)) {
  4740. // iterate old dir
  4741. err = lfs1_dir_fetch(lfs, &dir1, dir1.d.tail);
  4742. if (err) {
  4743. goto cleanup;
  4744. }
  4745. // create new dir and bind as temporary pretend root
  4746. err = lfs_dir_alloc(lfs, &dir2);
  4747. if (err) {
  4748. goto cleanup;
  4749. }
  4750. dir2.rev = dir1.d.rev;
  4751. dir1.head[0] = dir1.pair[0];
  4752. dir1.head[1] = dir1.pair[1];
  4753. lfs->root[0] = dir2.pair[0];
  4754. lfs->root[1] = dir2.pair[1];
  4755. err = lfs_dir_commit(lfs, &dir2, NULL, 0);
  4756. if (err) {
  4757. goto cleanup;
  4758. }
  4759. while (true) {
  4760. lfs1_entry_t entry1;
  4761. err = lfs1_dir_next(lfs, &dir1, &entry1);
  4762. if (err && err != LFS_ERR_NOENT) {
  4763. goto cleanup;
  4764. }
  4765. if (err == LFS_ERR_NOENT) {
  4766. break;
  4767. }
  4768. // check that entry has not been moved
  4769. if (entry1.d.type & 0x80) {
  4770. int moved = lfs1_moved(lfs, &entry1.d.u);
  4771. if (moved < 0) {
  4772. err = moved;
  4773. goto cleanup;
  4774. }
  4775. if (moved) {
  4776. continue;
  4777. }
  4778. entry1.d.type &= ~0x80;
  4779. }
  4780. // also fetch name
  4781. char name[LFS_NAME_MAX+1];
  4782. memset(name, 0, sizeof(name));
  4783. err = lfs1_bd_read(lfs, dir1.pair[0],
  4784. entry1.off + 4+entry1.d.elen+entry1.d.alen,
  4785. name, entry1.d.nlen);
  4786. if (err) {
  4787. goto cleanup;
  4788. }
  4789. bool isdir = (entry1.d.type == LFS1_TYPE_DIR);
  4790. // create entry in new dir
  4791. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4792. if (err) {
  4793. goto cleanup;
  4794. }
  4795. uint16_t id;
  4796. err = lfs_dir_find(lfs, &dir2, &(const char*){name}, &id);
  4797. if (!(err == LFS_ERR_NOENT && id != 0x3ff)) {
  4798. err = (err < 0) ? err : LFS_ERR_EXIST;
  4799. goto cleanup;
  4800. }
  4801. lfs1_entry_tole32(&entry1.d);
  4802. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4803. {LFS_MKTAG(LFS_TYPE_CREATE, id, 0), NULL},
  4804. {LFS_MKTAG_IF_ELSE(isdir,
  4805. LFS_TYPE_DIR, id, entry1.d.nlen,
  4806. LFS_TYPE_REG, id, entry1.d.nlen),
  4807. name},
  4808. {LFS_MKTAG_IF_ELSE(isdir,
  4809. LFS_TYPE_DIRSTRUCT, id, sizeof(entry1.d.u),
  4810. LFS_TYPE_CTZSTRUCT, id, sizeof(entry1.d.u)),
  4811. &entry1.d.u}));
  4812. lfs1_entry_fromle32(&entry1.d);
  4813. if (err) {
  4814. goto cleanup;
  4815. }
  4816. }
  4817. if (!lfs_pair_isnull(dir1.d.tail)) {
  4818. // find last block and update tail to thread into fs
  4819. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4820. if (err) {
  4821. goto cleanup;
  4822. }
  4823. while (dir2.split) {
  4824. err = lfs_dir_fetch(lfs, &dir2, dir2.tail);
  4825. if (err) {
  4826. goto cleanup;
  4827. }
  4828. }
  4829. lfs_pair_tole32(dir2.pair);
  4830. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4831. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir1.d.tail}));
  4832. lfs_pair_fromle32(dir2.pair);
  4833. if (err) {
  4834. goto cleanup;
  4835. }
  4836. }
  4837. // Copy over first block to thread into fs. Unfortunately
  4838. // if this fails there is not much we can do.
  4839. LFS_DEBUG("Migrating {0x%"PRIx32", 0x%"PRIx32"} "
  4840. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  4841. lfs->root[0], lfs->root[1], dir1.head[0], dir1.head[1]);
  4842. err = lfs_bd_erase(lfs, dir1.head[1]);
  4843. if (err) {
  4844. goto cleanup;
  4845. }
  4846. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4847. if (err) {
  4848. goto cleanup;
  4849. }
  4850. for (lfs_off_t i = 0; i < dir2.off; i++) {
  4851. uint8_t dat;
  4852. err = lfs_bd_read(lfs,
  4853. NULL, &lfs->rcache, dir2.off,
  4854. dir2.pair[0], i, &dat, 1);
  4855. if (err) {
  4856. goto cleanup;
  4857. }
  4858. err = lfs_bd_prog(lfs,
  4859. &lfs->pcache, &lfs->rcache, true,
  4860. dir1.head[1], i, &dat, 1);
  4861. if (err) {
  4862. goto cleanup;
  4863. }
  4864. }
  4865. err = lfs_bd_flush(lfs, &lfs->pcache, &lfs->rcache, true);
  4866. if (err) {
  4867. goto cleanup;
  4868. }
  4869. }
  4870. // Create new superblock. This marks a successful migration!
  4871. err = lfs1_dir_fetch(lfs, &dir1, (const lfs_block_t[2]){0, 1});
  4872. if (err) {
  4873. goto cleanup;
  4874. }
  4875. dir2.pair[0] = dir1.pair[0];
  4876. dir2.pair[1] = dir1.pair[1];
  4877. dir2.rev = dir1.d.rev;
  4878. dir2.off = sizeof(dir2.rev);
  4879. dir2.etag = 0xffffffff;
  4880. dir2.count = 0;
  4881. dir2.tail[0] = lfs->lfs1->root[0];
  4882. dir2.tail[1] = lfs->lfs1->root[1];
  4883. dir2.erased = false;
  4884. dir2.split = true;
  4885. lfs_superblock_t superblock = {
  4886. .version = LFS_DISK_VERSION,
  4887. .block_size = lfs->cfg->block_size,
  4888. .block_count = lfs->cfg->block_count,
  4889. .name_max = lfs->name_max,
  4890. .file_max = lfs->file_max,
  4891. .attr_max = lfs->attr_max,
  4892. };
  4893. lfs_superblock_tole32(&superblock);
  4894. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4895. {LFS_MKTAG(LFS_TYPE_CREATE, 0, 0), NULL},
  4896. {LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
  4897. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4898. &superblock}));
  4899. if (err) {
  4900. goto cleanup;
  4901. }
  4902. // sanity check that fetch works
  4903. err = lfs_dir_fetch(lfs, &dir2, (const lfs_block_t[2]){0, 1});
  4904. if (err) {
  4905. goto cleanup;
  4906. }
  4907. // force compaction to prevent accidentally mounting v1
  4908. dir2.erased = false;
  4909. err = lfs_dir_commit(lfs, &dir2, NULL, 0);
  4910. if (err) {
  4911. goto cleanup;
  4912. }
  4913. }
  4914. cleanup:
  4915. lfs1_unmount(lfs);
  4916. return err;
  4917. }
  4918. #endif
  4919. /// Public API wrappers ///
  4920. // Here we can add tracing/thread safety easily
  4921. // Thread-safe wrappers if enabled
  4922. #ifdef LFS_THREADSAFE
  4923. #define LFS_LOCK(cfg) cfg->lock(cfg)
  4924. #define LFS_UNLOCK(cfg) cfg->unlock(cfg)
  4925. #else
  4926. #define LFS_LOCK(cfg) ((void)cfg, 0)
  4927. #define LFS_UNLOCK(cfg) ((void)cfg)
  4928. #endif
  4929. // Public API
  4930. #ifndef LFS_READONLY
  4931. int lfs_format(lfs_t *lfs, const struct lfs_config *cfg) {
  4932. int err = LFS_LOCK(cfg);
  4933. if (err) {
  4934. return err;
  4935. }
  4936. LFS_TRACE("lfs_format(%p, %p {.context=%p, "
  4937. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  4938. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  4939. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  4940. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  4941. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  4942. ".prog_buffer=%p, .lookahead_buffer=%p, "
  4943. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  4944. ".attr_max=%"PRIu32"})",
  4945. (void*)lfs, (void*)cfg, cfg->context,
  4946. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  4947. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  4948. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  4949. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  4950. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  4951. cfg->name_max, cfg->file_max, cfg->attr_max);
  4952. err = lfs_rawformat(lfs, cfg);
  4953. LFS_TRACE("lfs_format -> %d", err);
  4954. LFS_UNLOCK(cfg);
  4955. return err;
  4956. }
  4957. #endif
  4958. int lfs_mount(lfs_t *lfs, const struct lfs_config *cfg) {
  4959. int err = LFS_LOCK(cfg);
  4960. if (err) {
  4961. return err;
  4962. }
  4963. LFS_TRACE("lfs_mount(%p, %p {.context=%p, "
  4964. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  4965. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  4966. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  4967. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  4968. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  4969. ".prog_buffer=%p, .lookahead_buffer=%p, "
  4970. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  4971. ".attr_max=%"PRIu32"})",
  4972. (void*)lfs, (void*)cfg, cfg->context,
  4973. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  4974. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  4975. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  4976. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  4977. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  4978. cfg->name_max, cfg->file_max, cfg->attr_max);
  4979. err = lfs_rawmount(lfs, cfg);
  4980. LFS_TRACE("lfs_mount -> %d", err);
  4981. LFS_UNLOCK(cfg);
  4982. return err;
  4983. }
  4984. int lfs_unmount(lfs_t *lfs) {
  4985. int err = LFS_LOCK(lfs->cfg);
  4986. if (err) {
  4987. return err;
  4988. }
  4989. LFS_TRACE("lfs_unmount(%p)", (void*)lfs);
  4990. err = lfs_rawunmount(lfs);
  4991. LFS_TRACE("lfs_unmount -> %d", err);
  4992. LFS_UNLOCK(lfs->cfg);
  4993. return err;
  4994. }
  4995. #ifndef LFS_READONLY
  4996. int lfs_remove(lfs_t *lfs, const char *path) {
  4997. int err = LFS_LOCK(lfs->cfg);
  4998. if (err) {
  4999. return err;
  5000. }
  5001. LFS_TRACE("lfs_remove(%p, \"%s\")", (void*)lfs, path);
  5002. err = lfs_rawremove(lfs, path);
  5003. LFS_TRACE("lfs_remove -> %d", err);
  5004. LFS_UNLOCK(lfs->cfg);
  5005. return err;
  5006. }
  5007. #endif
  5008. #ifndef LFS_READONLY
  5009. int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath) {
  5010. int err = LFS_LOCK(lfs->cfg);
  5011. if (err) {
  5012. return err;
  5013. }
  5014. LFS_TRACE("lfs_rename(%p, \"%s\", \"%s\")", (void*)lfs, oldpath, newpath);
  5015. err = lfs_rawrename(lfs, oldpath, newpath);
  5016. LFS_TRACE("lfs_rename -> %d", err);
  5017. LFS_UNLOCK(lfs->cfg);
  5018. return err;
  5019. }
  5020. #endif
  5021. int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info) {
  5022. int err = LFS_LOCK(lfs->cfg);
  5023. if (err) {
  5024. return err;
  5025. }
  5026. LFS_TRACE("lfs_stat(%p, \"%s\", %p)", (void*)lfs, path, (void*)info);
  5027. err = lfs_rawstat(lfs, path, info);
  5028. LFS_TRACE("lfs_stat -> %d", err);
  5029. LFS_UNLOCK(lfs->cfg);
  5030. return err;
  5031. }
  5032. lfs_ssize_t lfs_getattr(lfs_t *lfs, const char *path,
  5033. uint8_t type, void *buffer, lfs_size_t size) {
  5034. int err = LFS_LOCK(lfs->cfg);
  5035. if (err) {
  5036. return err;
  5037. }
  5038. LFS_TRACE("lfs_getattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
  5039. (void*)lfs, path, type, buffer, size);
  5040. lfs_ssize_t res = lfs_rawgetattr(lfs, path, type, buffer, size);
  5041. LFS_TRACE("lfs_getattr -> %"PRId32, res);
  5042. LFS_UNLOCK(lfs->cfg);
  5043. return res;
  5044. }
  5045. #ifndef LFS_READONLY
  5046. int lfs_setattr(lfs_t *lfs, const char *path,
  5047. uint8_t type, const void *buffer, lfs_size_t size) {
  5048. int err = LFS_LOCK(lfs->cfg);
  5049. if (err) {
  5050. return err;
  5051. }
  5052. LFS_TRACE("lfs_setattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
  5053. (void*)lfs, path, type, buffer, size);
  5054. err = lfs_rawsetattr(lfs, path, type, buffer, size);
  5055. LFS_TRACE("lfs_setattr -> %d", err);
  5056. LFS_UNLOCK(lfs->cfg);
  5057. return err;
  5058. }
  5059. #endif
  5060. #ifndef LFS_READONLY
  5061. int lfs_removeattr(lfs_t *lfs, const char *path, uint8_t type) {
  5062. int err = LFS_LOCK(lfs->cfg);
  5063. if (err) {
  5064. return err;
  5065. }
  5066. LFS_TRACE("lfs_removeattr(%p, \"%s\", %"PRIu8")", (void*)lfs, path, type);
  5067. err = lfs_rawremoveattr(lfs, path, type);
  5068. LFS_TRACE("lfs_removeattr -> %d", err);
  5069. LFS_UNLOCK(lfs->cfg);
  5070. return err;
  5071. }
  5072. #endif
  5073. #ifndef LFS_NO_MALLOC
  5074. int lfs_file_open(lfs_t *lfs, lfs_file_t *file, const char *path, int flags) {
  5075. int err = LFS_LOCK(lfs->cfg);
  5076. if (err) {
  5077. return err;
  5078. }
  5079. LFS_TRACE("lfs_file_open(%p, %p, \"%s\", %x)",
  5080. (void*)lfs, (void*)file, path, flags);
  5081. LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5082. err = lfs_file_rawopen(lfs, file, path, flags);
  5083. LFS_TRACE("lfs_file_open -> %d", err);
  5084. LFS_UNLOCK(lfs->cfg);
  5085. return err;
  5086. }
  5087. #endif
  5088. int lfs_file_opencfg(lfs_t *lfs, lfs_file_t *file,
  5089. const char *path, int flags,
  5090. const struct lfs_file_config *cfg) {
  5091. int err = LFS_LOCK(lfs->cfg);
  5092. if (err) {
  5093. return err;
  5094. }
  5095. LFS_TRACE("lfs_file_opencfg(%p, %p, \"%s\", %x, %p {"
  5096. ".buffer=%p, .attrs=%p, .attr_count=%"PRIu32"})",
  5097. (void*)lfs, (void*)file, path, flags,
  5098. (void*)cfg, cfg->buffer, (void*)cfg->attrs, cfg->attr_count);
  5099. LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5100. err = lfs_file_rawopencfg(lfs, file, path, flags, cfg);
  5101. LFS_TRACE("lfs_file_opencfg -> %d", err);
  5102. LFS_UNLOCK(lfs->cfg);
  5103. return err;
  5104. }
  5105. int lfs_file_close(lfs_t *lfs, lfs_file_t *file) {
  5106. int err = LFS_LOCK(lfs->cfg);
  5107. if (err) {
  5108. return err;
  5109. }
  5110. LFS_TRACE("lfs_file_close(%p, %p)", (void*)lfs, (void*)file);
  5111. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5112. err = lfs_file_rawclose(lfs, file);
  5113. LFS_TRACE("lfs_file_close -> %d", err);
  5114. LFS_UNLOCK(lfs->cfg);
  5115. return err;
  5116. }
  5117. #ifndef LFS_READONLY
  5118. int lfs_file_sync(lfs_t *lfs, lfs_file_t *file) {
  5119. int err = LFS_LOCK(lfs->cfg);
  5120. if (err) {
  5121. return err;
  5122. }
  5123. LFS_TRACE("lfs_file_sync(%p, %p)", (void*)lfs, (void*)file);
  5124. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5125. err = lfs_file_rawsync(lfs, file);
  5126. LFS_TRACE("lfs_file_sync -> %d", err);
  5127. LFS_UNLOCK(lfs->cfg);
  5128. return err;
  5129. }
  5130. #endif
  5131. lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file,
  5132. void *buffer, lfs_size_t size) {
  5133. int err = LFS_LOCK(lfs->cfg);
  5134. if (err) {
  5135. return err;
  5136. }
  5137. LFS_TRACE("lfs_file_read(%p, %p, %p, %"PRIu32")",
  5138. (void*)lfs, (void*)file, buffer, size);
  5139. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5140. lfs_ssize_t res = lfs_file_rawread(lfs, file, buffer, size);
  5141. LFS_TRACE("lfs_file_read -> %"PRId32, res);
  5142. LFS_UNLOCK(lfs->cfg);
  5143. return res;
  5144. }
  5145. #ifndef LFS_READONLY
  5146. lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file,
  5147. const void *buffer, lfs_size_t size) {
  5148. int err = LFS_LOCK(lfs->cfg);
  5149. if (err) {
  5150. return err;
  5151. }
  5152. LFS_TRACE("lfs_file_write(%p, %p, %p, %"PRIu32")",
  5153. (void*)lfs, (void*)file, buffer, size);
  5154. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5155. lfs_ssize_t res = lfs_file_rawwrite(lfs, file, buffer, size);
  5156. LFS_TRACE("lfs_file_write -> %"PRId32, res);
  5157. LFS_UNLOCK(lfs->cfg);
  5158. return res;
  5159. }
  5160. #endif
  5161. lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file,
  5162. lfs_soff_t off, int whence) {
  5163. int err = LFS_LOCK(lfs->cfg);
  5164. if (err) {
  5165. return err;
  5166. }
  5167. LFS_TRACE("lfs_file_seek(%p, %p, %"PRId32", %d)",
  5168. (void*)lfs, (void*)file, off, whence);
  5169. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5170. lfs_soff_t res = lfs_file_rawseek(lfs, file, off, whence);
  5171. LFS_TRACE("lfs_file_seek -> %"PRId32, res);
  5172. LFS_UNLOCK(lfs->cfg);
  5173. return res;
  5174. }
  5175. #ifndef LFS_READONLY
  5176. int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size) {
  5177. int err = LFS_LOCK(lfs->cfg);
  5178. if (err) {
  5179. return err;
  5180. }
  5181. LFS_TRACE("lfs_file_truncate(%p, %p, %"PRIu32")",
  5182. (void*)lfs, (void*)file, size);
  5183. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5184. err = lfs_file_rawtruncate(lfs, file, size);
  5185. LFS_TRACE("lfs_file_truncate -> %d", err);
  5186. LFS_UNLOCK(lfs->cfg);
  5187. return err;
  5188. }
  5189. #endif
  5190. lfs_soff_t lfs_file_tell(lfs_t *lfs, lfs_file_t *file) {
  5191. int err = LFS_LOCK(lfs->cfg);
  5192. if (err) {
  5193. return err;
  5194. }
  5195. LFS_TRACE("lfs_file_tell(%p, %p)", (void*)lfs, (void*)file);
  5196. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5197. lfs_soff_t res = lfs_file_rawtell(lfs, file);
  5198. LFS_TRACE("lfs_file_tell -> %"PRId32, res);
  5199. LFS_UNLOCK(lfs->cfg);
  5200. return res;
  5201. }
  5202. int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file) {
  5203. int err = LFS_LOCK(lfs->cfg);
  5204. if (err) {
  5205. return err;
  5206. }
  5207. LFS_TRACE("lfs_file_rewind(%p, %p)", (void*)lfs, (void*)file);
  5208. err = lfs_file_rawrewind(lfs, file);
  5209. LFS_TRACE("lfs_file_rewind -> %d", err);
  5210. LFS_UNLOCK(lfs->cfg);
  5211. return err;
  5212. }
  5213. lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file) {
  5214. int err = LFS_LOCK(lfs->cfg);
  5215. if (err) {
  5216. return err;
  5217. }
  5218. LFS_TRACE("lfs_file_size(%p, %p)", (void*)lfs, (void*)file);
  5219. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5220. lfs_soff_t res = lfs_file_rawsize(lfs, file);
  5221. LFS_TRACE("lfs_file_size -> %"PRId32, res);
  5222. LFS_UNLOCK(lfs->cfg);
  5223. return res;
  5224. }
  5225. #ifndef LFS_READONLY
  5226. int lfs_mkdir(lfs_t *lfs, const char *path) {
  5227. int err = LFS_LOCK(lfs->cfg);
  5228. if (err) {
  5229. return err;
  5230. }
  5231. LFS_TRACE("lfs_mkdir(%p, \"%s\")", (void*)lfs, path);
  5232. err = lfs_rawmkdir(lfs, path);
  5233. LFS_TRACE("lfs_mkdir -> %d", err);
  5234. LFS_UNLOCK(lfs->cfg);
  5235. return err;
  5236. }
  5237. #endif
  5238. int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path) {
  5239. int err = LFS_LOCK(lfs->cfg);
  5240. if (err) {
  5241. return err;
  5242. }
  5243. LFS_TRACE("lfs_dir_open(%p, %p, \"%s\")", (void*)lfs, (void*)dir, path);
  5244. LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)dir));
  5245. err = lfs_dir_rawopen(lfs, dir, path);
  5246. LFS_TRACE("lfs_dir_open -> %d", err);
  5247. LFS_UNLOCK(lfs->cfg);
  5248. return err;
  5249. }
  5250. int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir) {
  5251. int err = LFS_LOCK(lfs->cfg);
  5252. if (err) {
  5253. return err;
  5254. }
  5255. LFS_TRACE("lfs_dir_close(%p, %p)", (void*)lfs, (void*)dir);
  5256. err = lfs_dir_rawclose(lfs, dir);
  5257. LFS_TRACE("lfs_dir_close -> %d", err);
  5258. LFS_UNLOCK(lfs->cfg);
  5259. return err;
  5260. }
  5261. int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info) {
  5262. int err = LFS_LOCK(lfs->cfg);
  5263. if (err) {
  5264. return err;
  5265. }
  5266. LFS_TRACE("lfs_dir_read(%p, %p, %p)",
  5267. (void*)lfs, (void*)dir, (void*)info);
  5268. err = lfs_dir_rawread(lfs, dir, info);
  5269. LFS_TRACE("lfs_dir_read -> %d", err);
  5270. LFS_UNLOCK(lfs->cfg);
  5271. return err;
  5272. }
  5273. int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off) {
  5274. int err = LFS_LOCK(lfs->cfg);
  5275. if (err) {
  5276. return err;
  5277. }
  5278. LFS_TRACE("lfs_dir_seek(%p, %p, %"PRIu32")",
  5279. (void*)lfs, (void*)dir, off);
  5280. err = lfs_dir_rawseek(lfs, dir, off);
  5281. LFS_TRACE("lfs_dir_seek -> %d", err);
  5282. LFS_UNLOCK(lfs->cfg);
  5283. return err;
  5284. }
  5285. lfs_soff_t lfs_dir_tell(lfs_t *lfs, lfs_dir_t *dir) {
  5286. int err = LFS_LOCK(lfs->cfg);
  5287. if (err) {
  5288. return err;
  5289. }
  5290. LFS_TRACE("lfs_dir_tell(%p, %p)", (void*)lfs, (void*)dir);
  5291. lfs_soff_t res = lfs_dir_rawtell(lfs, dir);
  5292. LFS_TRACE("lfs_dir_tell -> %"PRId32, res);
  5293. LFS_UNLOCK(lfs->cfg);
  5294. return res;
  5295. }
  5296. int lfs_dir_rewind(lfs_t *lfs, lfs_dir_t *dir) {
  5297. int err = LFS_LOCK(lfs->cfg);
  5298. if (err) {
  5299. return err;
  5300. }
  5301. LFS_TRACE("lfs_dir_rewind(%p, %p)", (void*)lfs, (void*)dir);
  5302. err = lfs_dir_rawrewind(lfs, dir);
  5303. LFS_TRACE("lfs_dir_rewind -> %d", err);
  5304. LFS_UNLOCK(lfs->cfg);
  5305. return err;
  5306. }
  5307. int lfs_fs_stat(lfs_t *lfs, struct lfs_fsinfo *fsinfo) {
  5308. int err = LFS_LOCK(lfs->cfg);
  5309. if (err) {
  5310. return err;
  5311. }
  5312. LFS_TRACE("lfs_fs_stat(%p, %p)", (void*)lfs, (void*)fsinfo);
  5313. err = lfs_fs_rawstat(lfs, fsinfo);
  5314. LFS_TRACE("lfs_fs_stat -> %d", err);
  5315. LFS_UNLOCK(lfs->cfg);
  5316. return err;
  5317. }
  5318. lfs_ssize_t lfs_fs_size(lfs_t *lfs) {
  5319. int err = LFS_LOCK(lfs->cfg);
  5320. if (err) {
  5321. return err;
  5322. }
  5323. LFS_TRACE("lfs_fs_size(%p)", (void*)lfs);
  5324. lfs_ssize_t res = lfs_fs_rawsize(lfs);
  5325. LFS_TRACE("lfs_fs_size -> %"PRId32, res);
  5326. LFS_UNLOCK(lfs->cfg);
  5327. return res;
  5328. }
  5329. int lfs_fs_traverse(lfs_t *lfs, int (*cb)(void *, lfs_block_t), void *data) {
  5330. int err = LFS_LOCK(lfs->cfg);
  5331. if (err) {
  5332. return err;
  5333. }
  5334. LFS_TRACE("lfs_fs_traverse(%p, %p, %p)",
  5335. (void*)lfs, (void*)(uintptr_t)cb, data);
  5336. err = lfs_fs_rawtraverse(lfs, cb, data, true);
  5337. LFS_TRACE("lfs_fs_traverse -> %d", err);
  5338. LFS_UNLOCK(lfs->cfg);
  5339. return err;
  5340. }
  5341. #ifndef LFS_READONLY
  5342. int lfs_fs_mkconsistent(lfs_t *lfs) {
  5343. int err = LFS_LOCK(lfs->cfg);
  5344. if (err) {
  5345. return err;
  5346. }
  5347. LFS_TRACE("lfs_fs_mkconsistent(%p)", (void*)lfs);
  5348. err = lfs_fs_rawmkconsistent(lfs);
  5349. LFS_TRACE("lfs_fs_mkconsistent -> %d", err);
  5350. LFS_UNLOCK(lfs->cfg);
  5351. return err;
  5352. }
  5353. #endif
  5354. #ifndef LFS_READONLY
  5355. int lfs_fs_grow(lfs_t *lfs, lfs_size_t block_count) {
  5356. int err = LFS_LOCK(lfs->cfg);
  5357. if (err) {
  5358. return err;
  5359. }
  5360. LFS_TRACE("lfs_fs_grow(%p, %"PRIu32")", (void*)lfs, block_count);
  5361. err = lfs_fs_rawgrow(lfs, block_count);
  5362. LFS_TRACE("lfs_fs_grow -> %d", err);
  5363. LFS_UNLOCK(lfs->cfg);
  5364. return err;
  5365. }
  5366. #endif
  5367. #ifdef LFS_MIGRATE
  5368. int lfs_migrate(lfs_t *lfs, const struct lfs_config *cfg) {
  5369. int err = LFS_LOCK(cfg);
  5370. if (err) {
  5371. return err;
  5372. }
  5373. LFS_TRACE("lfs_migrate(%p, %p {.context=%p, "
  5374. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  5375. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  5376. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  5377. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  5378. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  5379. ".prog_buffer=%p, .lookahead_buffer=%p, "
  5380. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  5381. ".attr_max=%"PRIu32"})",
  5382. (void*)lfs, (void*)cfg, cfg->context,
  5383. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  5384. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  5385. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  5386. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  5387. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  5388. cfg->name_max, cfg->file_max, cfg->attr_max);
  5389. err = lfs_rawmigrate(lfs, cfg);
  5390. LFS_TRACE("lfs_migrate -> %d", err);
  5391. LFS_UNLOCK(cfg);
  5392. return err;
  5393. }
  5394. #endif