lfs.c 185 KB

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