lfs.c 186 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331
  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. static int lfs_init(lfs_t *lfs, const struct lfs_config *cfg) {
  3541. lfs->cfg = cfg;
  3542. lfs->block_count = cfg->block_count; // May be 0
  3543. int err = 0;
  3544. #ifdef LFS_MULTIVERSION
  3545. // this driver only supports minor version < current minor version
  3546. LFS_ASSERT(!lfs->cfg->disk_version || (
  3547. (0xffff & (lfs->cfg->disk_version >> 16))
  3548. == LFS_DISK_VERSION_MAJOR
  3549. && (0xffff & (lfs->cfg->disk_version >> 0))
  3550. <= LFS_DISK_VERSION_MINOR));
  3551. #endif
  3552. // check that bool is a truthy-preserving type
  3553. //
  3554. // note the most common reason for this failure is a before-c99 compiler,
  3555. // which littlefs currently does not support
  3556. LFS_ASSERT((bool)0x80000000);
  3557. // validate that the lfs-cfg sizes were initiated properly before
  3558. // performing any arithmetic logics with them
  3559. LFS_ASSERT(lfs->cfg->read_size != 0);
  3560. LFS_ASSERT(lfs->cfg->prog_size != 0);
  3561. LFS_ASSERT(lfs->cfg->cache_size != 0);
  3562. // check that block size is a multiple of cache size is a multiple
  3563. // of prog and read sizes
  3564. LFS_ASSERT(lfs->cfg->cache_size % lfs->cfg->read_size == 0);
  3565. LFS_ASSERT(lfs->cfg->cache_size % lfs->cfg->prog_size == 0);
  3566. LFS_ASSERT(lfs->cfg->block_size % lfs->cfg->cache_size == 0);
  3567. // check that the block size is large enough to fit all ctz pointers
  3568. LFS_ASSERT(lfs->cfg->block_size >= 128);
  3569. // this is the exact calculation for all ctz pointers, if this fails
  3570. // and the simpler assert above does not, math must be broken
  3571. LFS_ASSERT(4*lfs_npw2(0xffffffff / (lfs->cfg->block_size-2*4))
  3572. <= lfs->cfg->block_size);
  3573. // block_cycles = 0 is no longer supported.
  3574. //
  3575. // block_cycles is the number of erase cycles before littlefs evicts
  3576. // metadata logs as a part of wear leveling. Suggested values are in the
  3577. // range of 100-1000, or set block_cycles to -1 to disable block-level
  3578. // wear-leveling.
  3579. LFS_ASSERT(lfs->cfg->block_cycles != 0);
  3580. // setup read cache
  3581. if (lfs->cfg->read_buffer) {
  3582. lfs->rcache.buffer = lfs->cfg->read_buffer;
  3583. } else {
  3584. lfs->rcache.buffer = lfs_malloc(lfs->cfg->cache_size);
  3585. if (!lfs->rcache.buffer) {
  3586. err = LFS_ERR_NOMEM;
  3587. goto cleanup;
  3588. }
  3589. }
  3590. // setup program cache
  3591. if (lfs->cfg->prog_buffer) {
  3592. lfs->pcache.buffer = lfs->cfg->prog_buffer;
  3593. } else {
  3594. lfs->pcache.buffer = lfs_malloc(lfs->cfg->cache_size);
  3595. if (!lfs->pcache.buffer) {
  3596. err = LFS_ERR_NOMEM;
  3597. goto cleanup;
  3598. }
  3599. }
  3600. // zero to avoid information leaks
  3601. lfs_cache_zero(lfs, &lfs->rcache);
  3602. lfs_cache_zero(lfs, &lfs->pcache);
  3603. // setup lookahead, must be multiple of 64-bits, 32-bit aligned
  3604. LFS_ASSERT(lfs->cfg->lookahead_size > 0);
  3605. LFS_ASSERT(lfs->cfg->lookahead_size % 8 == 0 &&
  3606. (uintptr_t)lfs->cfg->lookahead_buffer % 4 == 0);
  3607. if (lfs->cfg->lookahead_buffer) {
  3608. lfs->free.buffer = lfs->cfg->lookahead_buffer;
  3609. } else {
  3610. lfs->free.buffer = lfs_malloc(lfs->cfg->lookahead_size);
  3611. if (!lfs->free.buffer) {
  3612. err = LFS_ERR_NOMEM;
  3613. goto cleanup;
  3614. }
  3615. }
  3616. // check that the size limits are sane
  3617. LFS_ASSERT(lfs->cfg->name_max <= LFS_NAME_MAX);
  3618. lfs->name_max = lfs->cfg->name_max;
  3619. if (!lfs->name_max) {
  3620. lfs->name_max = LFS_NAME_MAX;
  3621. }
  3622. LFS_ASSERT(lfs->cfg->file_max <= LFS_FILE_MAX);
  3623. lfs->file_max = lfs->cfg->file_max;
  3624. if (!lfs->file_max) {
  3625. lfs->file_max = LFS_FILE_MAX;
  3626. }
  3627. LFS_ASSERT(lfs->cfg->attr_max <= LFS_ATTR_MAX);
  3628. lfs->attr_max = lfs->cfg->attr_max;
  3629. if (!lfs->attr_max) {
  3630. lfs->attr_max = LFS_ATTR_MAX;
  3631. }
  3632. LFS_ASSERT(lfs->cfg->metadata_max <= lfs->cfg->block_size);
  3633. // setup default state
  3634. lfs->root[0] = LFS_BLOCK_NULL;
  3635. lfs->root[1] = LFS_BLOCK_NULL;
  3636. lfs->mlist = NULL;
  3637. lfs->seed = 0;
  3638. lfs->gdisk = (lfs_gstate_t){0};
  3639. lfs->gstate = (lfs_gstate_t){0};
  3640. lfs->gdelta = (lfs_gstate_t){0};
  3641. #ifdef LFS_MIGRATE
  3642. lfs->lfs1 = NULL;
  3643. #endif
  3644. return 0;
  3645. cleanup:
  3646. lfs_deinit(lfs);
  3647. return err;
  3648. }
  3649. static int lfs_deinit(lfs_t *lfs) {
  3650. // free allocated memory
  3651. if (!lfs->cfg->read_buffer) {
  3652. lfs_free(lfs->rcache.buffer);
  3653. }
  3654. if (!lfs->cfg->prog_buffer) {
  3655. lfs_free(lfs->pcache.buffer);
  3656. }
  3657. if (!lfs->cfg->lookahead_buffer) {
  3658. lfs_free(lfs->free.buffer);
  3659. }
  3660. return 0;
  3661. }
  3662. #ifndef LFS_READONLY
  3663. static int lfs_rawformat(lfs_t *lfs, const struct lfs_config *cfg) {
  3664. int err = 0;
  3665. {
  3666. err = lfs_init(lfs, cfg);
  3667. if (err) {
  3668. return err;
  3669. }
  3670. LFS_ASSERT(cfg->block_count != 0);
  3671. // create free lookahead
  3672. memset(lfs->free.buffer, 0, lfs->cfg->lookahead_size);
  3673. lfs->free.off = 0;
  3674. lfs->free.size = lfs_min(8*lfs->cfg->lookahead_size,
  3675. lfs->block_count);
  3676. lfs->free.i = 0;
  3677. lfs_alloc_ack(lfs);
  3678. // create root dir
  3679. lfs_mdir_t root;
  3680. err = lfs_dir_alloc(lfs, &root);
  3681. if (err) {
  3682. goto cleanup;
  3683. }
  3684. // write one superblock
  3685. lfs_superblock_t superblock = {
  3686. .version = lfs_fs_disk_version(lfs),
  3687. .block_size = lfs->cfg->block_size,
  3688. .block_count = lfs->block_count,
  3689. .name_max = lfs->name_max,
  3690. .file_max = lfs->file_max,
  3691. .attr_max = lfs->attr_max,
  3692. };
  3693. lfs_superblock_tole32(&superblock);
  3694. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  3695. {LFS_MKTAG(LFS_TYPE_CREATE, 0, 0), NULL},
  3696. {LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
  3697. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3698. &superblock}));
  3699. if (err) {
  3700. goto cleanup;
  3701. }
  3702. // force compaction to prevent accidentally mounting any
  3703. // older version of littlefs that may live on disk
  3704. root.erased = false;
  3705. err = lfs_dir_commit(lfs, &root, NULL, 0);
  3706. if (err) {
  3707. goto cleanup;
  3708. }
  3709. // sanity check that fetch works
  3710. err = lfs_dir_fetch(lfs, &root, (const lfs_block_t[2]){0, 1});
  3711. if (err) {
  3712. goto cleanup;
  3713. }
  3714. }
  3715. cleanup:
  3716. lfs_deinit(lfs);
  3717. return err;
  3718. }
  3719. #endif
  3720. static int lfs_rawmount(lfs_t *lfs, const struct lfs_config *cfg) {
  3721. int err = lfs_init(lfs, cfg);
  3722. if (err) {
  3723. return err;
  3724. }
  3725. // scan directory blocks for superblock and any global updates
  3726. lfs_mdir_t dir = {.tail = {0, 1}};
  3727. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  3728. lfs_size_t tortoise_i = 1;
  3729. lfs_size_t tortoise_period = 1;
  3730. while (!lfs_pair_isnull(dir.tail)) {
  3731. // detect cycles with Brent's algorithm
  3732. if (lfs_pair_issync(dir.tail, tortoise)) {
  3733. LFS_WARN("Cycle detected in tail list");
  3734. err = LFS_ERR_CORRUPT;
  3735. goto cleanup;
  3736. }
  3737. if (tortoise_i == tortoise_period) {
  3738. tortoise[0] = dir.tail[0];
  3739. tortoise[1] = dir.tail[1];
  3740. tortoise_i = 0;
  3741. tortoise_period *= 2;
  3742. }
  3743. tortoise_i += 1;
  3744. // fetch next block in tail list
  3745. lfs_stag_t tag = lfs_dir_fetchmatch(lfs, &dir, dir.tail,
  3746. LFS_MKTAG(0x7ff, 0x3ff, 0),
  3747. LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8),
  3748. NULL,
  3749. lfs_dir_find_match, &(struct lfs_dir_find_match){
  3750. lfs, "littlefs", 8});
  3751. if (tag < 0) {
  3752. err = tag;
  3753. goto cleanup;
  3754. }
  3755. // has superblock?
  3756. if (tag && !lfs_tag_isdelete(tag)) {
  3757. // update root
  3758. lfs->root[0] = dir.pair[0];
  3759. lfs->root[1] = dir.pair[1];
  3760. // grab superblock
  3761. lfs_superblock_t superblock;
  3762. tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3763. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3764. &superblock);
  3765. if (tag < 0) {
  3766. err = tag;
  3767. goto cleanup;
  3768. }
  3769. lfs_superblock_fromle32(&superblock);
  3770. // check version
  3771. uint16_t major_version = (0xffff & (superblock.version >> 16));
  3772. uint16_t minor_version = (0xffff & (superblock.version >> 0));
  3773. if (major_version != lfs_fs_disk_version_major(lfs)
  3774. || minor_version > lfs_fs_disk_version_minor(lfs)) {
  3775. LFS_ERROR("Invalid version "
  3776. "v%"PRIu16".%"PRIu16" != v%"PRIu16".%"PRIu16,
  3777. major_version,
  3778. minor_version,
  3779. lfs_fs_disk_version_major(lfs),
  3780. lfs_fs_disk_version_minor(lfs));
  3781. err = LFS_ERR_INVAL;
  3782. goto cleanup;
  3783. }
  3784. // found older minor version? set an in-device only bit in the
  3785. // gstate so we know we need to rewrite the superblock before
  3786. // the first write
  3787. if (minor_version < lfs_fs_disk_version_minor(lfs)) {
  3788. LFS_DEBUG("Found older minor version "
  3789. "v%"PRIu16".%"PRIu16" < v%"PRIu16".%"PRIu16,
  3790. major_version,
  3791. minor_version,
  3792. lfs_fs_disk_version_major(lfs),
  3793. lfs_fs_disk_version_minor(lfs));
  3794. // note this bit is reserved on disk, so fetching more gstate
  3795. // will not interfere here
  3796. lfs_fs_prepsuperblock(lfs, true);
  3797. }
  3798. // check superblock configuration
  3799. if (superblock.name_max) {
  3800. if (superblock.name_max > lfs->name_max) {
  3801. LFS_ERROR("Unsupported name_max (%"PRIu32" > %"PRIu32")",
  3802. superblock.name_max, lfs->name_max);
  3803. err = LFS_ERR_INVAL;
  3804. goto cleanup;
  3805. }
  3806. lfs->name_max = superblock.name_max;
  3807. }
  3808. if (superblock.file_max) {
  3809. if (superblock.file_max > lfs->file_max) {
  3810. LFS_ERROR("Unsupported file_max (%"PRIu32" > %"PRIu32")",
  3811. superblock.file_max, lfs->file_max);
  3812. err = LFS_ERR_INVAL;
  3813. goto cleanup;
  3814. }
  3815. lfs->file_max = superblock.file_max;
  3816. }
  3817. if (superblock.attr_max) {
  3818. if (superblock.attr_max > lfs->attr_max) {
  3819. LFS_ERROR("Unsupported attr_max (%"PRIu32" > %"PRIu32")",
  3820. superblock.attr_max, lfs->attr_max);
  3821. err = LFS_ERR_INVAL;
  3822. goto cleanup;
  3823. }
  3824. lfs->attr_max = superblock.attr_max;
  3825. }
  3826. // this is where we get the block_count from disk if block_count=0
  3827. if (lfs->cfg->block_count
  3828. && superblock.block_count != lfs->cfg->block_count) {
  3829. LFS_ERROR("Invalid block count (%"PRIu32" != %"PRIu32")",
  3830. superblock.block_count, lfs->cfg->block_count);
  3831. err = LFS_ERR_INVAL;
  3832. goto cleanup;
  3833. }
  3834. lfs->block_count = superblock.block_count;
  3835. if (superblock.block_size != lfs->cfg->block_size) {
  3836. LFS_ERROR("Invalid block size (%"PRIu32" != %"PRIu32")",
  3837. superblock.block_size, lfs->cfg->block_size);
  3838. err = LFS_ERR_INVAL;
  3839. goto cleanup;
  3840. }
  3841. }
  3842. // has gstate?
  3843. err = lfs_dir_getgstate(lfs, &dir, &lfs->gstate);
  3844. if (err) {
  3845. goto cleanup;
  3846. }
  3847. }
  3848. // update littlefs with gstate
  3849. if (!lfs_gstate_iszero(&lfs->gstate)) {
  3850. LFS_DEBUG("Found pending gstate 0x%08"PRIx32"%08"PRIx32"%08"PRIx32,
  3851. lfs->gstate.tag,
  3852. lfs->gstate.pair[0],
  3853. lfs->gstate.pair[1]);
  3854. }
  3855. lfs->gstate.tag += !lfs_tag_isvalid(lfs->gstate.tag);
  3856. lfs->gdisk = lfs->gstate;
  3857. // setup free lookahead, to distribute allocations uniformly across
  3858. // boots, we start the allocator at a random location
  3859. lfs->free.off = lfs->seed % lfs->block_count;
  3860. lfs_alloc_drop(lfs);
  3861. return 0;
  3862. cleanup:
  3863. lfs_rawunmount(lfs);
  3864. return err;
  3865. }
  3866. static int lfs_rawunmount(lfs_t *lfs) {
  3867. return lfs_deinit(lfs);
  3868. }
  3869. /// Filesystem filesystem operations ///
  3870. static int lfs_fs_rawstat(lfs_t *lfs, struct lfs_fsinfo *fsinfo) {
  3871. // if the superblock is up-to-date, we must be on the most recent
  3872. // minor version of littlefs
  3873. if (!lfs_gstate_needssuperblock(&lfs->gstate)) {
  3874. fsinfo->disk_version = lfs_fs_disk_version(lfs);
  3875. // otherwise we need to read the minor version on disk
  3876. } else {
  3877. // fetch the superblock
  3878. lfs_mdir_t dir;
  3879. int err = lfs_dir_fetch(lfs, &dir, lfs->root);
  3880. if (err) {
  3881. return err;
  3882. }
  3883. lfs_superblock_t superblock;
  3884. lfs_stag_t tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3885. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3886. &superblock);
  3887. if (tag < 0) {
  3888. return tag;
  3889. }
  3890. lfs_superblock_fromle32(&superblock);
  3891. // read the on-disk version
  3892. fsinfo->disk_version = superblock.version;
  3893. }
  3894. // filesystem geometry
  3895. fsinfo->block_size = lfs->cfg->block_size;
  3896. fsinfo->block_count = lfs->block_count;
  3897. // other on-disk configuration, we cache all of these for internal use
  3898. fsinfo->name_max = lfs->name_max;
  3899. fsinfo->file_max = lfs->file_max;
  3900. fsinfo->attr_max = lfs->attr_max;
  3901. return 0;
  3902. }
  3903. int lfs_fs_rawtraverse(lfs_t *lfs,
  3904. int (*cb)(void *data, lfs_block_t block), void *data,
  3905. bool includeorphans) {
  3906. // iterate over metadata pairs
  3907. lfs_mdir_t dir = {.tail = {0, 1}};
  3908. #ifdef LFS_MIGRATE
  3909. // also consider v1 blocks during migration
  3910. if (lfs->lfs1) {
  3911. int err = lfs1_traverse(lfs, cb, data);
  3912. if (err) {
  3913. return err;
  3914. }
  3915. dir.tail[0] = lfs->root[0];
  3916. dir.tail[1] = lfs->root[1];
  3917. }
  3918. #endif
  3919. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  3920. lfs_size_t tortoise_i = 1;
  3921. lfs_size_t tortoise_period = 1;
  3922. while (!lfs_pair_isnull(dir.tail)) {
  3923. // detect cycles with Brent's algorithm
  3924. if (lfs_pair_issync(dir.tail, tortoise)) {
  3925. LFS_WARN("Cycle detected in tail list");
  3926. return LFS_ERR_CORRUPT;
  3927. }
  3928. if (tortoise_i == tortoise_period) {
  3929. tortoise[0] = dir.tail[0];
  3930. tortoise[1] = dir.tail[1];
  3931. tortoise_i = 0;
  3932. tortoise_period *= 2;
  3933. }
  3934. tortoise_i += 1;
  3935. for (int i = 0; i < 2; i++) {
  3936. int err = cb(data, dir.tail[i]);
  3937. if (err) {
  3938. return err;
  3939. }
  3940. }
  3941. // iterate through ids in directory
  3942. int err = lfs_dir_fetch(lfs, &dir, dir.tail);
  3943. if (err) {
  3944. return err;
  3945. }
  3946. for (uint16_t id = 0; id < dir.count; id++) {
  3947. struct lfs_ctz ctz;
  3948. lfs_stag_t tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x700, 0x3ff, 0),
  3949. LFS_MKTAG(LFS_TYPE_STRUCT, id, sizeof(ctz)), &ctz);
  3950. if (tag < 0) {
  3951. if (tag == LFS_ERR_NOENT) {
  3952. continue;
  3953. }
  3954. return tag;
  3955. }
  3956. lfs_ctz_fromle32(&ctz);
  3957. if (lfs_tag_type3(tag) == LFS_TYPE_CTZSTRUCT) {
  3958. err = lfs_ctz_traverse(lfs, NULL, &lfs->rcache,
  3959. ctz.head, ctz.size, cb, data);
  3960. if (err) {
  3961. return err;
  3962. }
  3963. } else if (includeorphans &&
  3964. lfs_tag_type3(tag) == LFS_TYPE_DIRSTRUCT) {
  3965. for (int i = 0; i < 2; i++) {
  3966. err = cb(data, (&ctz.head)[i]);
  3967. if (err) {
  3968. return err;
  3969. }
  3970. }
  3971. }
  3972. }
  3973. }
  3974. #ifndef LFS_READONLY
  3975. // iterate over any open files
  3976. for (lfs_file_t *f = (lfs_file_t*)lfs->mlist; f; f = f->next) {
  3977. if (f->type != LFS_TYPE_REG) {
  3978. continue;
  3979. }
  3980. if ((f->flags & LFS_F_DIRTY) && !(f->flags & LFS_F_INLINE)) {
  3981. int err = lfs_ctz_traverse(lfs, &f->cache, &lfs->rcache,
  3982. f->ctz.head, f->ctz.size, cb, data);
  3983. if (err) {
  3984. return err;
  3985. }
  3986. }
  3987. if ((f->flags & LFS_F_WRITING) && !(f->flags & LFS_F_INLINE)) {
  3988. int err = lfs_ctz_traverse(lfs, &f->cache, &lfs->rcache,
  3989. f->block, f->pos, cb, data);
  3990. if (err) {
  3991. return err;
  3992. }
  3993. }
  3994. }
  3995. #endif
  3996. return 0;
  3997. }
  3998. #ifndef LFS_READONLY
  3999. static int lfs_fs_pred(lfs_t *lfs,
  4000. const lfs_block_t pair[2], lfs_mdir_t *pdir) {
  4001. // iterate over all directory directory entries
  4002. pdir->tail[0] = 0;
  4003. pdir->tail[1] = 1;
  4004. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  4005. lfs_size_t tortoise_i = 1;
  4006. lfs_size_t tortoise_period = 1;
  4007. while (!lfs_pair_isnull(pdir->tail)) {
  4008. // detect cycles with Brent's algorithm
  4009. if (lfs_pair_issync(pdir->tail, tortoise)) {
  4010. LFS_WARN("Cycle detected in tail list");
  4011. return LFS_ERR_CORRUPT;
  4012. }
  4013. if (tortoise_i == tortoise_period) {
  4014. tortoise[0] = pdir->tail[0];
  4015. tortoise[1] = pdir->tail[1];
  4016. tortoise_i = 0;
  4017. tortoise_period *= 2;
  4018. }
  4019. tortoise_i += 1;
  4020. if (lfs_pair_cmp(pdir->tail, pair) == 0) {
  4021. return 0;
  4022. }
  4023. int err = lfs_dir_fetch(lfs, pdir, pdir->tail);
  4024. if (err) {
  4025. return err;
  4026. }
  4027. }
  4028. return LFS_ERR_NOENT;
  4029. }
  4030. #endif
  4031. #ifndef LFS_READONLY
  4032. struct lfs_fs_parent_match {
  4033. lfs_t *lfs;
  4034. const lfs_block_t pair[2];
  4035. };
  4036. #endif
  4037. #ifndef LFS_READONLY
  4038. static int lfs_fs_parent_match(void *data,
  4039. lfs_tag_t tag, const void *buffer) {
  4040. struct lfs_fs_parent_match *find = data;
  4041. lfs_t *lfs = find->lfs;
  4042. const struct lfs_diskoff *disk = buffer;
  4043. (void)tag;
  4044. lfs_block_t child[2];
  4045. int err = lfs_bd_read(lfs,
  4046. &lfs->pcache, &lfs->rcache, lfs->cfg->block_size,
  4047. disk->block, disk->off, &child, sizeof(child));
  4048. if (err) {
  4049. return err;
  4050. }
  4051. lfs_pair_fromle32(child);
  4052. return (lfs_pair_cmp(child, find->pair) == 0) ? LFS_CMP_EQ : LFS_CMP_LT;
  4053. }
  4054. #endif
  4055. #ifndef LFS_READONLY
  4056. static lfs_stag_t lfs_fs_parent(lfs_t *lfs, const lfs_block_t pair[2],
  4057. lfs_mdir_t *parent) {
  4058. // use fetchmatch with callback to find pairs
  4059. parent->tail[0] = 0;
  4060. parent->tail[1] = 1;
  4061. lfs_block_t tortoise[2] = {LFS_BLOCK_NULL, LFS_BLOCK_NULL};
  4062. lfs_size_t tortoise_i = 1;
  4063. lfs_size_t tortoise_period = 1;
  4064. while (!lfs_pair_isnull(parent->tail)) {
  4065. // detect cycles with Brent's algorithm
  4066. if (lfs_pair_issync(parent->tail, tortoise)) {
  4067. LFS_WARN("Cycle detected in tail list");
  4068. return LFS_ERR_CORRUPT;
  4069. }
  4070. if (tortoise_i == tortoise_period) {
  4071. tortoise[0] = parent->tail[0];
  4072. tortoise[1] = parent->tail[1];
  4073. tortoise_i = 0;
  4074. tortoise_period *= 2;
  4075. }
  4076. tortoise_i += 1;
  4077. lfs_stag_t tag = lfs_dir_fetchmatch(lfs, parent, parent->tail,
  4078. LFS_MKTAG(0x7ff, 0, 0x3ff),
  4079. LFS_MKTAG(LFS_TYPE_DIRSTRUCT, 0, 8),
  4080. NULL,
  4081. lfs_fs_parent_match, &(struct lfs_fs_parent_match){
  4082. lfs, {pair[0], pair[1]}});
  4083. if (tag && tag != LFS_ERR_NOENT) {
  4084. return tag;
  4085. }
  4086. }
  4087. return LFS_ERR_NOENT;
  4088. }
  4089. #endif
  4090. static void lfs_fs_prepsuperblock(lfs_t *lfs, bool needssuperblock) {
  4091. lfs->gstate.tag = (lfs->gstate.tag & ~LFS_MKTAG(0, 0, 0x200))
  4092. | (uint32_t)needssuperblock << 9;
  4093. }
  4094. #ifndef LFS_READONLY
  4095. static int lfs_fs_preporphans(lfs_t *lfs, int8_t orphans) {
  4096. LFS_ASSERT(lfs_tag_size(lfs->gstate.tag) > 0x000 || orphans >= 0);
  4097. LFS_ASSERT(lfs_tag_size(lfs->gstate.tag) < 0x1ff || orphans <= 0);
  4098. lfs->gstate.tag += orphans;
  4099. lfs->gstate.tag = ((lfs->gstate.tag & ~LFS_MKTAG(0x800, 0, 0)) |
  4100. ((uint32_t)lfs_gstate_hasorphans(&lfs->gstate) << 31));
  4101. return 0;
  4102. }
  4103. #endif
  4104. #ifndef LFS_READONLY
  4105. static void lfs_fs_prepmove(lfs_t *lfs,
  4106. uint16_t id, const lfs_block_t pair[2]) {
  4107. lfs->gstate.tag = ((lfs->gstate.tag & ~LFS_MKTAG(0x7ff, 0x3ff, 0)) |
  4108. ((id != 0x3ff) ? LFS_MKTAG(LFS_TYPE_DELETE, id, 0) : 0));
  4109. lfs->gstate.pair[0] = (id != 0x3ff) ? pair[0] : 0;
  4110. lfs->gstate.pair[1] = (id != 0x3ff) ? pair[1] : 0;
  4111. }
  4112. #endif
  4113. #ifndef LFS_READONLY
  4114. static int lfs_fs_desuperblock(lfs_t *lfs) {
  4115. if (!lfs_gstate_needssuperblock(&lfs->gstate)) {
  4116. return 0;
  4117. }
  4118. LFS_DEBUG("Rewriting superblock {0x%"PRIx32", 0x%"PRIx32"}",
  4119. lfs->root[0],
  4120. lfs->root[1]);
  4121. lfs_mdir_t root;
  4122. int err = lfs_dir_fetch(lfs, &root, lfs->root);
  4123. if (err) {
  4124. return err;
  4125. }
  4126. // write a new superblock
  4127. lfs_superblock_t superblock = {
  4128. .version = lfs_fs_disk_version(lfs),
  4129. .block_size = lfs->cfg->block_size,
  4130. .block_count = lfs->block_count,
  4131. .name_max = lfs->name_max,
  4132. .file_max = lfs->file_max,
  4133. .attr_max = lfs->attr_max,
  4134. };
  4135. lfs_superblock_tole32(&superblock);
  4136. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  4137. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4138. &superblock}));
  4139. if (err) {
  4140. return err;
  4141. }
  4142. lfs_fs_prepsuperblock(lfs, false);
  4143. return 0;
  4144. }
  4145. #endif
  4146. #ifndef LFS_READONLY
  4147. static int lfs_fs_demove(lfs_t *lfs) {
  4148. if (!lfs_gstate_hasmove(&lfs->gdisk)) {
  4149. return 0;
  4150. }
  4151. // Fix bad moves
  4152. LFS_DEBUG("Fixing move {0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16,
  4153. lfs->gdisk.pair[0],
  4154. lfs->gdisk.pair[1],
  4155. lfs_tag_id(lfs->gdisk.tag));
  4156. // no other gstate is supported at this time, so if we found something else
  4157. // something most likely went wrong in gstate calculation
  4158. LFS_ASSERT(lfs_tag_type3(lfs->gdisk.tag) == LFS_TYPE_DELETE);
  4159. // fetch and delete the moved entry
  4160. lfs_mdir_t movedir;
  4161. int err = lfs_dir_fetch(lfs, &movedir, lfs->gdisk.pair);
  4162. if (err) {
  4163. return err;
  4164. }
  4165. // prep gstate and delete move id
  4166. uint16_t moveid = lfs_tag_id(lfs->gdisk.tag);
  4167. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  4168. err = lfs_dir_commit(lfs, &movedir, LFS_MKATTRS(
  4169. {LFS_MKTAG(LFS_TYPE_DELETE, moveid, 0), NULL}));
  4170. if (err) {
  4171. return err;
  4172. }
  4173. return 0;
  4174. }
  4175. #endif
  4176. #ifndef LFS_READONLY
  4177. static int lfs_fs_deorphan(lfs_t *lfs, bool powerloss) {
  4178. if (!lfs_gstate_hasorphans(&lfs->gstate)) {
  4179. return 0;
  4180. }
  4181. // Check for orphans in two separate passes:
  4182. // - 1 for half-orphans (relocations)
  4183. // - 2 for full-orphans (removes/renames)
  4184. //
  4185. // Two separate passes are needed as half-orphans can contain outdated
  4186. // references to full-orphans, effectively hiding them from the deorphan
  4187. // search.
  4188. //
  4189. int pass = 0;
  4190. while (pass < 2) {
  4191. // Fix any orphans
  4192. lfs_mdir_t pdir = {.split = true, .tail = {0, 1}};
  4193. lfs_mdir_t dir;
  4194. bool moreorphans = false;
  4195. // iterate over all directory directory entries
  4196. while (!lfs_pair_isnull(pdir.tail)) {
  4197. int err = lfs_dir_fetch(lfs, &dir, pdir.tail);
  4198. if (err) {
  4199. return err;
  4200. }
  4201. // check head blocks for orphans
  4202. if (!pdir.split) {
  4203. // check if we have a parent
  4204. lfs_mdir_t parent;
  4205. lfs_stag_t tag = lfs_fs_parent(lfs, pdir.tail, &parent);
  4206. if (tag < 0 && tag != LFS_ERR_NOENT) {
  4207. return tag;
  4208. }
  4209. if (pass == 0 && tag != LFS_ERR_NOENT) {
  4210. lfs_block_t pair[2];
  4211. lfs_stag_t state = lfs_dir_get(lfs, &parent,
  4212. LFS_MKTAG(0x7ff, 0x3ff, 0), tag, pair);
  4213. if (state < 0) {
  4214. return state;
  4215. }
  4216. lfs_pair_fromle32(pair);
  4217. if (!lfs_pair_issync(pair, pdir.tail)) {
  4218. // we have desynced
  4219. LFS_DEBUG("Fixing half-orphan "
  4220. "{0x%"PRIx32", 0x%"PRIx32"} "
  4221. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  4222. pdir.tail[0], pdir.tail[1], pair[0], pair[1]);
  4223. // fix pending move in this pair? this looks like an
  4224. // optimization but is in fact _required_ since
  4225. // relocating may outdate the move.
  4226. uint16_t moveid = 0x3ff;
  4227. if (lfs_gstate_hasmovehere(&lfs->gstate, pdir.pair)) {
  4228. moveid = lfs_tag_id(lfs->gstate.tag);
  4229. LFS_DEBUG("Fixing move while fixing orphans "
  4230. "{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
  4231. pdir.pair[0], pdir.pair[1], moveid);
  4232. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  4233. }
  4234. lfs_pair_tole32(pair);
  4235. state = lfs_dir_orphaningcommit(lfs, &pdir, LFS_MKATTRS(
  4236. {LFS_MKTAG_IF(moveid != 0x3ff,
  4237. LFS_TYPE_DELETE, moveid, 0), NULL},
  4238. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8),
  4239. pair}));
  4240. lfs_pair_fromle32(pair);
  4241. if (state < 0) {
  4242. return state;
  4243. }
  4244. // did our commit create more orphans?
  4245. if (state == LFS_OK_ORPHANED) {
  4246. moreorphans = true;
  4247. }
  4248. // refetch tail
  4249. continue;
  4250. }
  4251. }
  4252. // note we only check for full orphans if we may have had a
  4253. // power-loss, otherwise orphans are created intentionally
  4254. // during operations such as lfs_mkdir
  4255. if (pass == 1 && tag == LFS_ERR_NOENT && powerloss) {
  4256. // we are an orphan
  4257. LFS_DEBUG("Fixing orphan {0x%"PRIx32", 0x%"PRIx32"}",
  4258. pdir.tail[0], pdir.tail[1]);
  4259. // steal state
  4260. err = lfs_dir_getgstate(lfs, &dir, &lfs->gdelta);
  4261. if (err) {
  4262. return err;
  4263. }
  4264. // steal tail
  4265. lfs_pair_tole32(dir.tail);
  4266. int state = lfs_dir_orphaningcommit(lfs, &pdir, LFS_MKATTRS(
  4267. {LFS_MKTAG(LFS_TYPE_TAIL + dir.split, 0x3ff, 8),
  4268. dir.tail}));
  4269. lfs_pair_fromle32(dir.tail);
  4270. if (state < 0) {
  4271. return state;
  4272. }
  4273. // did our commit create more orphans?
  4274. if (state == LFS_OK_ORPHANED) {
  4275. moreorphans = true;
  4276. }
  4277. // refetch tail
  4278. continue;
  4279. }
  4280. }
  4281. pdir = dir;
  4282. }
  4283. pass = moreorphans ? 0 : pass+1;
  4284. }
  4285. // mark orphans as fixed
  4286. return lfs_fs_preporphans(lfs, -lfs_gstate_getorphans(&lfs->gstate));
  4287. }
  4288. #endif
  4289. #ifndef LFS_READONLY
  4290. static int lfs_fs_forceconsistency(lfs_t *lfs) {
  4291. int err = lfs_fs_desuperblock(lfs);
  4292. if (err) {
  4293. return err;
  4294. }
  4295. err = lfs_fs_demove(lfs);
  4296. if (err) {
  4297. return err;
  4298. }
  4299. err = lfs_fs_deorphan(lfs, true);
  4300. if (err) {
  4301. return err;
  4302. }
  4303. return 0;
  4304. }
  4305. #endif
  4306. #ifndef LFS_READONLY
  4307. static int lfs_fs_rawmkconsistent(lfs_t *lfs) {
  4308. // lfs_fs_forceconsistency does most of the work here
  4309. int err = lfs_fs_forceconsistency(lfs);
  4310. if (err) {
  4311. return err;
  4312. }
  4313. // do we have any pending gstate?
  4314. lfs_gstate_t delta = {0};
  4315. lfs_gstate_xor(&delta, &lfs->gdisk);
  4316. lfs_gstate_xor(&delta, &lfs->gstate);
  4317. if (!lfs_gstate_iszero(&delta)) {
  4318. // lfs_dir_commit will implicitly write out any pending gstate
  4319. lfs_mdir_t root;
  4320. err = lfs_dir_fetch(lfs, &root, lfs->root);
  4321. if (err) {
  4322. return err;
  4323. }
  4324. err = lfs_dir_commit(lfs, &root, NULL, 0);
  4325. if (err) {
  4326. return err;
  4327. }
  4328. }
  4329. return 0;
  4330. }
  4331. #endif
  4332. static int lfs_fs_size_count(void *p, lfs_block_t block) {
  4333. (void)block;
  4334. lfs_size_t *size = p;
  4335. *size += 1;
  4336. return 0;
  4337. }
  4338. static lfs_ssize_t lfs_fs_rawsize(lfs_t *lfs) {
  4339. lfs_size_t size = 0;
  4340. int err = lfs_fs_rawtraverse(lfs, lfs_fs_size_count, &size, false);
  4341. if (err) {
  4342. return err;
  4343. }
  4344. return size;
  4345. }
  4346. #ifndef LFS_READONLY
  4347. static int lfs_fs_rawgrow(lfs_t *lfs, lfs_size_t block_count) {
  4348. // shrinking is not supported
  4349. LFS_ASSERT(block_count >= lfs->block_count);
  4350. if (block_count > lfs->block_count) {
  4351. lfs->block_count = block_count;
  4352. // fetch the root
  4353. lfs_mdir_t root;
  4354. int err = lfs_dir_fetch(lfs, &root, lfs->root);
  4355. if (err) {
  4356. return err;
  4357. }
  4358. // update the superblock
  4359. lfs_superblock_t superblock;
  4360. lfs_stag_t tag = lfs_dir_get(lfs, &root, LFS_MKTAG(0x7ff, 0x3ff, 0),
  4361. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4362. &superblock);
  4363. if (tag < 0) {
  4364. return tag;
  4365. }
  4366. lfs_superblock_fromle32(&superblock);
  4367. superblock.block_count = lfs->block_count;
  4368. lfs_superblock_tole32(&superblock);
  4369. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  4370. {tag, &superblock}));
  4371. if (err) {
  4372. return err;
  4373. }
  4374. }
  4375. return 0;
  4376. }
  4377. #endif
  4378. #ifdef LFS_MIGRATE
  4379. ////// Migration from littelfs v1 below this //////
  4380. /// Version info ///
  4381. // Software library version
  4382. // Major (top-nibble), incremented on backwards incompatible changes
  4383. // Minor (bottom-nibble), incremented on feature additions
  4384. #define LFS1_VERSION 0x00010007
  4385. #define LFS1_VERSION_MAJOR (0xffff & (LFS1_VERSION >> 16))
  4386. #define LFS1_VERSION_MINOR (0xffff & (LFS1_VERSION >> 0))
  4387. // Version of On-disk data structures
  4388. // Major (top-nibble), incremented on backwards incompatible changes
  4389. // Minor (bottom-nibble), incremented on feature additions
  4390. #define LFS1_DISK_VERSION 0x00010001
  4391. #define LFS1_DISK_VERSION_MAJOR (0xffff & (LFS1_DISK_VERSION >> 16))
  4392. #define LFS1_DISK_VERSION_MINOR (0xffff & (LFS1_DISK_VERSION >> 0))
  4393. /// v1 Definitions ///
  4394. // File types
  4395. enum lfs1_type {
  4396. LFS1_TYPE_REG = 0x11,
  4397. LFS1_TYPE_DIR = 0x22,
  4398. LFS1_TYPE_SUPERBLOCK = 0x2e,
  4399. };
  4400. typedef struct lfs1 {
  4401. lfs_block_t root[2];
  4402. } lfs1_t;
  4403. typedef struct lfs1_entry {
  4404. lfs_off_t off;
  4405. struct lfs1_disk_entry {
  4406. uint8_t type;
  4407. uint8_t elen;
  4408. uint8_t alen;
  4409. uint8_t nlen;
  4410. union {
  4411. struct {
  4412. lfs_block_t head;
  4413. lfs_size_t size;
  4414. } file;
  4415. lfs_block_t dir[2];
  4416. } u;
  4417. } d;
  4418. } lfs1_entry_t;
  4419. typedef struct lfs1_dir {
  4420. struct lfs1_dir *next;
  4421. lfs_block_t pair[2];
  4422. lfs_off_t off;
  4423. lfs_block_t head[2];
  4424. lfs_off_t pos;
  4425. struct lfs1_disk_dir {
  4426. uint32_t rev;
  4427. lfs_size_t size;
  4428. lfs_block_t tail[2];
  4429. } d;
  4430. } lfs1_dir_t;
  4431. typedef struct lfs1_superblock {
  4432. lfs_off_t off;
  4433. struct lfs1_disk_superblock {
  4434. uint8_t type;
  4435. uint8_t elen;
  4436. uint8_t alen;
  4437. uint8_t nlen;
  4438. lfs_block_t root[2];
  4439. uint32_t block_size;
  4440. uint32_t block_count;
  4441. uint32_t version;
  4442. char magic[8];
  4443. } d;
  4444. } lfs1_superblock_t;
  4445. /// Low-level wrappers v1->v2 ///
  4446. static void lfs1_crc(uint32_t *crc, const void *buffer, size_t size) {
  4447. *crc = lfs_crc(*crc, buffer, size);
  4448. }
  4449. static int lfs1_bd_read(lfs_t *lfs, lfs_block_t block,
  4450. lfs_off_t off, void *buffer, lfs_size_t size) {
  4451. // if we ever do more than writes to alternating pairs,
  4452. // this may need to consider pcache
  4453. return lfs_bd_read(lfs, &lfs->pcache, &lfs->rcache, size,
  4454. block, off, buffer, size);
  4455. }
  4456. static int lfs1_bd_crc(lfs_t *lfs, lfs_block_t block,
  4457. lfs_off_t off, lfs_size_t size, uint32_t *crc) {
  4458. for (lfs_off_t i = 0; i < size; i++) {
  4459. uint8_t c;
  4460. int err = lfs1_bd_read(lfs, block, off+i, &c, 1);
  4461. if (err) {
  4462. return err;
  4463. }
  4464. lfs1_crc(crc, &c, 1);
  4465. }
  4466. return 0;
  4467. }
  4468. /// Endian swapping functions ///
  4469. static void lfs1_dir_fromle32(struct lfs1_disk_dir *d) {
  4470. d->rev = lfs_fromle32(d->rev);
  4471. d->size = lfs_fromle32(d->size);
  4472. d->tail[0] = lfs_fromle32(d->tail[0]);
  4473. d->tail[1] = lfs_fromle32(d->tail[1]);
  4474. }
  4475. static void lfs1_dir_tole32(struct lfs1_disk_dir *d) {
  4476. d->rev = lfs_tole32(d->rev);
  4477. d->size = lfs_tole32(d->size);
  4478. d->tail[0] = lfs_tole32(d->tail[0]);
  4479. d->tail[1] = lfs_tole32(d->tail[1]);
  4480. }
  4481. static void lfs1_entry_fromle32(struct lfs1_disk_entry *d) {
  4482. d->u.dir[0] = lfs_fromle32(d->u.dir[0]);
  4483. d->u.dir[1] = lfs_fromle32(d->u.dir[1]);
  4484. }
  4485. static void lfs1_entry_tole32(struct lfs1_disk_entry *d) {
  4486. d->u.dir[0] = lfs_tole32(d->u.dir[0]);
  4487. d->u.dir[1] = lfs_tole32(d->u.dir[1]);
  4488. }
  4489. static void lfs1_superblock_fromle32(struct lfs1_disk_superblock *d) {
  4490. d->root[0] = lfs_fromle32(d->root[0]);
  4491. d->root[1] = lfs_fromle32(d->root[1]);
  4492. d->block_size = lfs_fromle32(d->block_size);
  4493. d->block_count = lfs_fromle32(d->block_count);
  4494. d->version = lfs_fromle32(d->version);
  4495. }
  4496. ///// Metadata pair and directory operations ///
  4497. static inline lfs_size_t lfs1_entry_size(const lfs1_entry_t *entry) {
  4498. return 4 + entry->d.elen + entry->d.alen + entry->d.nlen;
  4499. }
  4500. static int lfs1_dir_fetch(lfs_t *lfs,
  4501. lfs1_dir_t *dir, const lfs_block_t pair[2]) {
  4502. // copy out pair, otherwise may be aliasing dir
  4503. const lfs_block_t tpair[2] = {pair[0], pair[1]};
  4504. bool valid = false;
  4505. // check both blocks for the most recent revision
  4506. for (int i = 0; i < 2; i++) {
  4507. struct lfs1_disk_dir test;
  4508. int err = lfs1_bd_read(lfs, tpair[i], 0, &test, sizeof(test));
  4509. lfs1_dir_fromle32(&test);
  4510. if (err) {
  4511. if (err == LFS_ERR_CORRUPT) {
  4512. continue;
  4513. }
  4514. return err;
  4515. }
  4516. if (valid && lfs_scmp(test.rev, dir->d.rev) < 0) {
  4517. continue;
  4518. }
  4519. if ((0x7fffffff & test.size) < sizeof(test)+4 ||
  4520. (0x7fffffff & test.size) > lfs->cfg->block_size) {
  4521. continue;
  4522. }
  4523. uint32_t crc = 0xffffffff;
  4524. lfs1_dir_tole32(&test);
  4525. lfs1_crc(&crc, &test, sizeof(test));
  4526. lfs1_dir_fromle32(&test);
  4527. err = lfs1_bd_crc(lfs, tpair[i], sizeof(test),
  4528. (0x7fffffff & test.size) - sizeof(test), &crc);
  4529. if (err) {
  4530. if (err == LFS_ERR_CORRUPT) {
  4531. continue;
  4532. }
  4533. return err;
  4534. }
  4535. if (crc != 0) {
  4536. continue;
  4537. }
  4538. valid = true;
  4539. // setup dir in case it's valid
  4540. dir->pair[0] = tpair[(i+0) % 2];
  4541. dir->pair[1] = tpair[(i+1) % 2];
  4542. dir->off = sizeof(dir->d);
  4543. dir->d = test;
  4544. }
  4545. if (!valid) {
  4546. LFS_ERROR("Corrupted dir pair at {0x%"PRIx32", 0x%"PRIx32"}",
  4547. tpair[0], tpair[1]);
  4548. return LFS_ERR_CORRUPT;
  4549. }
  4550. return 0;
  4551. }
  4552. static int lfs1_dir_next(lfs_t *lfs, lfs1_dir_t *dir, lfs1_entry_t *entry) {
  4553. while (dir->off + sizeof(entry->d) > (0x7fffffff & dir->d.size)-4) {
  4554. if (!(0x80000000 & dir->d.size)) {
  4555. entry->off = dir->off;
  4556. return LFS_ERR_NOENT;
  4557. }
  4558. int err = lfs1_dir_fetch(lfs, dir, dir->d.tail);
  4559. if (err) {
  4560. return err;
  4561. }
  4562. dir->off = sizeof(dir->d);
  4563. dir->pos += sizeof(dir->d) + 4;
  4564. }
  4565. int err = lfs1_bd_read(lfs, dir->pair[0], dir->off,
  4566. &entry->d, sizeof(entry->d));
  4567. lfs1_entry_fromle32(&entry->d);
  4568. if (err) {
  4569. return err;
  4570. }
  4571. entry->off = dir->off;
  4572. dir->off += lfs1_entry_size(entry);
  4573. dir->pos += lfs1_entry_size(entry);
  4574. return 0;
  4575. }
  4576. /// littlefs v1 specific operations ///
  4577. int lfs1_traverse(lfs_t *lfs, int (*cb)(void*, lfs_block_t), void *data) {
  4578. if (lfs_pair_isnull(lfs->lfs1->root)) {
  4579. return 0;
  4580. }
  4581. // iterate over metadata pairs
  4582. lfs1_dir_t dir;
  4583. lfs1_entry_t entry;
  4584. lfs_block_t cwd[2] = {0, 1};
  4585. while (true) {
  4586. for (int i = 0; i < 2; i++) {
  4587. int err = cb(data, cwd[i]);
  4588. if (err) {
  4589. return err;
  4590. }
  4591. }
  4592. int err = lfs1_dir_fetch(lfs, &dir, cwd);
  4593. if (err) {
  4594. return err;
  4595. }
  4596. // iterate over contents
  4597. while (dir.off + sizeof(entry.d) <= (0x7fffffff & dir.d.size)-4) {
  4598. err = lfs1_bd_read(lfs, dir.pair[0], dir.off,
  4599. &entry.d, sizeof(entry.d));
  4600. lfs1_entry_fromle32(&entry.d);
  4601. if (err) {
  4602. return err;
  4603. }
  4604. dir.off += lfs1_entry_size(&entry);
  4605. if ((0x70 & entry.d.type) == (0x70 & LFS1_TYPE_REG)) {
  4606. err = lfs_ctz_traverse(lfs, NULL, &lfs->rcache,
  4607. entry.d.u.file.head, entry.d.u.file.size, cb, data);
  4608. if (err) {
  4609. return err;
  4610. }
  4611. }
  4612. }
  4613. // we also need to check if we contain a threaded v2 directory
  4614. lfs_mdir_t dir2 = {.split=true, .tail={cwd[0], cwd[1]}};
  4615. while (dir2.split) {
  4616. err = lfs_dir_fetch(lfs, &dir2, dir2.tail);
  4617. if (err) {
  4618. break;
  4619. }
  4620. for (int i = 0; i < 2; i++) {
  4621. err = cb(data, dir2.pair[i]);
  4622. if (err) {
  4623. return err;
  4624. }
  4625. }
  4626. }
  4627. cwd[0] = dir.d.tail[0];
  4628. cwd[1] = dir.d.tail[1];
  4629. if (lfs_pair_isnull(cwd)) {
  4630. break;
  4631. }
  4632. }
  4633. return 0;
  4634. }
  4635. static int lfs1_moved(lfs_t *lfs, const void *e) {
  4636. if (lfs_pair_isnull(lfs->lfs1->root)) {
  4637. return 0;
  4638. }
  4639. // skip superblock
  4640. lfs1_dir_t cwd;
  4641. int err = lfs1_dir_fetch(lfs, &cwd, (const lfs_block_t[2]){0, 1});
  4642. if (err) {
  4643. return err;
  4644. }
  4645. // iterate over all directory directory entries
  4646. lfs1_entry_t entry;
  4647. while (!lfs_pair_isnull(cwd.d.tail)) {
  4648. err = lfs1_dir_fetch(lfs, &cwd, cwd.d.tail);
  4649. if (err) {
  4650. return err;
  4651. }
  4652. while (true) {
  4653. err = lfs1_dir_next(lfs, &cwd, &entry);
  4654. if (err && err != LFS_ERR_NOENT) {
  4655. return err;
  4656. }
  4657. if (err == LFS_ERR_NOENT) {
  4658. break;
  4659. }
  4660. if (!(0x80 & entry.d.type) &&
  4661. memcmp(&entry.d.u, e, sizeof(entry.d.u)) == 0) {
  4662. return true;
  4663. }
  4664. }
  4665. }
  4666. return false;
  4667. }
  4668. /// Filesystem operations ///
  4669. static int lfs1_mount(lfs_t *lfs, struct lfs1 *lfs1,
  4670. const struct lfs_config *cfg) {
  4671. int err = 0;
  4672. {
  4673. err = lfs_init(lfs, cfg);
  4674. if (err) {
  4675. return err;
  4676. }
  4677. lfs->lfs1 = lfs1;
  4678. lfs->lfs1->root[0] = LFS_BLOCK_NULL;
  4679. lfs->lfs1->root[1] = LFS_BLOCK_NULL;
  4680. // setup free lookahead
  4681. lfs->free.off = 0;
  4682. lfs->free.size = 0;
  4683. lfs->free.i = 0;
  4684. lfs_alloc_ack(lfs);
  4685. // load superblock
  4686. lfs1_dir_t dir;
  4687. lfs1_superblock_t superblock;
  4688. err = lfs1_dir_fetch(lfs, &dir, (const lfs_block_t[2]){0, 1});
  4689. if (err && err != LFS_ERR_CORRUPT) {
  4690. goto cleanup;
  4691. }
  4692. if (!err) {
  4693. err = lfs1_bd_read(lfs, dir.pair[0], sizeof(dir.d),
  4694. &superblock.d, sizeof(superblock.d));
  4695. lfs1_superblock_fromle32(&superblock.d);
  4696. if (err) {
  4697. goto cleanup;
  4698. }
  4699. lfs->lfs1->root[0] = superblock.d.root[0];
  4700. lfs->lfs1->root[1] = superblock.d.root[1];
  4701. }
  4702. if (err || memcmp(superblock.d.magic, "littlefs", 8) != 0) {
  4703. LFS_ERROR("Invalid superblock at {0x%"PRIx32", 0x%"PRIx32"}",
  4704. 0, 1);
  4705. err = LFS_ERR_CORRUPT;
  4706. goto cleanup;
  4707. }
  4708. uint16_t major_version = (0xffff & (superblock.d.version >> 16));
  4709. uint16_t minor_version = (0xffff & (superblock.d.version >> 0));
  4710. if ((major_version != LFS1_DISK_VERSION_MAJOR ||
  4711. minor_version > LFS1_DISK_VERSION_MINOR)) {
  4712. LFS_ERROR("Invalid version v%d.%d", major_version, minor_version);
  4713. err = LFS_ERR_INVAL;
  4714. goto cleanup;
  4715. }
  4716. return 0;
  4717. }
  4718. cleanup:
  4719. lfs_deinit(lfs);
  4720. return err;
  4721. }
  4722. static int lfs1_unmount(lfs_t *lfs) {
  4723. return lfs_deinit(lfs);
  4724. }
  4725. /// v1 migration ///
  4726. static int lfs_rawmigrate(lfs_t *lfs, const struct lfs_config *cfg) {
  4727. struct lfs1 lfs1;
  4728. // Indeterminate filesystem size not allowed for migration.
  4729. LFS_ASSERT(cfg->block_count != 0);
  4730. int err = lfs1_mount(lfs, &lfs1, cfg);
  4731. if (err) {
  4732. return err;
  4733. }
  4734. {
  4735. // iterate through each directory, copying over entries
  4736. // into new directory
  4737. lfs1_dir_t dir1;
  4738. lfs_mdir_t dir2;
  4739. dir1.d.tail[0] = lfs->lfs1->root[0];
  4740. dir1.d.tail[1] = lfs->lfs1->root[1];
  4741. while (!lfs_pair_isnull(dir1.d.tail)) {
  4742. // iterate old dir
  4743. err = lfs1_dir_fetch(lfs, &dir1, dir1.d.tail);
  4744. if (err) {
  4745. goto cleanup;
  4746. }
  4747. // create new dir and bind as temporary pretend root
  4748. err = lfs_dir_alloc(lfs, &dir2);
  4749. if (err) {
  4750. goto cleanup;
  4751. }
  4752. dir2.rev = dir1.d.rev;
  4753. dir1.head[0] = dir1.pair[0];
  4754. dir1.head[1] = dir1.pair[1];
  4755. lfs->root[0] = dir2.pair[0];
  4756. lfs->root[1] = dir2.pair[1];
  4757. err = lfs_dir_commit(lfs, &dir2, NULL, 0);
  4758. if (err) {
  4759. goto cleanup;
  4760. }
  4761. while (true) {
  4762. lfs1_entry_t entry1;
  4763. err = lfs1_dir_next(lfs, &dir1, &entry1);
  4764. if (err && err != LFS_ERR_NOENT) {
  4765. goto cleanup;
  4766. }
  4767. if (err == LFS_ERR_NOENT) {
  4768. break;
  4769. }
  4770. // check that entry has not been moved
  4771. if (entry1.d.type & 0x80) {
  4772. int moved = lfs1_moved(lfs, &entry1.d.u);
  4773. if (moved < 0) {
  4774. err = moved;
  4775. goto cleanup;
  4776. }
  4777. if (moved) {
  4778. continue;
  4779. }
  4780. entry1.d.type &= ~0x80;
  4781. }
  4782. // also fetch name
  4783. char name[LFS_NAME_MAX+1];
  4784. memset(name, 0, sizeof(name));
  4785. err = lfs1_bd_read(lfs, dir1.pair[0],
  4786. entry1.off + 4+entry1.d.elen+entry1.d.alen,
  4787. name, entry1.d.nlen);
  4788. if (err) {
  4789. goto cleanup;
  4790. }
  4791. bool isdir = (entry1.d.type == LFS1_TYPE_DIR);
  4792. // create entry in new dir
  4793. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4794. if (err) {
  4795. goto cleanup;
  4796. }
  4797. uint16_t id;
  4798. err = lfs_dir_find(lfs, &dir2, &(const char*){name}, &id);
  4799. if (!(err == LFS_ERR_NOENT && id != 0x3ff)) {
  4800. err = (err < 0) ? err : LFS_ERR_EXIST;
  4801. goto cleanup;
  4802. }
  4803. lfs1_entry_tole32(&entry1.d);
  4804. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4805. {LFS_MKTAG(LFS_TYPE_CREATE, id, 0), NULL},
  4806. {LFS_MKTAG_IF_ELSE(isdir,
  4807. LFS_TYPE_DIR, id, entry1.d.nlen,
  4808. LFS_TYPE_REG, id, entry1.d.nlen),
  4809. name},
  4810. {LFS_MKTAG_IF_ELSE(isdir,
  4811. LFS_TYPE_DIRSTRUCT, id, sizeof(entry1.d.u),
  4812. LFS_TYPE_CTZSTRUCT, id, sizeof(entry1.d.u)),
  4813. &entry1.d.u}));
  4814. lfs1_entry_fromle32(&entry1.d);
  4815. if (err) {
  4816. goto cleanup;
  4817. }
  4818. }
  4819. if (!lfs_pair_isnull(dir1.d.tail)) {
  4820. // find last block and update tail to thread into fs
  4821. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4822. if (err) {
  4823. goto cleanup;
  4824. }
  4825. while (dir2.split) {
  4826. err = lfs_dir_fetch(lfs, &dir2, dir2.tail);
  4827. if (err) {
  4828. goto cleanup;
  4829. }
  4830. }
  4831. lfs_pair_tole32(dir2.pair);
  4832. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4833. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir1.d.tail}));
  4834. lfs_pair_fromle32(dir2.pair);
  4835. if (err) {
  4836. goto cleanup;
  4837. }
  4838. }
  4839. // Copy over first block to thread into fs. Unfortunately
  4840. // if this fails there is not much we can do.
  4841. LFS_DEBUG("Migrating {0x%"PRIx32", 0x%"PRIx32"} "
  4842. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  4843. lfs->root[0], lfs->root[1], dir1.head[0], dir1.head[1]);
  4844. err = lfs_bd_erase(lfs, dir1.head[1]);
  4845. if (err) {
  4846. goto cleanup;
  4847. }
  4848. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4849. if (err) {
  4850. goto cleanup;
  4851. }
  4852. for (lfs_off_t i = 0; i < dir2.off; i++) {
  4853. uint8_t dat;
  4854. err = lfs_bd_read(lfs,
  4855. NULL, &lfs->rcache, dir2.off,
  4856. dir2.pair[0], i, &dat, 1);
  4857. if (err) {
  4858. goto cleanup;
  4859. }
  4860. err = lfs_bd_prog(lfs,
  4861. &lfs->pcache, &lfs->rcache, true,
  4862. dir1.head[1], i, &dat, 1);
  4863. if (err) {
  4864. goto cleanup;
  4865. }
  4866. }
  4867. err = lfs_bd_flush(lfs, &lfs->pcache, &lfs->rcache, true);
  4868. if (err) {
  4869. goto cleanup;
  4870. }
  4871. }
  4872. // Create new superblock. This marks a successful migration!
  4873. err = lfs1_dir_fetch(lfs, &dir1, (const lfs_block_t[2]){0, 1});
  4874. if (err) {
  4875. goto cleanup;
  4876. }
  4877. dir2.pair[0] = dir1.pair[0];
  4878. dir2.pair[1] = dir1.pair[1];
  4879. dir2.rev = dir1.d.rev;
  4880. dir2.off = sizeof(dir2.rev);
  4881. dir2.etag = 0xffffffff;
  4882. dir2.count = 0;
  4883. dir2.tail[0] = lfs->lfs1->root[0];
  4884. dir2.tail[1] = lfs->lfs1->root[1];
  4885. dir2.erased = false;
  4886. dir2.split = true;
  4887. lfs_superblock_t superblock = {
  4888. .version = LFS_DISK_VERSION,
  4889. .block_size = lfs->cfg->block_size,
  4890. .block_count = lfs->cfg->block_count,
  4891. .name_max = lfs->name_max,
  4892. .file_max = lfs->file_max,
  4893. .attr_max = lfs->attr_max,
  4894. };
  4895. lfs_superblock_tole32(&superblock);
  4896. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4897. {LFS_MKTAG(LFS_TYPE_CREATE, 0, 0), NULL},
  4898. {LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
  4899. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4900. &superblock}));
  4901. if (err) {
  4902. goto cleanup;
  4903. }
  4904. // sanity check that fetch works
  4905. err = lfs_dir_fetch(lfs, &dir2, (const lfs_block_t[2]){0, 1});
  4906. if (err) {
  4907. goto cleanup;
  4908. }
  4909. // force compaction to prevent accidentally mounting v1
  4910. dir2.erased = false;
  4911. err = lfs_dir_commit(lfs, &dir2, NULL, 0);
  4912. if (err) {
  4913. goto cleanup;
  4914. }
  4915. }
  4916. cleanup:
  4917. lfs1_unmount(lfs);
  4918. return err;
  4919. }
  4920. #endif
  4921. /// Public API wrappers ///
  4922. // Here we can add tracing/thread safety easily
  4923. // Thread-safe wrappers if enabled
  4924. #ifdef LFS_THREADSAFE
  4925. #define LFS_LOCK(cfg) cfg->lock(cfg)
  4926. #define LFS_UNLOCK(cfg) cfg->unlock(cfg)
  4927. #else
  4928. #define LFS_LOCK(cfg) ((void)cfg, 0)
  4929. #define LFS_UNLOCK(cfg) ((void)cfg)
  4930. #endif
  4931. // Public API
  4932. #ifndef LFS_READONLY
  4933. int lfs_format(lfs_t *lfs, const struct lfs_config *cfg) {
  4934. int err = LFS_LOCK(cfg);
  4935. if (err) {
  4936. return err;
  4937. }
  4938. LFS_TRACE("lfs_format(%p, %p {.context=%p, "
  4939. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  4940. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  4941. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  4942. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  4943. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  4944. ".prog_buffer=%p, .lookahead_buffer=%p, "
  4945. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  4946. ".attr_max=%"PRIu32"})",
  4947. (void*)lfs, (void*)cfg, cfg->context,
  4948. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  4949. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  4950. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  4951. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  4952. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  4953. cfg->name_max, cfg->file_max, cfg->attr_max);
  4954. err = lfs_rawformat(lfs, cfg);
  4955. LFS_TRACE("lfs_format -> %d", err);
  4956. LFS_UNLOCK(cfg);
  4957. return err;
  4958. }
  4959. #endif
  4960. int lfs_mount(lfs_t *lfs, const struct lfs_config *cfg) {
  4961. int err = LFS_LOCK(cfg);
  4962. if (err) {
  4963. return err;
  4964. }
  4965. LFS_TRACE("lfs_mount(%p, %p {.context=%p, "
  4966. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  4967. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  4968. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  4969. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  4970. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  4971. ".prog_buffer=%p, .lookahead_buffer=%p, "
  4972. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  4973. ".attr_max=%"PRIu32"})",
  4974. (void*)lfs, (void*)cfg, cfg->context,
  4975. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  4976. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  4977. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  4978. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  4979. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  4980. cfg->name_max, cfg->file_max, cfg->attr_max);
  4981. err = lfs_rawmount(lfs, cfg);
  4982. LFS_TRACE("lfs_mount -> %d", err);
  4983. LFS_UNLOCK(cfg);
  4984. return err;
  4985. }
  4986. int lfs_unmount(lfs_t *lfs) {
  4987. int err = LFS_LOCK(lfs->cfg);
  4988. if (err) {
  4989. return err;
  4990. }
  4991. LFS_TRACE("lfs_unmount(%p)", (void*)lfs);
  4992. err = lfs_rawunmount(lfs);
  4993. LFS_TRACE("lfs_unmount -> %d", err);
  4994. LFS_UNLOCK(lfs->cfg);
  4995. return err;
  4996. }
  4997. #ifndef LFS_READONLY
  4998. int lfs_remove(lfs_t *lfs, const char *path) {
  4999. int err = LFS_LOCK(lfs->cfg);
  5000. if (err) {
  5001. return err;
  5002. }
  5003. LFS_TRACE("lfs_remove(%p, \"%s\")", (void*)lfs, path);
  5004. err = lfs_rawremove(lfs, path);
  5005. LFS_TRACE("lfs_remove -> %d", err);
  5006. LFS_UNLOCK(lfs->cfg);
  5007. return err;
  5008. }
  5009. #endif
  5010. #ifndef LFS_READONLY
  5011. int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath) {
  5012. int err = LFS_LOCK(lfs->cfg);
  5013. if (err) {
  5014. return err;
  5015. }
  5016. LFS_TRACE("lfs_rename(%p, \"%s\", \"%s\")", (void*)lfs, oldpath, newpath);
  5017. err = lfs_rawrename(lfs, oldpath, newpath);
  5018. LFS_TRACE("lfs_rename -> %d", err);
  5019. LFS_UNLOCK(lfs->cfg);
  5020. return err;
  5021. }
  5022. #endif
  5023. int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info) {
  5024. int err = LFS_LOCK(lfs->cfg);
  5025. if (err) {
  5026. return err;
  5027. }
  5028. LFS_TRACE("lfs_stat(%p, \"%s\", %p)", (void*)lfs, path, (void*)info);
  5029. err = lfs_rawstat(lfs, path, info);
  5030. LFS_TRACE("lfs_stat -> %d", err);
  5031. LFS_UNLOCK(lfs->cfg);
  5032. return err;
  5033. }
  5034. lfs_ssize_t lfs_getattr(lfs_t *lfs, const char *path,
  5035. uint8_t type, void *buffer, lfs_size_t size) {
  5036. int err = LFS_LOCK(lfs->cfg);
  5037. if (err) {
  5038. return err;
  5039. }
  5040. LFS_TRACE("lfs_getattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
  5041. (void*)lfs, path, type, buffer, size);
  5042. lfs_ssize_t res = lfs_rawgetattr(lfs, path, type, buffer, size);
  5043. LFS_TRACE("lfs_getattr -> %"PRId32, res);
  5044. LFS_UNLOCK(lfs->cfg);
  5045. return res;
  5046. }
  5047. #ifndef LFS_READONLY
  5048. int lfs_setattr(lfs_t *lfs, const char *path,
  5049. uint8_t type, const void *buffer, lfs_size_t size) {
  5050. int err = LFS_LOCK(lfs->cfg);
  5051. if (err) {
  5052. return err;
  5053. }
  5054. LFS_TRACE("lfs_setattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
  5055. (void*)lfs, path, type, buffer, size);
  5056. err = lfs_rawsetattr(lfs, path, type, buffer, size);
  5057. LFS_TRACE("lfs_setattr -> %d", err);
  5058. LFS_UNLOCK(lfs->cfg);
  5059. return err;
  5060. }
  5061. #endif
  5062. #ifndef LFS_READONLY
  5063. int lfs_removeattr(lfs_t *lfs, const char *path, uint8_t type) {
  5064. int err = LFS_LOCK(lfs->cfg);
  5065. if (err) {
  5066. return err;
  5067. }
  5068. LFS_TRACE("lfs_removeattr(%p, \"%s\", %"PRIu8")", (void*)lfs, path, type);
  5069. err = lfs_rawremoveattr(lfs, path, type);
  5070. LFS_TRACE("lfs_removeattr -> %d", err);
  5071. LFS_UNLOCK(lfs->cfg);
  5072. return err;
  5073. }
  5074. #endif
  5075. #ifndef LFS_NO_MALLOC
  5076. int lfs_file_open(lfs_t *lfs, lfs_file_t *file, const char *path, int flags) {
  5077. int err = LFS_LOCK(lfs->cfg);
  5078. if (err) {
  5079. return err;
  5080. }
  5081. LFS_TRACE("lfs_file_open(%p, %p, \"%s\", %x)",
  5082. (void*)lfs, (void*)file, path, flags);
  5083. LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5084. err = lfs_file_rawopen(lfs, file, path, flags);
  5085. LFS_TRACE("lfs_file_open -> %d", err);
  5086. LFS_UNLOCK(lfs->cfg);
  5087. return err;
  5088. }
  5089. #endif
  5090. int lfs_file_opencfg(lfs_t *lfs, lfs_file_t *file,
  5091. const char *path, int flags,
  5092. const struct lfs_file_config *cfg) {
  5093. int err = LFS_LOCK(lfs->cfg);
  5094. if (err) {
  5095. return err;
  5096. }
  5097. LFS_TRACE("lfs_file_opencfg(%p, %p, \"%s\", %x, %p {"
  5098. ".buffer=%p, .attrs=%p, .attr_count=%"PRIu32"})",
  5099. (void*)lfs, (void*)file, path, flags,
  5100. (void*)cfg, cfg->buffer, (void*)cfg->attrs, cfg->attr_count);
  5101. LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5102. err = lfs_file_rawopencfg(lfs, file, path, flags, cfg);
  5103. LFS_TRACE("lfs_file_opencfg -> %d", err);
  5104. LFS_UNLOCK(lfs->cfg);
  5105. return err;
  5106. }
  5107. int lfs_file_close(lfs_t *lfs, lfs_file_t *file) {
  5108. int err = LFS_LOCK(lfs->cfg);
  5109. if (err) {
  5110. return err;
  5111. }
  5112. LFS_TRACE("lfs_file_close(%p, %p)", (void*)lfs, (void*)file);
  5113. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5114. err = lfs_file_rawclose(lfs, file);
  5115. LFS_TRACE("lfs_file_close -> %d", err);
  5116. LFS_UNLOCK(lfs->cfg);
  5117. return err;
  5118. }
  5119. #ifndef LFS_READONLY
  5120. int lfs_file_sync(lfs_t *lfs, lfs_file_t *file) {
  5121. int err = LFS_LOCK(lfs->cfg);
  5122. if (err) {
  5123. return err;
  5124. }
  5125. LFS_TRACE("lfs_file_sync(%p, %p)", (void*)lfs, (void*)file);
  5126. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5127. err = lfs_file_rawsync(lfs, file);
  5128. LFS_TRACE("lfs_file_sync -> %d", err);
  5129. LFS_UNLOCK(lfs->cfg);
  5130. return err;
  5131. }
  5132. #endif
  5133. lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file,
  5134. void *buffer, lfs_size_t size) {
  5135. int err = LFS_LOCK(lfs->cfg);
  5136. if (err) {
  5137. return err;
  5138. }
  5139. LFS_TRACE("lfs_file_read(%p, %p, %p, %"PRIu32")",
  5140. (void*)lfs, (void*)file, buffer, size);
  5141. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5142. lfs_ssize_t res = lfs_file_rawread(lfs, file, buffer, size);
  5143. LFS_TRACE("lfs_file_read -> %"PRId32, res);
  5144. LFS_UNLOCK(lfs->cfg);
  5145. return res;
  5146. }
  5147. #ifndef LFS_READONLY
  5148. lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file,
  5149. const void *buffer, lfs_size_t size) {
  5150. int err = LFS_LOCK(lfs->cfg);
  5151. if (err) {
  5152. return err;
  5153. }
  5154. LFS_TRACE("lfs_file_write(%p, %p, %p, %"PRIu32")",
  5155. (void*)lfs, (void*)file, buffer, size);
  5156. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5157. lfs_ssize_t res = lfs_file_rawwrite(lfs, file, buffer, size);
  5158. LFS_TRACE("lfs_file_write -> %"PRId32, res);
  5159. LFS_UNLOCK(lfs->cfg);
  5160. return res;
  5161. }
  5162. #endif
  5163. lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file,
  5164. lfs_soff_t off, int whence) {
  5165. int err = LFS_LOCK(lfs->cfg);
  5166. if (err) {
  5167. return err;
  5168. }
  5169. LFS_TRACE("lfs_file_seek(%p, %p, %"PRId32", %d)",
  5170. (void*)lfs, (void*)file, off, whence);
  5171. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5172. lfs_soff_t res = lfs_file_rawseek(lfs, file, off, whence);
  5173. LFS_TRACE("lfs_file_seek -> %"PRId32, res);
  5174. LFS_UNLOCK(lfs->cfg);
  5175. return res;
  5176. }
  5177. #ifndef LFS_READONLY
  5178. int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size) {
  5179. int err = LFS_LOCK(lfs->cfg);
  5180. if (err) {
  5181. return err;
  5182. }
  5183. LFS_TRACE("lfs_file_truncate(%p, %p, %"PRIu32")",
  5184. (void*)lfs, (void*)file, size);
  5185. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5186. err = lfs_file_rawtruncate(lfs, file, size);
  5187. LFS_TRACE("lfs_file_truncate -> %d", err);
  5188. LFS_UNLOCK(lfs->cfg);
  5189. return err;
  5190. }
  5191. #endif
  5192. lfs_soff_t lfs_file_tell(lfs_t *lfs, lfs_file_t *file) {
  5193. int err = LFS_LOCK(lfs->cfg);
  5194. if (err) {
  5195. return err;
  5196. }
  5197. LFS_TRACE("lfs_file_tell(%p, %p)", (void*)lfs, (void*)file);
  5198. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5199. lfs_soff_t res = lfs_file_rawtell(lfs, file);
  5200. LFS_TRACE("lfs_file_tell -> %"PRId32, res);
  5201. LFS_UNLOCK(lfs->cfg);
  5202. return res;
  5203. }
  5204. int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file) {
  5205. int err = LFS_LOCK(lfs->cfg);
  5206. if (err) {
  5207. return err;
  5208. }
  5209. LFS_TRACE("lfs_file_rewind(%p, %p)", (void*)lfs, (void*)file);
  5210. err = lfs_file_rawrewind(lfs, file);
  5211. LFS_TRACE("lfs_file_rewind -> %d", err);
  5212. LFS_UNLOCK(lfs->cfg);
  5213. return err;
  5214. }
  5215. lfs_soff_t lfs_file_size(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_size(%p, %p)", (void*)lfs, (void*)file);
  5221. LFS_ASSERT(lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)file));
  5222. lfs_soff_t res = lfs_file_rawsize(lfs, file);
  5223. LFS_TRACE("lfs_file_size -> %"PRId32, res);
  5224. LFS_UNLOCK(lfs->cfg);
  5225. return res;
  5226. }
  5227. #ifndef LFS_READONLY
  5228. int lfs_mkdir(lfs_t *lfs, const char *path) {
  5229. int err = LFS_LOCK(lfs->cfg);
  5230. if (err) {
  5231. return err;
  5232. }
  5233. LFS_TRACE("lfs_mkdir(%p, \"%s\")", (void*)lfs, path);
  5234. err = lfs_rawmkdir(lfs, path);
  5235. LFS_TRACE("lfs_mkdir -> %d", err);
  5236. LFS_UNLOCK(lfs->cfg);
  5237. return err;
  5238. }
  5239. #endif
  5240. int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path) {
  5241. int err = LFS_LOCK(lfs->cfg);
  5242. if (err) {
  5243. return err;
  5244. }
  5245. LFS_TRACE("lfs_dir_open(%p, %p, \"%s\")", (void*)lfs, (void*)dir, path);
  5246. LFS_ASSERT(!lfs_mlist_isopen(lfs->mlist, (struct lfs_mlist*)dir));
  5247. err = lfs_dir_rawopen(lfs, dir, path);
  5248. LFS_TRACE("lfs_dir_open -> %d", err);
  5249. LFS_UNLOCK(lfs->cfg);
  5250. return err;
  5251. }
  5252. int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir) {
  5253. int err = LFS_LOCK(lfs->cfg);
  5254. if (err) {
  5255. return err;
  5256. }
  5257. LFS_TRACE("lfs_dir_close(%p, %p)", (void*)lfs, (void*)dir);
  5258. err = lfs_dir_rawclose(lfs, dir);
  5259. LFS_TRACE("lfs_dir_close -> %d", err);
  5260. LFS_UNLOCK(lfs->cfg);
  5261. return err;
  5262. }
  5263. int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info) {
  5264. int err = LFS_LOCK(lfs->cfg);
  5265. if (err) {
  5266. return err;
  5267. }
  5268. LFS_TRACE("lfs_dir_read(%p, %p, %p)",
  5269. (void*)lfs, (void*)dir, (void*)info);
  5270. err = lfs_dir_rawread(lfs, dir, info);
  5271. LFS_TRACE("lfs_dir_read -> %d", err);
  5272. LFS_UNLOCK(lfs->cfg);
  5273. return err;
  5274. }
  5275. int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off) {
  5276. int err = LFS_LOCK(lfs->cfg);
  5277. if (err) {
  5278. return err;
  5279. }
  5280. LFS_TRACE("lfs_dir_seek(%p, %p, %"PRIu32")",
  5281. (void*)lfs, (void*)dir, off);
  5282. err = lfs_dir_rawseek(lfs, dir, off);
  5283. LFS_TRACE("lfs_dir_seek -> %d", err);
  5284. LFS_UNLOCK(lfs->cfg);
  5285. return err;
  5286. }
  5287. lfs_soff_t lfs_dir_tell(lfs_t *lfs, lfs_dir_t *dir) {
  5288. int err = LFS_LOCK(lfs->cfg);
  5289. if (err) {
  5290. return err;
  5291. }
  5292. LFS_TRACE("lfs_dir_tell(%p, %p)", (void*)lfs, (void*)dir);
  5293. lfs_soff_t res = lfs_dir_rawtell(lfs, dir);
  5294. LFS_TRACE("lfs_dir_tell -> %"PRId32, res);
  5295. LFS_UNLOCK(lfs->cfg);
  5296. return res;
  5297. }
  5298. int lfs_dir_rewind(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_rewind(%p, %p)", (void*)lfs, (void*)dir);
  5304. err = lfs_dir_rawrewind(lfs, dir);
  5305. LFS_TRACE("lfs_dir_rewind -> %d", err);
  5306. LFS_UNLOCK(lfs->cfg);
  5307. return err;
  5308. }
  5309. int lfs_fs_stat(lfs_t *lfs, struct lfs_fsinfo *fsinfo) {
  5310. int err = LFS_LOCK(lfs->cfg);
  5311. if (err) {
  5312. return err;
  5313. }
  5314. LFS_TRACE("lfs_fs_stat(%p, %p)", (void*)lfs, (void*)fsinfo);
  5315. err = lfs_fs_rawstat(lfs, fsinfo);
  5316. LFS_TRACE("lfs_fs_stat -> %d", err);
  5317. LFS_UNLOCK(lfs->cfg);
  5318. return err;
  5319. }
  5320. lfs_ssize_t lfs_fs_size(lfs_t *lfs) {
  5321. int err = LFS_LOCK(lfs->cfg);
  5322. if (err) {
  5323. return err;
  5324. }
  5325. LFS_TRACE("lfs_fs_size(%p)", (void*)lfs);
  5326. lfs_ssize_t res = lfs_fs_rawsize(lfs);
  5327. LFS_TRACE("lfs_fs_size -> %"PRId32, res);
  5328. LFS_UNLOCK(lfs->cfg);
  5329. return res;
  5330. }
  5331. int lfs_fs_traverse(lfs_t *lfs, int (*cb)(void *, lfs_block_t), void *data) {
  5332. int err = LFS_LOCK(lfs->cfg);
  5333. if (err) {
  5334. return err;
  5335. }
  5336. LFS_TRACE("lfs_fs_traverse(%p, %p, %p)",
  5337. (void*)lfs, (void*)(uintptr_t)cb, data);
  5338. err = lfs_fs_rawtraverse(lfs, cb, data, true);
  5339. LFS_TRACE("lfs_fs_traverse -> %d", err);
  5340. LFS_UNLOCK(lfs->cfg);
  5341. return err;
  5342. }
  5343. #ifndef LFS_READONLY
  5344. int lfs_fs_gc(lfs_t *lfs) {
  5345. int err = LFS_LOCK(lfs->cfg);
  5346. if (err) {
  5347. return err;
  5348. }
  5349. LFS_TRACE("lfs_fs_gc(%p)", (void*)lfs);
  5350. err = lfs_fs_rawgc(lfs);
  5351. LFS_TRACE("lfs_fs_gc -> %d", err);
  5352. LFS_UNLOCK(lfs->cfg);
  5353. return err;
  5354. }
  5355. #endif
  5356. #ifndef LFS_READONLY
  5357. int lfs_fs_mkconsistent(lfs_t *lfs) {
  5358. int err = LFS_LOCK(lfs->cfg);
  5359. if (err) {
  5360. return err;
  5361. }
  5362. LFS_TRACE("lfs_fs_mkconsistent(%p)", (void*)lfs);
  5363. err = lfs_fs_rawmkconsistent(lfs);
  5364. LFS_TRACE("lfs_fs_mkconsistent -> %d", err);
  5365. LFS_UNLOCK(lfs->cfg);
  5366. return err;
  5367. }
  5368. #endif
  5369. #ifndef LFS_READONLY
  5370. int lfs_fs_grow(lfs_t *lfs, lfs_size_t block_count) {
  5371. int err = LFS_LOCK(lfs->cfg);
  5372. if (err) {
  5373. return err;
  5374. }
  5375. LFS_TRACE("lfs_fs_grow(%p, %"PRIu32")", (void*)lfs, block_count);
  5376. err = lfs_fs_rawgrow(lfs, block_count);
  5377. LFS_TRACE("lfs_fs_grow -> %d", err);
  5378. LFS_UNLOCK(lfs->cfg);
  5379. return err;
  5380. }
  5381. #endif
  5382. #ifdef LFS_MIGRATE
  5383. int lfs_migrate(lfs_t *lfs, const struct lfs_config *cfg) {
  5384. int err = LFS_LOCK(cfg);
  5385. if (err) {
  5386. return err;
  5387. }
  5388. LFS_TRACE("lfs_migrate(%p, %p {.context=%p, "
  5389. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  5390. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  5391. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  5392. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  5393. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  5394. ".prog_buffer=%p, .lookahead_buffer=%p, "
  5395. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  5396. ".attr_max=%"PRIu32"})",
  5397. (void*)lfs, (void*)cfg, cfg->context,
  5398. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  5399. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  5400. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  5401. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  5402. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  5403. cfg->name_max, cfg->file_max, cfg->attr_max);
  5404. err = lfs_rawmigrate(lfs, cfg);
  5405. LFS_TRACE("lfs_migrate -> %d", err);
  5406. LFS_UNLOCK(cfg);
  5407. return err;
  5408. }
  5409. #endif