lfs.c 186 KB

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