lfs.c 190 KB

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