lfs.c 193 KB

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