lfs.c 184 KB

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