lfs.c 183 KB

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