lfs.c 190 KB

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