lfs.c 164 KB

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