lfs.c 179 KB

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