lfs.c 176 KB

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