lfs.c 151 KB

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