lfs.c 186 KB

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