lfs.c 185 KB

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