lfs.c 189 KB

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