lfs.c 172 KB

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