lfs.c 193 KB

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