lfs.c 191 KB

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