lfs.c 193 KB

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