lfs.c 150 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. int lfs_mkdir(lfs_t *lfs, const char *path) {
  1690. #ifdef LFS_READONLY
  1691. return LFS_ERR_NOSYS;
  1692. #else
  1693. LFS_TRACE("lfs_mkdir(%p, \"%s\")", (void*)lfs, path);
  1694. // deorphan if we haven't yet, needed at most once after poweron
  1695. int err = lfs_fs_forceconsistency(lfs);
  1696. if (err) {
  1697. LFS_TRACE("lfs_mkdir -> %d", err);
  1698. return err;
  1699. }
  1700. struct lfs_mlist cwd;
  1701. cwd.next = lfs->mlist;
  1702. uint16_t id;
  1703. err = lfs_dir_find(lfs, &cwd.m, &path, &id);
  1704. if (!(err == LFS_ERR_NOENT && id != 0x3ff)) {
  1705. LFS_TRACE("lfs_mkdir -> %d", (err < 0) ? err : LFS_ERR_EXIST);
  1706. return (err < 0) ? err : LFS_ERR_EXIST;
  1707. }
  1708. // check that name fits
  1709. lfs_size_t nlen = strlen(path);
  1710. if (nlen > lfs->name_max) {
  1711. LFS_TRACE("lfs_mkdir -> %d", LFS_ERR_NAMETOOLONG);
  1712. return LFS_ERR_NAMETOOLONG;
  1713. }
  1714. // build up new directory
  1715. lfs_alloc_ack(lfs);
  1716. lfs_mdir_t dir;
  1717. err = lfs_dir_alloc(lfs, &dir);
  1718. if (err) {
  1719. LFS_TRACE("lfs_mkdir -> %d", err);
  1720. return err;
  1721. }
  1722. // find end of list
  1723. lfs_mdir_t pred = cwd.m;
  1724. while (pred.split) {
  1725. err = lfs_dir_fetch(lfs, &pred, pred.tail);
  1726. if (err) {
  1727. LFS_TRACE("lfs_mkdir -> %d", err);
  1728. return err;
  1729. }
  1730. }
  1731. // setup dir
  1732. lfs_pair_tole32(pred.tail);
  1733. err = lfs_dir_commit(lfs, &dir, LFS_MKATTRS(
  1734. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), pred.tail}));
  1735. lfs_pair_fromle32(pred.tail);
  1736. if (err) {
  1737. LFS_TRACE("lfs_mkdir -> %d", err);
  1738. return err;
  1739. }
  1740. // current block end of list?
  1741. if (cwd.m.split) {
  1742. // update tails, this creates a desync
  1743. lfs_fs_preporphans(lfs, +1);
  1744. // it's possible our predecessor has to be relocated, and if
  1745. // our parent is our predecessor's predecessor, this could have
  1746. // caused our parent to go out of date, fortunately we can hook
  1747. // ourselves into littlefs to catch this
  1748. cwd.type = 0;
  1749. cwd.id = 0;
  1750. lfs->mlist = &cwd;
  1751. lfs_pair_tole32(dir.pair);
  1752. err = lfs_dir_commit(lfs, &pred, LFS_MKATTRS(
  1753. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir.pair}));
  1754. lfs_pair_fromle32(dir.pair);
  1755. if (err) {
  1756. lfs->mlist = cwd.next;
  1757. LFS_TRACE("lfs_mkdir -> %d", err);
  1758. return err;
  1759. }
  1760. lfs->mlist = cwd.next;
  1761. lfs_fs_preporphans(lfs, -1);
  1762. }
  1763. // now insert into our parent block
  1764. lfs_pair_tole32(dir.pair);
  1765. err = lfs_dir_commit(lfs, &cwd.m, LFS_MKATTRS(
  1766. {LFS_MKTAG(LFS_TYPE_CREATE, id, 0), NULL},
  1767. {LFS_MKTAG(LFS_TYPE_DIR, id, nlen), path},
  1768. {LFS_MKTAG(LFS_TYPE_DIRSTRUCT, id, 8), dir.pair},
  1769. {LFS_MKTAG_IF(!cwd.m.split,
  1770. LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir.pair}));
  1771. lfs_pair_fromle32(dir.pair);
  1772. if (err) {
  1773. LFS_TRACE("lfs_mkdir -> %d", err);
  1774. return err;
  1775. }
  1776. LFS_TRACE("lfs_mkdir -> %d", 0);
  1777. return 0;
  1778. #endif
  1779. }
  1780. int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path) {
  1781. LFS_TRACE("lfs_dir_open(%p, %p, \"%s\")", (void*)lfs, (void*)dir, path);
  1782. lfs_stag_t tag = lfs_dir_find(lfs, &dir->m, &path, NULL);
  1783. if (tag < 0) {
  1784. LFS_TRACE("lfs_dir_open -> %"PRId32, tag);
  1785. return tag;
  1786. }
  1787. if (lfs_tag_type3(tag) != LFS_TYPE_DIR) {
  1788. LFS_TRACE("lfs_dir_open -> %d", LFS_ERR_NOTDIR);
  1789. return LFS_ERR_NOTDIR;
  1790. }
  1791. lfs_block_t pair[2];
  1792. if (lfs_tag_id(tag) == 0x3ff) {
  1793. // handle root dir separately
  1794. pair[0] = lfs->root[0];
  1795. pair[1] = lfs->root[1];
  1796. } else {
  1797. // get dir pair from parent
  1798. lfs_stag_t res = lfs_dir_get(lfs, &dir->m, LFS_MKTAG(0x700, 0x3ff, 0),
  1799. LFS_MKTAG(LFS_TYPE_STRUCT, lfs_tag_id(tag), 8), pair);
  1800. if (res < 0) {
  1801. LFS_TRACE("lfs_dir_open -> %"PRId32, res);
  1802. return res;
  1803. }
  1804. lfs_pair_fromle32(pair);
  1805. }
  1806. // fetch first pair
  1807. int err = lfs_dir_fetch(lfs, &dir->m, pair);
  1808. if (err) {
  1809. LFS_TRACE("lfs_dir_open -> %d", err);
  1810. return err;
  1811. }
  1812. // setup entry
  1813. dir->head[0] = dir->m.pair[0];
  1814. dir->head[1] = dir->m.pair[1];
  1815. dir->id = 0;
  1816. dir->pos = 0;
  1817. // add to list of mdirs
  1818. dir->type = LFS_TYPE_DIR;
  1819. dir->next = (lfs_dir_t*)lfs->mlist;
  1820. lfs->mlist = (struct lfs_mlist*)dir;
  1821. LFS_TRACE("lfs_dir_open -> %d", 0);
  1822. return 0;
  1823. }
  1824. int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir) {
  1825. LFS_TRACE("lfs_dir_close(%p, %p)", (void*)lfs, (void*)dir);
  1826. // remove from list of mdirs
  1827. for (struct lfs_mlist **p = &lfs->mlist; *p; p = &(*p)->next) {
  1828. if (*p == (struct lfs_mlist*)dir) {
  1829. *p = (*p)->next;
  1830. break;
  1831. }
  1832. }
  1833. LFS_TRACE("lfs_dir_close -> %d", 0);
  1834. return 0;
  1835. }
  1836. int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info) {
  1837. LFS_TRACE("lfs_dir_read(%p, %p, %p)",
  1838. (void*)lfs, (void*)dir, (void*)info);
  1839. memset(info, 0, sizeof(*info));
  1840. // special offset for '.' and '..'
  1841. if (dir->pos == 0) {
  1842. info->type = LFS_TYPE_DIR;
  1843. strcpy(info->name, ".");
  1844. dir->pos += 1;
  1845. LFS_TRACE("lfs_dir_read -> %d", true);
  1846. return true;
  1847. } else if (dir->pos == 1) {
  1848. info->type = LFS_TYPE_DIR;
  1849. strcpy(info->name, "..");
  1850. dir->pos += 1;
  1851. LFS_TRACE("lfs_dir_read -> %d", true);
  1852. return true;
  1853. }
  1854. while (true) {
  1855. if (dir->id == dir->m.count) {
  1856. if (!dir->m.split) {
  1857. LFS_TRACE("lfs_dir_read -> %d", false);
  1858. return false;
  1859. }
  1860. int err = lfs_dir_fetch(lfs, &dir->m, dir->m.tail);
  1861. if (err) {
  1862. LFS_TRACE("lfs_dir_read -> %d", err);
  1863. return err;
  1864. }
  1865. dir->id = 0;
  1866. }
  1867. int err = lfs_dir_getinfo(lfs, &dir->m, dir->id, info);
  1868. if (err && err != LFS_ERR_NOENT) {
  1869. LFS_TRACE("lfs_dir_read -> %d", err);
  1870. return err;
  1871. }
  1872. dir->id += 1;
  1873. if (err != LFS_ERR_NOENT) {
  1874. break;
  1875. }
  1876. }
  1877. dir->pos += 1;
  1878. LFS_TRACE("lfs_dir_read -> %d", true);
  1879. return true;
  1880. }
  1881. int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off) {
  1882. LFS_TRACE("lfs_dir_seek(%p, %p, %"PRIu32")",
  1883. (void*)lfs, (void*)dir, off);
  1884. // simply walk from head dir
  1885. int err = lfs_dir_rewind(lfs, dir);
  1886. if (err) {
  1887. LFS_TRACE("lfs_dir_seek -> %d", err);
  1888. return err;
  1889. }
  1890. // first two for ./..
  1891. dir->pos = lfs_min(2, off);
  1892. off -= dir->pos;
  1893. // skip superblock entry
  1894. dir->id = (off > 0 && lfs_pair_cmp(dir->head, lfs->root) == 0);
  1895. while (off > 0) {
  1896. int diff = lfs_min(dir->m.count - dir->id, off);
  1897. dir->id += diff;
  1898. dir->pos += diff;
  1899. off -= diff;
  1900. if (dir->id == dir->m.count) {
  1901. if (!dir->m.split) {
  1902. LFS_TRACE("lfs_dir_seek -> %d", LFS_ERR_INVAL);
  1903. return LFS_ERR_INVAL;
  1904. }
  1905. err = lfs_dir_fetch(lfs, &dir->m, dir->m.tail);
  1906. if (err) {
  1907. LFS_TRACE("lfs_dir_seek -> %d", err);
  1908. return err;
  1909. }
  1910. dir->id = 0;
  1911. }
  1912. }
  1913. LFS_TRACE("lfs_dir_seek -> %d", 0);
  1914. return 0;
  1915. }
  1916. lfs_soff_t lfs_dir_tell(lfs_t *lfs, lfs_dir_t *dir) {
  1917. LFS_TRACE("lfs_dir_tell(%p, %p)", (void*)lfs, (void*)dir);
  1918. (void)lfs;
  1919. LFS_TRACE("lfs_dir_tell -> %"PRId32, dir->pos);
  1920. return dir->pos;
  1921. }
  1922. int lfs_dir_rewind(lfs_t *lfs, lfs_dir_t *dir) {
  1923. LFS_TRACE("lfs_dir_rewind(%p, %p)", (void*)lfs, (void*)dir);
  1924. // reload the head dir
  1925. int err = lfs_dir_fetch(lfs, &dir->m, dir->head);
  1926. if (err) {
  1927. LFS_TRACE("lfs_dir_rewind -> %d", err);
  1928. return err;
  1929. }
  1930. dir->id = 0;
  1931. dir->pos = 0;
  1932. LFS_TRACE("lfs_dir_rewind -> %d", 0);
  1933. return 0;
  1934. }
  1935. /// File index list operations ///
  1936. static int lfs_ctz_index(lfs_t *lfs, lfs_off_t *off) {
  1937. lfs_off_t size = *off;
  1938. lfs_off_t b = lfs->cfg->block_size - 2*4;
  1939. lfs_off_t i = size / b;
  1940. if (i == 0) {
  1941. return 0;
  1942. }
  1943. i = (size - 4*(lfs_popc(i-1)+2)) / b;
  1944. *off = size - b*i - 4*lfs_popc(i);
  1945. return i;
  1946. }
  1947. static int lfs_ctz_find(lfs_t *lfs,
  1948. const lfs_cache_t *pcache, lfs_cache_t *rcache,
  1949. lfs_block_t head, lfs_size_t size,
  1950. lfs_size_t pos, lfs_block_t *block, lfs_off_t *off) {
  1951. if (size == 0) {
  1952. *block = LFS_BLOCK_NULL;
  1953. *off = 0;
  1954. return 0;
  1955. }
  1956. lfs_off_t current = lfs_ctz_index(lfs, &(lfs_off_t){size-1});
  1957. lfs_off_t target = lfs_ctz_index(lfs, &pos);
  1958. while (current > target) {
  1959. lfs_size_t skip = lfs_min(
  1960. lfs_npw2(current-target+1) - 1,
  1961. lfs_ctz(current));
  1962. int err = lfs_bd_read(lfs,
  1963. pcache, rcache, sizeof(head),
  1964. head, 4*skip, &head, sizeof(head));
  1965. head = lfs_fromle32(head);
  1966. if (err) {
  1967. return err;
  1968. }
  1969. current -= 1 << skip;
  1970. }
  1971. *block = head;
  1972. *off = pos;
  1973. return 0;
  1974. }
  1975. #ifndef LFS_READONLY
  1976. static int lfs_ctz_extend(lfs_t *lfs,
  1977. lfs_cache_t *pcache, lfs_cache_t *rcache,
  1978. lfs_block_t head, lfs_size_t size,
  1979. lfs_block_t *block, lfs_off_t *off) {
  1980. while (true) {
  1981. // go ahead and grab a block
  1982. lfs_block_t nblock;
  1983. int err = lfs_alloc(lfs, &nblock);
  1984. if (err) {
  1985. return err;
  1986. }
  1987. {
  1988. err = lfs_bd_erase(lfs, nblock);
  1989. if (err) {
  1990. if (err == LFS_ERR_CORRUPT) {
  1991. goto relocate;
  1992. }
  1993. return err;
  1994. }
  1995. if (size == 0) {
  1996. *block = nblock;
  1997. *off = 0;
  1998. return 0;
  1999. }
  2000. lfs_size_t noff = size - 1;
  2001. lfs_off_t index = lfs_ctz_index(lfs, &noff);
  2002. noff = noff + 1;
  2003. // just copy out the last block if it is incomplete
  2004. if (noff != lfs->cfg->block_size) {
  2005. for (lfs_off_t i = 0; i < noff; i++) {
  2006. uint8_t data;
  2007. err = lfs_bd_read(lfs,
  2008. NULL, rcache, noff-i,
  2009. head, i, &data, 1);
  2010. if (err) {
  2011. return err;
  2012. }
  2013. err = lfs_bd_prog(lfs,
  2014. pcache, rcache, true,
  2015. nblock, i, &data, 1);
  2016. if (err) {
  2017. if (err == LFS_ERR_CORRUPT) {
  2018. goto relocate;
  2019. }
  2020. return err;
  2021. }
  2022. }
  2023. *block = nblock;
  2024. *off = noff;
  2025. return 0;
  2026. }
  2027. // append block
  2028. index += 1;
  2029. lfs_size_t skips = lfs_ctz(index) + 1;
  2030. lfs_block_t nhead = head;
  2031. for (lfs_off_t i = 0; i < skips; i++) {
  2032. nhead = lfs_tole32(nhead);
  2033. err = lfs_bd_prog(lfs, pcache, rcache, true,
  2034. nblock, 4*i, &nhead, 4);
  2035. nhead = lfs_fromle32(nhead);
  2036. if (err) {
  2037. if (err == LFS_ERR_CORRUPT) {
  2038. goto relocate;
  2039. }
  2040. return err;
  2041. }
  2042. if (i != skips-1) {
  2043. err = lfs_bd_read(lfs,
  2044. NULL, rcache, sizeof(nhead),
  2045. nhead, 4*i, &nhead, sizeof(nhead));
  2046. nhead = lfs_fromle32(nhead);
  2047. if (err) {
  2048. return err;
  2049. }
  2050. }
  2051. }
  2052. *block = nblock;
  2053. *off = 4*skips;
  2054. return 0;
  2055. }
  2056. relocate:
  2057. LFS_DEBUG("Bad block at 0x%"PRIx32, nblock);
  2058. // just clear cache and try a new block
  2059. lfs_cache_drop(lfs, pcache);
  2060. }
  2061. }
  2062. #endif
  2063. static int lfs_ctz_traverse(lfs_t *lfs,
  2064. const lfs_cache_t *pcache, lfs_cache_t *rcache,
  2065. lfs_block_t head, lfs_size_t size,
  2066. int (*cb)(void*, lfs_block_t), void *data) {
  2067. if (size == 0) {
  2068. return 0;
  2069. }
  2070. lfs_off_t index = lfs_ctz_index(lfs, &(lfs_off_t){size-1});
  2071. while (true) {
  2072. int err = cb(data, head);
  2073. if (err) {
  2074. return err;
  2075. }
  2076. if (index == 0) {
  2077. return 0;
  2078. }
  2079. lfs_block_t heads[2];
  2080. int count = 2 - (index & 1);
  2081. err = lfs_bd_read(lfs,
  2082. pcache, rcache, count*sizeof(head),
  2083. head, 0, &heads, count*sizeof(head));
  2084. heads[0] = lfs_fromle32(heads[0]);
  2085. heads[1] = lfs_fromle32(heads[1]);
  2086. if (err) {
  2087. return err;
  2088. }
  2089. for (int i = 0; i < count-1; i++) {
  2090. err = cb(data, heads[i]);
  2091. if (err) {
  2092. return err;
  2093. }
  2094. }
  2095. head = heads[count-1];
  2096. index -= count;
  2097. }
  2098. }
  2099. /// Top level file operations ///
  2100. int lfs_file_opencfg(lfs_t *lfs, lfs_file_t *file,
  2101. const char *path, int flags,
  2102. const struct lfs_file_config *cfg) {
  2103. LFS_TRACE("lfs_file_opencfg(%p, %p, \"%s\", %x, %p {"
  2104. ".buffer=%p, .attrs=%p, .attr_count=%"PRIu32"})",
  2105. (void*)lfs, (void*)file, path, flags,
  2106. (void*)cfg, cfg->buffer, (void*)cfg->attrs, cfg->attr_count);
  2107. // deorphan if we haven't yet, needed at most once after poweron
  2108. if ((flags & 3) != LFS_O_RDONLY) {
  2109. #ifdef LFS_READONLY
  2110. return LFS_ERR_INVAL;
  2111. #else
  2112. int err = lfs_fs_forceconsistency(lfs);
  2113. if (err) {
  2114. LFS_TRACE("lfs_file_opencfg -> %d", err);
  2115. return err;
  2116. }
  2117. #endif
  2118. }
  2119. // setup simple file details
  2120. int err;
  2121. file->cfg = cfg;
  2122. file->flags = flags | LFS_F_OPENED;
  2123. file->pos = 0;
  2124. file->off = 0;
  2125. file->cache.buffer = NULL;
  2126. // allocate entry for file if it doesn't exist
  2127. lfs_stag_t tag = lfs_dir_find(lfs, &file->m, &path, &file->id);
  2128. if (tag < 0 && !(tag == LFS_ERR_NOENT && file->id != 0x3ff)) {
  2129. err = tag;
  2130. goto cleanup;
  2131. }
  2132. // get id, add to list of mdirs to catch update changes
  2133. file->type = LFS_TYPE_REG;
  2134. file->next = (lfs_file_t*)lfs->mlist;
  2135. lfs->mlist = (struct lfs_mlist*)file;
  2136. if (tag == LFS_ERR_NOENT) {
  2137. #ifdef LFS_READONLY
  2138. err = LFS_ERR_NOENT;
  2139. goto cleanup;
  2140. #else
  2141. if (!(flags & LFS_O_CREAT)) {
  2142. err = LFS_ERR_NOENT;
  2143. goto cleanup;
  2144. }
  2145. // check that name fits
  2146. lfs_size_t nlen = strlen(path);
  2147. if (nlen > lfs->name_max) {
  2148. err = LFS_ERR_NAMETOOLONG;
  2149. goto cleanup;
  2150. }
  2151. // get next slot and create entry to remember name
  2152. err = lfs_dir_commit(lfs, &file->m, LFS_MKATTRS(
  2153. {LFS_MKTAG(LFS_TYPE_CREATE, file->id, 0), NULL},
  2154. {LFS_MKTAG(LFS_TYPE_REG, file->id, nlen), path},
  2155. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0), NULL}));
  2156. if (err) {
  2157. err = LFS_ERR_NAMETOOLONG;
  2158. goto cleanup;
  2159. }
  2160. tag = LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, 0);
  2161. #endif
  2162. } else if (flags & LFS_O_EXCL) {
  2163. err = LFS_ERR_EXIST;
  2164. goto cleanup;
  2165. } else if (lfs_tag_type3(tag) != LFS_TYPE_REG) {
  2166. err = LFS_ERR_ISDIR;
  2167. goto cleanup;
  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. } else {
  2173. // try to load what's on disk, if it's inlined we'll fix it later
  2174. tag = lfs_dir_get(lfs, &file->m, LFS_MKTAG(0x700, 0x3ff, 0),
  2175. LFS_MKTAG(LFS_TYPE_STRUCT, file->id, 8), &file->ctz);
  2176. if (tag < 0) {
  2177. err = tag;
  2178. goto cleanup;
  2179. }
  2180. lfs_ctz_fromle32(&file->ctz);
  2181. }
  2182. // fetch attrs
  2183. for (unsigned i = 0; i < file->cfg->attr_count; i++) {
  2184. if ((file->flags & 3) != LFS_O_WRONLY) {
  2185. lfs_stag_t res = lfs_dir_get(lfs, &file->m,
  2186. LFS_MKTAG(0x7ff, 0x3ff, 0),
  2187. LFS_MKTAG(LFS_TYPE_USERATTR + file->cfg->attrs[i].type,
  2188. file->id, file->cfg->attrs[i].size),
  2189. file->cfg->attrs[i].buffer);
  2190. if (res < 0 && res != LFS_ERR_NOENT) {
  2191. err = res;
  2192. goto cleanup;
  2193. }
  2194. }
  2195. if ((file->flags & 3) != LFS_O_RDONLY) {
  2196. if (file->cfg->attrs[i].size > lfs->attr_max) {
  2197. err = LFS_ERR_NOSPC;
  2198. goto cleanup;
  2199. }
  2200. file->flags |= LFS_F_DIRTY;
  2201. }
  2202. }
  2203. // allocate buffer if needed
  2204. if (file->cfg->buffer) {
  2205. file->cache.buffer = file->cfg->buffer;
  2206. } else {
  2207. file->cache.buffer = lfs_malloc(lfs->cfg->cache_size);
  2208. if (!file->cache.buffer) {
  2209. err = LFS_ERR_NOMEM;
  2210. goto cleanup;
  2211. }
  2212. }
  2213. // zero to avoid information leak
  2214. lfs_cache_zero(lfs, &file->cache);
  2215. if (lfs_tag_type3(tag) == LFS_TYPE_INLINESTRUCT) {
  2216. // load inline files
  2217. file->ctz.head = LFS_BLOCK_INLINE;
  2218. file->ctz.size = lfs_tag_size(tag);
  2219. file->flags |= LFS_F_INLINE;
  2220. file->cache.block = file->ctz.head;
  2221. file->cache.off = 0;
  2222. file->cache.size = lfs->cfg->cache_size;
  2223. // don't always read (may be new/trunc file)
  2224. if (file->ctz.size > 0) {
  2225. lfs_stag_t res = lfs_dir_get(lfs, &file->m,
  2226. LFS_MKTAG(0x700, 0x3ff, 0),
  2227. LFS_MKTAG(LFS_TYPE_STRUCT, file->id,
  2228. lfs_min(file->cache.size, 0x3fe)),
  2229. file->cache.buffer);
  2230. if (res < 0) {
  2231. err = res;
  2232. goto cleanup;
  2233. }
  2234. }
  2235. }
  2236. LFS_TRACE("lfs_file_opencfg -> %d", 0);
  2237. return 0;
  2238. cleanup:
  2239. // clean up lingering resources
  2240. file->flags |= LFS_F_ERRED;
  2241. lfs_file_close(lfs, file);
  2242. LFS_TRACE("lfs_file_opencfg -> %d", err);
  2243. return err;
  2244. }
  2245. int lfs_file_open(lfs_t *lfs, lfs_file_t *file,
  2246. const char *path, int flags) {
  2247. LFS_TRACE("lfs_file_open(%p, %p, \"%s\", %x)",
  2248. (void*)lfs, (void*)file, path, flags);
  2249. static const struct lfs_file_config defaults = {0};
  2250. int err = lfs_file_opencfg(lfs, file, path, flags, &defaults);
  2251. LFS_TRACE("lfs_file_open -> %d", err);
  2252. return err;
  2253. }
  2254. int lfs_file_close(lfs_t *lfs, lfs_file_t *file) {
  2255. LFS_TRACE("lfs_file_close(%p, %p)", (void*)lfs, (void*)file);
  2256. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2257. int err = lfs_file_sync(lfs, file);
  2258. // remove from list of mdirs
  2259. for (struct lfs_mlist **p = &lfs->mlist; *p; p = &(*p)->next) {
  2260. if (*p == (struct lfs_mlist*)file) {
  2261. *p = (*p)->next;
  2262. break;
  2263. }
  2264. }
  2265. // clean up memory
  2266. if (!file->cfg->buffer) {
  2267. lfs_free(file->cache.buffer);
  2268. }
  2269. file->flags &= ~LFS_F_OPENED;
  2270. LFS_TRACE("lfs_file_close -> %d", err);
  2271. return err;
  2272. }
  2273. #ifndef LFS_READONLY
  2274. static int lfs_file_relocate(lfs_t *lfs, lfs_file_t *file) {
  2275. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2276. while (true) {
  2277. // just relocate what exists into new block
  2278. lfs_block_t nblock;
  2279. int err = lfs_alloc(lfs, &nblock);
  2280. if (err) {
  2281. return err;
  2282. }
  2283. err = lfs_bd_erase(lfs, nblock);
  2284. if (err) {
  2285. if (err == LFS_ERR_CORRUPT) {
  2286. goto relocate;
  2287. }
  2288. return err;
  2289. }
  2290. // either read from dirty cache or disk
  2291. for (lfs_off_t i = 0; i < file->off; i++) {
  2292. uint8_t data;
  2293. if (file->flags & LFS_F_INLINE) {
  2294. err = lfs_dir_getread(lfs, &file->m,
  2295. // note we evict inline files before they can be dirty
  2296. NULL, &file->cache, file->off-i,
  2297. LFS_MKTAG(0xfff, 0x1ff, 0),
  2298. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0),
  2299. i, &data, 1);
  2300. if (err) {
  2301. return err;
  2302. }
  2303. } else {
  2304. err = lfs_bd_read(lfs,
  2305. &file->cache, &lfs->rcache, file->off-i,
  2306. file->block, i, &data, 1);
  2307. if (err) {
  2308. return err;
  2309. }
  2310. }
  2311. err = lfs_bd_prog(lfs,
  2312. &lfs->pcache, &lfs->rcache, true,
  2313. nblock, i, &data, 1);
  2314. if (err) {
  2315. if (err == LFS_ERR_CORRUPT) {
  2316. goto relocate;
  2317. }
  2318. return err;
  2319. }
  2320. }
  2321. // copy over new state of file
  2322. memcpy(file->cache.buffer, lfs->pcache.buffer, lfs->cfg->cache_size);
  2323. file->cache.block = lfs->pcache.block;
  2324. file->cache.off = lfs->pcache.off;
  2325. file->cache.size = lfs->pcache.size;
  2326. lfs_cache_zero(lfs, &lfs->pcache);
  2327. file->block = nblock;
  2328. file->flags |= LFS_F_WRITING;
  2329. return 0;
  2330. relocate:
  2331. LFS_DEBUG("Bad block at 0x%"PRIx32, nblock);
  2332. // just clear cache and try a new block
  2333. lfs_cache_drop(lfs, &lfs->pcache);
  2334. }
  2335. }
  2336. #endif
  2337. #ifndef LFS_READONLY
  2338. static int lfs_file_outline(lfs_t *lfs, lfs_file_t *file) {
  2339. file->off = file->pos;
  2340. lfs_alloc_ack(lfs);
  2341. int err = lfs_file_relocate(lfs, file);
  2342. if (err) {
  2343. return err;
  2344. }
  2345. file->flags &= ~LFS_F_INLINE;
  2346. return 0;
  2347. }
  2348. #endif
  2349. static int lfs_file_flush(lfs_t *lfs, lfs_file_t *file) {
  2350. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2351. if (file->flags & LFS_F_READING) {
  2352. if (!(file->flags & LFS_F_INLINE)) {
  2353. lfs_cache_drop(lfs, &file->cache);
  2354. }
  2355. file->flags &= ~LFS_F_READING;
  2356. }
  2357. #ifndef LFS_READONLY
  2358. if (file->flags & LFS_F_WRITING) {
  2359. lfs_off_t pos = file->pos;
  2360. if (!(file->flags & LFS_F_INLINE)) {
  2361. // copy over anything after current branch
  2362. lfs_file_t orig = {
  2363. .ctz.head = file->ctz.head,
  2364. .ctz.size = file->ctz.size,
  2365. .flags = LFS_O_RDONLY | LFS_F_OPENED,
  2366. .pos = file->pos,
  2367. .cache = lfs->rcache,
  2368. };
  2369. lfs_cache_drop(lfs, &lfs->rcache);
  2370. while (file->pos < file->ctz.size) {
  2371. // copy over a byte at a time, leave it up to caching
  2372. // to make this efficient
  2373. uint8_t data;
  2374. lfs_ssize_t res = lfs_file_read(lfs, &orig, &data, 1);
  2375. if (res < 0) {
  2376. return res;
  2377. }
  2378. res = lfs_file_write(lfs, file, &data, 1);
  2379. if (res < 0) {
  2380. return res;
  2381. }
  2382. // keep our reference to the rcache in sync
  2383. if (lfs->rcache.block != LFS_BLOCK_NULL) {
  2384. lfs_cache_drop(lfs, &orig.cache);
  2385. lfs_cache_drop(lfs, &lfs->rcache);
  2386. }
  2387. }
  2388. // write out what we have
  2389. while (true) {
  2390. int err = lfs_bd_flush(lfs, &file->cache, &lfs->rcache, true);
  2391. if (err) {
  2392. if (err == LFS_ERR_CORRUPT) {
  2393. goto relocate;
  2394. }
  2395. return err;
  2396. }
  2397. break;
  2398. relocate:
  2399. LFS_DEBUG("Bad block at 0x%"PRIx32, file->block);
  2400. err = lfs_file_relocate(lfs, file);
  2401. if (err) {
  2402. return err;
  2403. }
  2404. }
  2405. } else {
  2406. file->pos = lfs_max(file->pos, file->ctz.size);
  2407. }
  2408. // actual file updates
  2409. file->ctz.head = file->block;
  2410. file->ctz.size = file->pos;
  2411. file->flags &= ~LFS_F_WRITING;
  2412. file->flags |= LFS_F_DIRTY;
  2413. file->pos = pos;
  2414. }
  2415. #endif
  2416. return 0;
  2417. }
  2418. int lfs_file_sync(lfs_t *lfs, lfs_file_t *file) {
  2419. LFS_TRACE("lfs_file_sync(%p, %p)", (void*)lfs, (void*)file);
  2420. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2421. if (file->flags & LFS_F_ERRED) {
  2422. // it's not safe to do anything if our file errored
  2423. LFS_TRACE("lfs_file_sync -> %d", 0);
  2424. return 0;
  2425. }
  2426. int err = lfs_file_flush(lfs, file);
  2427. if (err) {
  2428. file->flags |= LFS_F_ERRED;
  2429. LFS_TRACE("lfs_file_sync -> %d", err);
  2430. return err;
  2431. }
  2432. #ifndef LFS_READONLY
  2433. if ((file->flags & LFS_F_DIRTY) &&
  2434. !lfs_pair_isnull(file->m.pair)) {
  2435. // update dir entry
  2436. uint16_t type;
  2437. const void *buffer;
  2438. lfs_size_t size;
  2439. struct lfs_ctz ctz;
  2440. if (file->flags & LFS_F_INLINE) {
  2441. // inline the whole file
  2442. type = LFS_TYPE_INLINESTRUCT;
  2443. buffer = file->cache.buffer;
  2444. size = file->ctz.size;
  2445. } else {
  2446. // update the ctz reference
  2447. type = LFS_TYPE_CTZSTRUCT;
  2448. // copy ctz so alloc will work during a relocate
  2449. ctz = file->ctz;
  2450. lfs_ctz_tole32(&ctz);
  2451. buffer = &ctz;
  2452. size = sizeof(ctz);
  2453. }
  2454. // commit file data and attributes
  2455. err = lfs_dir_commit(lfs, &file->m, LFS_MKATTRS(
  2456. {LFS_MKTAG(type, file->id, size), buffer},
  2457. {LFS_MKTAG(LFS_FROM_USERATTRS, file->id,
  2458. file->cfg->attr_count), file->cfg->attrs}));
  2459. if (err) {
  2460. file->flags |= LFS_F_ERRED;
  2461. LFS_TRACE("lfs_file_sync -> %d", err);
  2462. return err;
  2463. }
  2464. file->flags &= ~LFS_F_DIRTY;
  2465. }
  2466. #endif
  2467. LFS_TRACE("lfs_file_sync -> %d", 0);
  2468. return 0;
  2469. }
  2470. lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file,
  2471. void *buffer, lfs_size_t size) {
  2472. LFS_TRACE("lfs_file_read(%p, %p, %p, %"PRIu32")",
  2473. (void*)lfs, (void*)file, buffer, size);
  2474. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2475. LFS_ASSERT((file->flags & 3) != LFS_O_WRONLY);
  2476. uint8_t *data = buffer;
  2477. lfs_size_t nsize = size;
  2478. #ifndef LFS_READONLY
  2479. if (file->flags & LFS_F_WRITING) {
  2480. // flush out any writes
  2481. int err = lfs_file_flush(lfs, file);
  2482. if (err) {
  2483. LFS_TRACE("lfs_file_read -> %d", err);
  2484. return err;
  2485. }
  2486. }
  2487. #endif
  2488. if (file->pos >= file->ctz.size) {
  2489. // eof if past end
  2490. LFS_TRACE("lfs_file_read -> %d", 0);
  2491. return 0;
  2492. }
  2493. size = lfs_min(size, file->ctz.size - file->pos);
  2494. nsize = size;
  2495. while (nsize > 0) {
  2496. // check if we need a new block
  2497. if (!(file->flags & LFS_F_READING) ||
  2498. file->off == lfs->cfg->block_size) {
  2499. if (!(file->flags & LFS_F_INLINE)) {
  2500. int err = lfs_ctz_find(lfs, NULL, &file->cache,
  2501. file->ctz.head, file->ctz.size,
  2502. file->pos, &file->block, &file->off);
  2503. if (err) {
  2504. LFS_TRACE("lfs_file_read -> %d", err);
  2505. return err;
  2506. }
  2507. } else {
  2508. file->block = LFS_BLOCK_INLINE;
  2509. file->off = file->pos;
  2510. }
  2511. file->flags |= LFS_F_READING;
  2512. }
  2513. // read as much as we can in current block
  2514. lfs_size_t diff = lfs_min(nsize, lfs->cfg->block_size - file->off);
  2515. if (file->flags & LFS_F_INLINE) {
  2516. int err = lfs_dir_getread(lfs, &file->m,
  2517. NULL, &file->cache, lfs->cfg->block_size,
  2518. LFS_MKTAG(0xfff, 0x1ff, 0),
  2519. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, file->id, 0),
  2520. file->off, data, diff);
  2521. if (err) {
  2522. LFS_TRACE("lfs_file_read -> %d", err);
  2523. return err;
  2524. }
  2525. } else {
  2526. int err = lfs_bd_read(lfs,
  2527. NULL, &file->cache, lfs->cfg->block_size,
  2528. file->block, file->off, data, diff);
  2529. if (err) {
  2530. LFS_TRACE("lfs_file_read -> %d", err);
  2531. return err;
  2532. }
  2533. }
  2534. file->pos += diff;
  2535. file->off += diff;
  2536. data += diff;
  2537. nsize -= diff;
  2538. }
  2539. LFS_TRACE("lfs_file_read -> %"PRId32, size);
  2540. return size;
  2541. }
  2542. lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file,
  2543. const void *buffer, lfs_size_t size) {
  2544. LFS_TRACE("lfs_file_write(%p, %p, %p, %"PRIu32")",
  2545. (void*)lfs, (void*)file, buffer, size);
  2546. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2547. LFS_ASSERT((file->flags & 3) != LFS_O_RDONLY);
  2548. #ifdef LFS_READONLY
  2549. return LFS_ERR_NOSYS;
  2550. #else
  2551. const uint8_t *data = buffer;
  2552. lfs_size_t nsize = size;
  2553. if (file->flags & LFS_F_READING) {
  2554. // drop any reads
  2555. int err = lfs_file_flush(lfs, file);
  2556. if (err) {
  2557. LFS_TRACE("lfs_file_write -> %d", err);
  2558. return err;
  2559. }
  2560. }
  2561. if ((file->flags & LFS_O_APPEND) && file->pos < file->ctz.size) {
  2562. file->pos = file->ctz.size;
  2563. }
  2564. if (file->pos + size > lfs->file_max) {
  2565. // Larger than file limit?
  2566. LFS_TRACE("lfs_file_write -> %d", LFS_ERR_FBIG);
  2567. return LFS_ERR_FBIG;
  2568. }
  2569. if (!(file->flags & LFS_F_WRITING) && file->pos > file->ctz.size) {
  2570. // fill with zeros
  2571. lfs_off_t pos = file->pos;
  2572. file->pos = file->ctz.size;
  2573. while (file->pos < pos) {
  2574. lfs_ssize_t res = lfs_file_write(lfs, file, &(uint8_t){0}, 1);
  2575. if (res < 0) {
  2576. LFS_TRACE("lfs_file_write -> %"PRId32, res);
  2577. return res;
  2578. }
  2579. }
  2580. }
  2581. if ((file->flags & LFS_F_INLINE) &&
  2582. lfs_max(file->pos+nsize, file->ctz.size) >
  2583. lfs_min(0x3fe, lfs_min(
  2584. lfs->cfg->cache_size, lfs->cfg->block_size/8))) {
  2585. // inline file doesn't fit anymore
  2586. int err = lfs_file_outline(lfs, file);
  2587. if (err) {
  2588. file->flags |= LFS_F_ERRED;
  2589. LFS_TRACE("lfs_file_write -> %d", err);
  2590. return err;
  2591. }
  2592. }
  2593. while (nsize > 0) {
  2594. // check if we need a new block
  2595. if (!(file->flags & LFS_F_WRITING) ||
  2596. file->off == lfs->cfg->block_size) {
  2597. if (!(file->flags & LFS_F_INLINE)) {
  2598. if (!(file->flags & LFS_F_WRITING) && file->pos > 0) {
  2599. // find out which block we're extending from
  2600. int err = lfs_ctz_find(lfs, NULL, &file->cache,
  2601. file->ctz.head, file->ctz.size,
  2602. file->pos-1, &file->block, &file->off);
  2603. if (err) {
  2604. file->flags |= LFS_F_ERRED;
  2605. LFS_TRACE("lfs_file_write -> %d", err);
  2606. return err;
  2607. }
  2608. // mark cache as dirty since we may have read data into it
  2609. lfs_cache_zero(lfs, &file->cache);
  2610. }
  2611. // extend file with new blocks
  2612. lfs_alloc_ack(lfs);
  2613. int err = lfs_ctz_extend(lfs, &file->cache, &lfs->rcache,
  2614. file->block, file->pos,
  2615. &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. } else {
  2622. file->block = LFS_BLOCK_INLINE;
  2623. file->off = file->pos;
  2624. }
  2625. file->flags |= LFS_F_WRITING;
  2626. }
  2627. // program as much as we can in current block
  2628. lfs_size_t diff = lfs_min(nsize, lfs->cfg->block_size - file->off);
  2629. while (true) {
  2630. int err = lfs_bd_prog(lfs, &file->cache, &lfs->rcache, true,
  2631. file->block, file->off, data, diff);
  2632. if (err) {
  2633. if (err == LFS_ERR_CORRUPT) {
  2634. goto relocate;
  2635. }
  2636. file->flags |= LFS_F_ERRED;
  2637. LFS_TRACE("lfs_file_write -> %d", err);
  2638. return err;
  2639. }
  2640. break;
  2641. relocate:
  2642. err = lfs_file_relocate(lfs, file);
  2643. if (err) {
  2644. file->flags |= LFS_F_ERRED;
  2645. LFS_TRACE("lfs_file_write -> %d", err);
  2646. return err;
  2647. }
  2648. }
  2649. file->pos += diff;
  2650. file->off += diff;
  2651. data += diff;
  2652. nsize -= diff;
  2653. lfs_alloc_ack(lfs);
  2654. }
  2655. file->flags &= ~LFS_F_ERRED;
  2656. LFS_TRACE("lfs_file_write -> %"PRId32, size);
  2657. return size;
  2658. #endif
  2659. }
  2660. lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file,
  2661. lfs_soff_t off, int whence) {
  2662. LFS_TRACE("lfs_file_seek(%p, %p, %"PRId32", %d)",
  2663. (void*)lfs, (void*)file, off, whence);
  2664. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2665. // write out everything beforehand, may be noop if rdonly
  2666. int err = lfs_file_flush(lfs, file);
  2667. if (err) {
  2668. LFS_TRACE("lfs_file_seek -> %d", err);
  2669. return err;
  2670. }
  2671. // find new pos
  2672. lfs_off_t npos = file->pos;
  2673. if (whence == LFS_SEEK_SET) {
  2674. npos = off;
  2675. } else if (whence == LFS_SEEK_CUR) {
  2676. npos = file->pos + off;
  2677. } else if (whence == LFS_SEEK_END) {
  2678. npos = file->ctz.size + off;
  2679. }
  2680. if (npos > lfs->file_max) {
  2681. // file position out of range
  2682. LFS_TRACE("lfs_file_seek -> %d", LFS_ERR_INVAL);
  2683. return LFS_ERR_INVAL;
  2684. }
  2685. // update pos
  2686. file->pos = npos;
  2687. LFS_TRACE("lfs_file_seek -> %"PRId32, npos);
  2688. return npos;
  2689. }
  2690. int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size) {
  2691. LFS_TRACE("lfs_file_truncate(%p, %p, %"PRIu32")",
  2692. (void*)lfs, (void*)file, size);
  2693. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2694. LFS_ASSERT((file->flags & 3) != LFS_O_RDONLY);
  2695. if (size > LFS_FILE_MAX) {
  2696. LFS_TRACE("lfs_file_truncate -> %d", LFS_ERR_INVAL);
  2697. return LFS_ERR_INVAL;
  2698. }
  2699. #ifdef LFS_READONLY
  2700. return LFS_ERR_NOSYS;
  2701. #else
  2702. lfs_off_t pos = file->pos;
  2703. lfs_off_t oldsize = lfs_file_size(lfs, file);
  2704. if (size < oldsize) {
  2705. // need to flush since directly changing metadata
  2706. int err = lfs_file_flush(lfs, file);
  2707. if (err) {
  2708. LFS_TRACE("lfs_file_truncate -> %d", err);
  2709. return err;
  2710. }
  2711. // lookup new head in ctz skip list
  2712. err = lfs_ctz_find(lfs, NULL, &file->cache,
  2713. file->ctz.head, file->ctz.size,
  2714. size, &file->block, &file->off);
  2715. if (err) {
  2716. LFS_TRACE("lfs_file_truncate -> %d", err);
  2717. return err;
  2718. }
  2719. file->ctz.head = file->block;
  2720. file->ctz.size = size;
  2721. file->flags |= LFS_F_DIRTY | LFS_F_READING;
  2722. } else if (size > oldsize) {
  2723. // flush+seek if not already at end
  2724. if (file->pos != oldsize) {
  2725. lfs_soff_t res = lfs_file_seek(lfs, file, 0, LFS_SEEK_END);
  2726. if (res < 0) {
  2727. LFS_TRACE("lfs_file_truncate -> %"PRId32, res);
  2728. return (int)res;
  2729. }
  2730. }
  2731. // fill with zeros
  2732. while (file->pos < size) {
  2733. lfs_ssize_t res = lfs_file_write(lfs, file, &(uint8_t){0}, 1);
  2734. if (res < 0) {
  2735. LFS_TRACE("lfs_file_truncate -> %"PRId32, res);
  2736. return (int)res;
  2737. }
  2738. }
  2739. }
  2740. // restore pos
  2741. lfs_soff_t res = lfs_file_seek(lfs, file, pos, LFS_SEEK_SET);
  2742. if (res < 0) {
  2743. LFS_TRACE("lfs_file_truncate -> %"PRId32, res);
  2744. return (int)res;
  2745. }
  2746. LFS_TRACE("lfs_file_truncate -> %d", 0);
  2747. return 0;
  2748. #endif
  2749. }
  2750. lfs_soff_t lfs_file_tell(lfs_t *lfs, lfs_file_t *file) {
  2751. LFS_TRACE("lfs_file_tell(%p, %p)", (void*)lfs, (void*)file);
  2752. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2753. (void)lfs;
  2754. LFS_TRACE("lfs_file_tell -> %"PRId32, file->pos);
  2755. return file->pos;
  2756. }
  2757. int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file) {
  2758. LFS_TRACE("lfs_file_rewind(%p, %p)", (void*)lfs, (void*)file);
  2759. lfs_soff_t res = lfs_file_seek(lfs, file, 0, LFS_SEEK_SET);
  2760. if (res < 0) {
  2761. LFS_TRACE("lfs_file_rewind -> %"PRId32, res);
  2762. return (int)res;
  2763. }
  2764. LFS_TRACE("lfs_file_rewind -> %d", 0);
  2765. return 0;
  2766. }
  2767. lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file) {
  2768. LFS_TRACE("lfs_file_size(%p, %p)", (void*)lfs, (void*)file);
  2769. LFS_ASSERT(file->flags & LFS_F_OPENED);
  2770. (void)lfs;
  2771. #ifndef LFS_READONLY
  2772. if (file->flags & LFS_F_WRITING) {
  2773. LFS_TRACE("lfs_file_size -> %"PRId32,
  2774. lfs_max(file->pos, file->ctz.size));
  2775. return lfs_max(file->pos, file->ctz.size);
  2776. } else
  2777. #endif
  2778. {
  2779. LFS_TRACE("lfs_file_size -> %"PRId32, file->ctz.size);
  2780. return file->ctz.size;
  2781. }
  2782. }
  2783. /// General fs operations ///
  2784. int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info) {
  2785. LFS_TRACE("lfs_stat(%p, \"%s\", %p)", (void*)lfs, path, (void*)info);
  2786. lfs_mdir_t cwd;
  2787. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  2788. if (tag < 0) {
  2789. LFS_TRACE("lfs_stat -> %"PRId32, tag);
  2790. return (int)tag;
  2791. }
  2792. int err = lfs_dir_getinfo(lfs, &cwd, lfs_tag_id(tag), info);
  2793. LFS_TRACE("lfs_stat -> %d", err);
  2794. return err;
  2795. }
  2796. int lfs_remove(lfs_t *lfs, const char *path) {
  2797. LFS_TRACE("lfs_remove(%p, \"%s\")", (void*)lfs, path);
  2798. #ifdef LFS_READONLY
  2799. return LFS_ERR_NOSYS;
  2800. #else
  2801. // deorphan if we haven't yet, needed at most once after poweron
  2802. int err = lfs_fs_forceconsistency(lfs);
  2803. if (err) {
  2804. LFS_TRACE("lfs_remove -> %d", err);
  2805. return err;
  2806. }
  2807. lfs_mdir_t cwd;
  2808. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  2809. if (tag < 0 || lfs_tag_id(tag) == 0x3ff) {
  2810. LFS_TRACE("lfs_remove -> %"PRId32, (tag < 0) ? tag : LFS_ERR_INVAL);
  2811. return (tag < 0) ? (int)tag : LFS_ERR_INVAL;
  2812. }
  2813. struct lfs_mlist dir;
  2814. dir.next = lfs->mlist;
  2815. if (lfs_tag_type3(tag) == LFS_TYPE_DIR) {
  2816. // must be empty before removal
  2817. lfs_block_t pair[2];
  2818. lfs_stag_t res = lfs_dir_get(lfs, &cwd, LFS_MKTAG(0x700, 0x3ff, 0),
  2819. LFS_MKTAG(LFS_TYPE_STRUCT, lfs_tag_id(tag), 8), pair);
  2820. if (res < 0) {
  2821. LFS_TRACE("lfs_remove -> %"PRId32, res);
  2822. return (int)res;
  2823. }
  2824. lfs_pair_fromle32(pair);
  2825. err = lfs_dir_fetch(lfs, &dir.m, pair);
  2826. if (err) {
  2827. LFS_TRACE("lfs_remove -> %d", err);
  2828. return err;
  2829. }
  2830. if (dir.m.count > 0 || dir.m.split) {
  2831. LFS_TRACE("lfs_remove -> %d", LFS_ERR_NOTEMPTY);
  2832. return LFS_ERR_NOTEMPTY;
  2833. }
  2834. // mark fs as orphaned
  2835. lfs_fs_preporphans(lfs, +1);
  2836. // I know it's crazy but yes, dir can be changed by our parent's
  2837. // commit (if predecessor is child)
  2838. dir.type = 0;
  2839. dir.id = 0;
  2840. lfs->mlist = &dir;
  2841. }
  2842. // delete the entry
  2843. err = lfs_dir_commit(lfs, &cwd, LFS_MKATTRS(
  2844. {LFS_MKTAG(LFS_TYPE_DELETE, lfs_tag_id(tag), 0), NULL}));
  2845. if (err) {
  2846. lfs->mlist = dir.next;
  2847. LFS_TRACE("lfs_remove -> %d", err);
  2848. return err;
  2849. }
  2850. lfs->mlist = dir.next;
  2851. if (lfs_tag_type3(tag) == LFS_TYPE_DIR) {
  2852. // fix orphan
  2853. lfs_fs_preporphans(lfs, -1);
  2854. err = lfs_fs_pred(lfs, dir.m.pair, &cwd);
  2855. if (err) {
  2856. LFS_TRACE("lfs_remove -> %d", err);
  2857. return err;
  2858. }
  2859. err = lfs_dir_drop(lfs, &cwd, &dir.m);
  2860. if (err) {
  2861. LFS_TRACE("lfs_remove -> %d", err);
  2862. return err;
  2863. }
  2864. }
  2865. LFS_TRACE("lfs_remove -> %d", 0);
  2866. return 0;
  2867. #endif
  2868. }
  2869. int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath) {
  2870. LFS_TRACE("lfs_rename(%p, \"%s\", \"%s\")", (void*)lfs, oldpath, newpath);
  2871. #ifdef LFS_READONLY
  2872. return LFS_ERR_NOSYS;
  2873. #else
  2874. // deorphan if we haven't yet, needed at most once after poweron
  2875. int err = lfs_fs_forceconsistency(lfs);
  2876. if (err) {
  2877. LFS_TRACE("lfs_rename -> %d", err);
  2878. return err;
  2879. }
  2880. // find old entry
  2881. lfs_mdir_t oldcwd;
  2882. lfs_stag_t oldtag = lfs_dir_find(lfs, &oldcwd, &oldpath, NULL);
  2883. if (oldtag < 0 || lfs_tag_id(oldtag) == 0x3ff) {
  2884. LFS_TRACE("lfs_rename -> %"PRId32,
  2885. (oldtag < 0) ? oldtag : LFS_ERR_INVAL);
  2886. return (oldtag < 0) ? (int)oldtag : LFS_ERR_INVAL;
  2887. }
  2888. // find new entry
  2889. lfs_mdir_t newcwd;
  2890. uint16_t newid;
  2891. lfs_stag_t prevtag = lfs_dir_find(lfs, &newcwd, &newpath, &newid);
  2892. if ((prevtag < 0 || lfs_tag_id(prevtag) == 0x3ff) &&
  2893. !(prevtag == LFS_ERR_NOENT && newid != 0x3ff)) {
  2894. LFS_TRACE("lfs_rename -> %"PRId32,
  2895. (prevtag < 0) ? prevtag : LFS_ERR_INVAL);
  2896. return (prevtag < 0) ? (int)prevtag : LFS_ERR_INVAL;
  2897. }
  2898. // if we're in the same pair there's a few special cases...
  2899. bool samepair = (lfs_pair_cmp(oldcwd.pair, newcwd.pair) == 0);
  2900. uint16_t newoldid = lfs_tag_id(oldtag);
  2901. struct lfs_mlist prevdir;
  2902. prevdir.next = lfs->mlist;
  2903. if (prevtag == LFS_ERR_NOENT) {
  2904. // check that name fits
  2905. lfs_size_t nlen = strlen(newpath);
  2906. if (nlen > lfs->name_max) {
  2907. LFS_TRACE("lfs_rename -> %d", LFS_ERR_NAMETOOLONG);
  2908. return LFS_ERR_NAMETOOLONG;
  2909. }
  2910. // there is a small chance we are being renamed in the same
  2911. // directory/ to an id less than our old id, the global update
  2912. // to handle this is a bit messy
  2913. if (samepair && newid <= newoldid) {
  2914. newoldid += 1;
  2915. }
  2916. } else if (lfs_tag_type3(prevtag) != lfs_tag_type3(oldtag)) {
  2917. LFS_TRACE("lfs_rename -> %d", LFS_ERR_ISDIR);
  2918. return LFS_ERR_ISDIR;
  2919. } else if (samepair && newid == newoldid) {
  2920. // we're renaming to ourselves??
  2921. LFS_TRACE("lfs_rename -> %d", 0);
  2922. return 0;
  2923. } else if (lfs_tag_type3(prevtag) == LFS_TYPE_DIR) {
  2924. // must be empty before removal
  2925. lfs_block_t prevpair[2];
  2926. lfs_stag_t res = lfs_dir_get(lfs, &newcwd, LFS_MKTAG(0x700, 0x3ff, 0),
  2927. LFS_MKTAG(LFS_TYPE_STRUCT, newid, 8), prevpair);
  2928. if (res < 0) {
  2929. LFS_TRACE("lfs_rename -> %"PRId32, res);
  2930. return (int)res;
  2931. }
  2932. lfs_pair_fromle32(prevpair);
  2933. // must be empty before removal
  2934. err = lfs_dir_fetch(lfs, &prevdir.m, prevpair);
  2935. if (err) {
  2936. LFS_TRACE("lfs_rename -> %d", err);
  2937. return err;
  2938. }
  2939. if (prevdir.m.count > 0 || prevdir.m.split) {
  2940. LFS_TRACE("lfs_rename -> %d", LFS_ERR_NOTEMPTY);
  2941. return LFS_ERR_NOTEMPTY;
  2942. }
  2943. // mark fs as orphaned
  2944. lfs_fs_preporphans(lfs, +1);
  2945. // I know it's crazy but yes, dir can be changed by our parent's
  2946. // commit (if predecessor is child)
  2947. prevdir.type = 0;
  2948. prevdir.id = 0;
  2949. lfs->mlist = &prevdir;
  2950. }
  2951. if (!samepair) {
  2952. lfs_fs_prepmove(lfs, newoldid, oldcwd.pair);
  2953. }
  2954. // move over all attributes
  2955. err = lfs_dir_commit(lfs, &newcwd, LFS_MKATTRS(
  2956. {LFS_MKTAG_IF(prevtag != LFS_ERR_NOENT,
  2957. LFS_TYPE_DELETE, newid, 0), NULL},
  2958. {LFS_MKTAG(LFS_TYPE_CREATE, newid, 0), NULL},
  2959. {LFS_MKTAG(lfs_tag_type3(oldtag), newid, strlen(newpath)), newpath},
  2960. {LFS_MKTAG(LFS_FROM_MOVE, newid, lfs_tag_id(oldtag)), &oldcwd},
  2961. {LFS_MKTAG_IF(samepair,
  2962. LFS_TYPE_DELETE, newoldid, 0), NULL}));
  2963. if (err) {
  2964. lfs->mlist = prevdir.next;
  2965. LFS_TRACE("lfs_rename -> %d", err);
  2966. return err;
  2967. }
  2968. // let commit clean up after move (if we're different! otherwise move
  2969. // logic already fixed it for us)
  2970. if (!samepair && lfs_gstate_hasmove(&lfs->gstate)) {
  2971. // prep gstate and delete move id
  2972. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  2973. err = lfs_dir_commit(lfs, &oldcwd, LFS_MKATTRS(
  2974. {LFS_MKTAG(LFS_TYPE_DELETE, lfs_tag_id(oldtag), 0), NULL}));
  2975. if (err) {
  2976. lfs->mlist = prevdir.next;
  2977. LFS_TRACE("lfs_rename -> %d", err);
  2978. return err;
  2979. }
  2980. }
  2981. lfs->mlist = prevdir.next;
  2982. if (prevtag != LFS_ERR_NOENT && lfs_tag_type3(prevtag) == LFS_TYPE_DIR) {
  2983. // fix orphan
  2984. lfs_fs_preporphans(lfs, -1);
  2985. err = lfs_fs_pred(lfs, prevdir.m.pair, &newcwd);
  2986. if (err) {
  2987. LFS_TRACE("lfs_rename -> %d", err);
  2988. return err;
  2989. }
  2990. err = lfs_dir_drop(lfs, &newcwd, &prevdir.m);
  2991. if (err) {
  2992. LFS_TRACE("lfs_rename -> %d", err);
  2993. return err;
  2994. }
  2995. }
  2996. LFS_TRACE("lfs_rename -> %d", 0);
  2997. return 0;
  2998. #endif
  2999. }
  3000. lfs_ssize_t lfs_getattr(lfs_t *lfs, const char *path,
  3001. uint8_t type, void *buffer, lfs_size_t size) {
  3002. LFS_TRACE("lfs_getattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
  3003. (void*)lfs, path, type, buffer, size);
  3004. lfs_mdir_t cwd;
  3005. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  3006. if (tag < 0) {
  3007. LFS_TRACE("lfs_getattr -> %"PRId32, tag);
  3008. return tag;
  3009. }
  3010. uint16_t id = lfs_tag_id(tag);
  3011. if (id == 0x3ff) {
  3012. // special case for root
  3013. id = 0;
  3014. int err = lfs_dir_fetch(lfs, &cwd, lfs->root);
  3015. if (err) {
  3016. LFS_TRACE("lfs_getattr -> %d", err);
  3017. return err;
  3018. }
  3019. }
  3020. tag = lfs_dir_get(lfs, &cwd, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3021. LFS_MKTAG(LFS_TYPE_USERATTR + type,
  3022. id, lfs_min(size, lfs->attr_max)),
  3023. buffer);
  3024. if (tag < 0) {
  3025. if (tag == LFS_ERR_NOENT) {
  3026. LFS_TRACE("lfs_getattr -> %d", LFS_ERR_NOATTR);
  3027. return LFS_ERR_NOATTR;
  3028. }
  3029. LFS_TRACE("lfs_getattr -> %"PRId32, tag);
  3030. return tag;
  3031. }
  3032. size = lfs_tag_size(tag);
  3033. LFS_TRACE("lfs_getattr -> %"PRId32, size);
  3034. return size;
  3035. }
  3036. #ifndef LFS_READONLY
  3037. static int lfs_commitattr(lfs_t *lfs, const char *path,
  3038. uint8_t type, const void *buffer, lfs_size_t size) {
  3039. lfs_mdir_t cwd;
  3040. lfs_stag_t tag = lfs_dir_find(lfs, &cwd, &path, NULL);
  3041. if (tag < 0) {
  3042. return tag;
  3043. }
  3044. uint16_t id = lfs_tag_id(tag);
  3045. if (id == 0x3ff) {
  3046. // special case for root
  3047. id = 0;
  3048. int err = lfs_dir_fetch(lfs, &cwd, lfs->root);
  3049. if (err) {
  3050. return err;
  3051. }
  3052. }
  3053. return lfs_dir_commit(lfs, &cwd, LFS_MKATTRS(
  3054. {LFS_MKTAG(LFS_TYPE_USERATTR + type, id, size), buffer}));
  3055. }
  3056. #endif
  3057. int lfs_setattr(lfs_t *lfs, const char *path,
  3058. uint8_t type, const void *buffer, lfs_size_t size) {
  3059. LFS_TRACE("lfs_setattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")",
  3060. (void*)lfs, path, type, buffer, size);
  3061. #ifdef LFS_READONLY
  3062. return LFS_ERR_NOSYS;
  3063. #else
  3064. if (size > lfs->attr_max) {
  3065. LFS_TRACE("lfs_setattr -> %d", LFS_ERR_NOSPC);
  3066. return LFS_ERR_NOSPC;
  3067. }
  3068. int err = lfs_commitattr(lfs, path, type, buffer, size);
  3069. LFS_TRACE("lfs_setattr -> %d", err);
  3070. return err;
  3071. #endif
  3072. }
  3073. int lfs_removeattr(lfs_t *lfs, const char *path, uint8_t type) {
  3074. LFS_TRACE("lfs_removeattr(%p, \"%s\", %"PRIu8")", (void*)lfs, path, type);
  3075. #ifdef LFS_READONLY
  3076. return LFS_ERR_NOSYS;
  3077. #else
  3078. int err = lfs_commitattr(lfs, path, type, NULL, 0x3ff);
  3079. LFS_TRACE("lfs_removeattr -> %d", err);
  3080. return err;
  3081. #endif
  3082. }
  3083. /// Filesystem operations ///
  3084. static int lfs_init(lfs_t *lfs, const struct lfs_config *cfg) {
  3085. lfs->cfg = cfg;
  3086. int err = 0;
  3087. // validate that the lfs-cfg sizes were initiated properly before
  3088. // performing any arithmetic logics with them
  3089. LFS_ASSERT(lfs->cfg->read_size != 0);
  3090. LFS_ASSERT(lfs->cfg->prog_size != 0);
  3091. LFS_ASSERT(lfs->cfg->cache_size != 0);
  3092. // check that block size is a multiple of cache size is a multiple
  3093. // of prog and read sizes
  3094. LFS_ASSERT(lfs->cfg->cache_size % lfs->cfg->read_size == 0);
  3095. LFS_ASSERT(lfs->cfg->cache_size % lfs->cfg->prog_size == 0);
  3096. LFS_ASSERT(lfs->cfg->block_size % lfs->cfg->cache_size == 0);
  3097. // check that the block size is large enough to fit ctz pointers
  3098. LFS_ASSERT(4*lfs_npw2(0xffffffff / (lfs->cfg->block_size-2*4))
  3099. <= lfs->cfg->block_size);
  3100. // block_cycles = 0 is no longer supported.
  3101. //
  3102. // block_cycles is the number of erase cycles before littlefs evicts
  3103. // metadata logs as a part of wear leveling. Suggested values are in the
  3104. // range of 100-1000, or set block_cycles to -1 to disable block-level
  3105. // wear-leveling.
  3106. LFS_ASSERT(lfs->cfg->block_cycles != 0);
  3107. // setup read cache
  3108. if (lfs->cfg->read_buffer) {
  3109. lfs->rcache.buffer = lfs->cfg->read_buffer;
  3110. } else {
  3111. lfs->rcache.buffer = lfs_malloc(lfs->cfg->cache_size);
  3112. if (!lfs->rcache.buffer) {
  3113. err = LFS_ERR_NOMEM;
  3114. goto cleanup;
  3115. }
  3116. }
  3117. // setup program cache
  3118. if (lfs->cfg->prog_buffer) {
  3119. lfs->pcache.buffer = lfs->cfg->prog_buffer;
  3120. } else {
  3121. lfs->pcache.buffer = lfs_malloc(lfs->cfg->cache_size);
  3122. if (!lfs->pcache.buffer) {
  3123. err = LFS_ERR_NOMEM;
  3124. goto cleanup;
  3125. }
  3126. }
  3127. // zero to avoid information leaks
  3128. lfs_cache_zero(lfs, &lfs->rcache);
  3129. lfs_cache_zero(lfs, &lfs->pcache);
  3130. // setup lookahead, must be multiple of 64-bits, 32-bit aligned
  3131. LFS_ASSERT(lfs->cfg->lookahead_size > 0);
  3132. LFS_ASSERT(lfs->cfg->lookahead_size % 8 == 0 &&
  3133. (uintptr_t)lfs->cfg->lookahead_buffer % 4 == 0);
  3134. if (lfs->cfg->lookahead_buffer) {
  3135. lfs->free.buffer = lfs->cfg->lookahead_buffer;
  3136. } else {
  3137. lfs->free.buffer = lfs_malloc(lfs->cfg->lookahead_size);
  3138. if (!lfs->free.buffer) {
  3139. err = LFS_ERR_NOMEM;
  3140. goto cleanup;
  3141. }
  3142. }
  3143. // check that the size limits are sane
  3144. LFS_ASSERT(lfs->cfg->name_max <= LFS_NAME_MAX);
  3145. lfs->name_max = lfs->cfg->name_max;
  3146. if (!lfs->name_max) {
  3147. lfs->name_max = LFS_NAME_MAX;
  3148. }
  3149. LFS_ASSERT(lfs->cfg->file_max <= LFS_FILE_MAX);
  3150. lfs->file_max = lfs->cfg->file_max;
  3151. if (!lfs->file_max) {
  3152. lfs->file_max = LFS_FILE_MAX;
  3153. }
  3154. LFS_ASSERT(lfs->cfg->attr_max <= LFS_ATTR_MAX);
  3155. lfs->attr_max = lfs->cfg->attr_max;
  3156. if (!lfs->attr_max) {
  3157. lfs->attr_max = LFS_ATTR_MAX;
  3158. }
  3159. // setup default state
  3160. lfs->root[0] = LFS_BLOCK_NULL;
  3161. lfs->root[1] = LFS_BLOCK_NULL;
  3162. lfs->mlist = NULL;
  3163. lfs->seed = 0;
  3164. lfs->gdisk = (lfs_gstate_t){0};
  3165. lfs->gstate = (lfs_gstate_t){0};
  3166. lfs->gdelta = (lfs_gstate_t){0};
  3167. #ifdef LFS_MIGRATE
  3168. lfs->lfs1 = NULL;
  3169. #endif
  3170. return 0;
  3171. cleanup:
  3172. lfs_deinit(lfs);
  3173. return err;
  3174. }
  3175. static int lfs_deinit(lfs_t *lfs) {
  3176. // free allocated memory
  3177. if (!lfs->cfg->read_buffer) {
  3178. lfs_free(lfs->rcache.buffer);
  3179. }
  3180. if (!lfs->cfg->prog_buffer) {
  3181. lfs_free(lfs->pcache.buffer);
  3182. }
  3183. if (!lfs->cfg->lookahead_buffer) {
  3184. lfs_free(lfs->free.buffer);
  3185. }
  3186. return 0;
  3187. }
  3188. int lfs_format(lfs_t *lfs, const struct lfs_config *cfg) {
  3189. LFS_TRACE("lfs_format(%p, %p {.context=%p, "
  3190. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  3191. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  3192. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  3193. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  3194. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  3195. ".prog_buffer=%p, .lookahead_buffer=%p, "
  3196. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  3197. ".attr_max=%"PRIu32"})",
  3198. (void*)lfs, (void*)cfg, cfg->context,
  3199. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  3200. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  3201. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  3202. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  3203. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  3204. cfg->name_max, cfg->file_max, cfg->attr_max);
  3205. #ifdef LFS_READONLY
  3206. return LFS_ERR_NOSYS;
  3207. #else
  3208. int err = 0;
  3209. {
  3210. err = lfs_init(lfs, cfg);
  3211. if (err) {
  3212. LFS_TRACE("lfs_format -> %d", err);
  3213. return err;
  3214. }
  3215. // create free lookahead
  3216. memset(lfs->free.buffer, 0, lfs->cfg->lookahead_size);
  3217. lfs->free.off = 0;
  3218. lfs->free.size = lfs_min(8*lfs->cfg->lookahead_size,
  3219. lfs->cfg->block_count);
  3220. lfs->free.i = 0;
  3221. lfs_alloc_ack(lfs);
  3222. // create root dir
  3223. lfs_mdir_t root;
  3224. err = lfs_dir_alloc(lfs, &root);
  3225. if (err) {
  3226. goto cleanup;
  3227. }
  3228. // write one superblock
  3229. lfs_superblock_t superblock = {
  3230. .version = LFS_DISK_VERSION,
  3231. .block_size = lfs->cfg->block_size,
  3232. .block_count = lfs->cfg->block_count,
  3233. .name_max = lfs->name_max,
  3234. .file_max = lfs->file_max,
  3235. .attr_max = lfs->attr_max,
  3236. };
  3237. lfs_superblock_tole32(&superblock);
  3238. err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
  3239. {LFS_MKTAG(LFS_TYPE_CREATE, 0, 0), NULL},
  3240. {LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
  3241. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3242. &superblock}));
  3243. if (err) {
  3244. goto cleanup;
  3245. }
  3246. // sanity check that fetch works
  3247. err = lfs_dir_fetch(lfs, &root, (const lfs_block_t[2]){0, 1});
  3248. if (err) {
  3249. goto cleanup;
  3250. }
  3251. // force compaction to prevent accidentally mounting any
  3252. // older version of littlefs that may live on disk
  3253. root.erased = false;
  3254. err = lfs_dir_commit(lfs, &root, NULL, 0);
  3255. if (err) {
  3256. goto cleanup;
  3257. }
  3258. }
  3259. cleanup:
  3260. lfs_deinit(lfs);
  3261. LFS_TRACE("lfs_format -> %d", err);
  3262. return err;
  3263. #endif
  3264. }
  3265. int lfs_mount(lfs_t *lfs, const struct lfs_config *cfg) {
  3266. LFS_TRACE("lfs_mount(%p, %p {.context=%p, "
  3267. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  3268. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  3269. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  3270. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  3271. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  3272. ".prog_buffer=%p, .lookahead_buffer=%p, "
  3273. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  3274. ".attr_max=%"PRIu32"})",
  3275. (void*)lfs, (void*)cfg, cfg->context,
  3276. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  3277. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  3278. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  3279. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  3280. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  3281. cfg->name_max, cfg->file_max, cfg->attr_max);
  3282. int err = lfs_init(lfs, cfg);
  3283. if (err) {
  3284. LFS_TRACE("lfs_mount -> %d", err);
  3285. return err;
  3286. }
  3287. // scan directory blocks for superblock and any global updates
  3288. lfs_mdir_t dir = {.tail = {0, 1}};
  3289. lfs_block_t cycle = 0;
  3290. while (!lfs_pair_isnull(dir.tail)) {
  3291. if (cycle >= lfs->cfg->block_count/2) {
  3292. // loop detected
  3293. err = LFS_ERR_CORRUPT;
  3294. goto cleanup;
  3295. }
  3296. cycle += 1;
  3297. // fetch next block in tail list
  3298. lfs_stag_t tag = lfs_dir_fetchmatch(lfs, &dir, dir.tail,
  3299. LFS_MKTAG(0x7ff, 0x3ff, 0),
  3300. LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8),
  3301. NULL,
  3302. lfs_dir_find_match, &(struct lfs_dir_find_match){
  3303. lfs, "littlefs", 8});
  3304. if (tag < 0) {
  3305. err = tag;
  3306. goto cleanup;
  3307. }
  3308. // has superblock?
  3309. if (tag && !lfs_tag_isdelete(tag)) {
  3310. // update root
  3311. lfs->root[0] = dir.pair[0];
  3312. lfs->root[1] = dir.pair[1];
  3313. // grab superblock
  3314. lfs_superblock_t superblock;
  3315. tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x7ff, 0x3ff, 0),
  3316. LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  3317. &superblock);
  3318. if (tag < 0) {
  3319. err = tag;
  3320. goto cleanup;
  3321. }
  3322. lfs_superblock_fromle32(&superblock);
  3323. // check version
  3324. uint16_t major_version = (0xffff & (superblock.version >> 16));
  3325. uint16_t minor_version = (0xffff & (superblock.version >> 0));
  3326. if ((major_version != LFS_DISK_VERSION_MAJOR ||
  3327. minor_version > LFS_DISK_VERSION_MINOR)) {
  3328. LFS_ERROR("Invalid version v%"PRIu16".%"PRIu16,
  3329. major_version, minor_version);
  3330. err = LFS_ERR_INVAL;
  3331. goto cleanup;
  3332. }
  3333. // check superblock configuration
  3334. if (superblock.name_max) {
  3335. if (superblock.name_max > lfs->name_max) {
  3336. LFS_ERROR("Unsupported name_max (%"PRIu32" > %"PRIu32")",
  3337. superblock.name_max, lfs->name_max);
  3338. err = LFS_ERR_INVAL;
  3339. goto cleanup;
  3340. }
  3341. lfs->name_max = superblock.name_max;
  3342. }
  3343. if (superblock.file_max) {
  3344. if (superblock.file_max > lfs->file_max) {
  3345. LFS_ERROR("Unsupported file_max (%"PRIu32" > %"PRIu32")",
  3346. superblock.file_max, lfs->file_max);
  3347. err = LFS_ERR_INVAL;
  3348. goto cleanup;
  3349. }
  3350. lfs->file_max = superblock.file_max;
  3351. }
  3352. if (superblock.attr_max) {
  3353. if (superblock.attr_max > lfs->attr_max) {
  3354. LFS_ERROR("Unsupported attr_max (%"PRIu32" > %"PRIu32")",
  3355. superblock.attr_max, lfs->attr_max);
  3356. err = LFS_ERR_INVAL;
  3357. goto cleanup;
  3358. }
  3359. lfs->attr_max = superblock.attr_max;
  3360. }
  3361. }
  3362. // has gstate?
  3363. err = lfs_dir_getgstate(lfs, &dir, &lfs->gstate);
  3364. if (err) {
  3365. goto cleanup;
  3366. }
  3367. }
  3368. // found superblock?
  3369. if (lfs_pair_isnull(lfs->root)) {
  3370. err = LFS_ERR_INVAL;
  3371. goto cleanup;
  3372. }
  3373. // update littlefs with gstate
  3374. if (!lfs_gstate_iszero(&lfs->gstate)) {
  3375. LFS_DEBUG("Found pending gstate 0x%08"PRIx32"%08"PRIx32"%08"PRIx32,
  3376. lfs->gstate.tag,
  3377. lfs->gstate.pair[0],
  3378. lfs->gstate.pair[1]);
  3379. }
  3380. lfs->gstate.tag += !lfs_tag_isvalid(lfs->gstate.tag);
  3381. lfs->gdisk = lfs->gstate;
  3382. // setup free lookahead
  3383. lfs_alloc_reset(lfs);
  3384. LFS_TRACE("lfs_mount -> %d", 0);
  3385. return 0;
  3386. cleanup:
  3387. lfs_unmount(lfs);
  3388. LFS_TRACE("lfs_mount -> %d", err);
  3389. return err;
  3390. }
  3391. int lfs_unmount(lfs_t *lfs) {
  3392. LFS_TRACE("lfs_unmount(%p)", (void*)lfs);
  3393. int err = lfs_deinit(lfs);
  3394. LFS_TRACE("lfs_unmount -> %d", err);
  3395. return err;
  3396. }
  3397. /// Filesystem filesystem operations ///
  3398. int lfs_fs_traverseraw(lfs_t *lfs,
  3399. int (*cb)(void *data, lfs_block_t block), void *data,
  3400. bool includeorphans) {
  3401. // iterate over metadata pairs
  3402. lfs_mdir_t dir = {.tail = {0, 1}};
  3403. #ifdef LFS_MIGRATE
  3404. // also consider v1 blocks during migration
  3405. if (lfs->lfs1) {
  3406. int err = lfs1_traverse(lfs, cb, data);
  3407. if (err) {
  3408. return err;
  3409. }
  3410. dir.tail[0] = lfs->root[0];
  3411. dir.tail[1] = lfs->root[1];
  3412. }
  3413. #endif
  3414. lfs_block_t cycle = 0;
  3415. while (!lfs_pair_isnull(dir.tail)) {
  3416. if (cycle >= lfs->cfg->block_count/2) {
  3417. // loop detected
  3418. return LFS_ERR_CORRUPT;
  3419. }
  3420. cycle += 1;
  3421. for (int i = 0; i < 2; i++) {
  3422. int err = cb(data, dir.tail[i]);
  3423. if (err) {
  3424. return err;
  3425. }
  3426. }
  3427. // iterate through ids in directory
  3428. int err = lfs_dir_fetch(lfs, &dir, dir.tail);
  3429. if (err) {
  3430. return err;
  3431. }
  3432. for (uint16_t id = 0; id < dir.count; id++) {
  3433. struct lfs_ctz ctz;
  3434. lfs_stag_t tag = lfs_dir_get(lfs, &dir, LFS_MKTAG(0x700, 0x3ff, 0),
  3435. LFS_MKTAG(LFS_TYPE_STRUCT, id, sizeof(ctz)), &ctz);
  3436. if (tag < 0) {
  3437. if (tag == LFS_ERR_NOENT) {
  3438. continue;
  3439. }
  3440. return tag;
  3441. }
  3442. lfs_ctz_fromle32(&ctz);
  3443. if (lfs_tag_type3(tag) == LFS_TYPE_CTZSTRUCT) {
  3444. err = lfs_ctz_traverse(lfs, NULL, &lfs->rcache,
  3445. ctz.head, ctz.size, cb, data);
  3446. if (err) {
  3447. return err;
  3448. }
  3449. } else if (includeorphans &&
  3450. lfs_tag_type3(tag) == LFS_TYPE_DIRSTRUCT) {
  3451. for (int i = 0; i < 2; i++) {
  3452. err = cb(data, (&ctz.head)[i]);
  3453. if (err) {
  3454. return err;
  3455. }
  3456. }
  3457. }
  3458. }
  3459. }
  3460. // iterate over any open files
  3461. for (lfs_file_t *f = (lfs_file_t*)lfs->mlist; f; f = f->next) {
  3462. if (f->type != LFS_TYPE_REG) {
  3463. continue;
  3464. }
  3465. if ((f->flags & LFS_F_DIRTY) && !(f->flags & LFS_F_INLINE)) {
  3466. int err = lfs_ctz_traverse(lfs, &f->cache, &lfs->rcache,
  3467. f->ctz.head, f->ctz.size, cb, data);
  3468. if (err) {
  3469. return err;
  3470. }
  3471. }
  3472. #ifndef LFS_READONLY
  3473. if ((f->flags & LFS_F_WRITING) && !(f->flags & LFS_F_INLINE)) {
  3474. int err = lfs_ctz_traverse(lfs, &f->cache, &lfs->rcache,
  3475. f->block, f->pos, cb, data);
  3476. if (err) {
  3477. return err;
  3478. }
  3479. }
  3480. #endif
  3481. }
  3482. return 0;
  3483. }
  3484. int lfs_fs_traverse(lfs_t *lfs,
  3485. int (*cb)(void *data, lfs_block_t block), void *data) {
  3486. LFS_TRACE("lfs_fs_traverse(%p, %p, %p)",
  3487. (void*)lfs, (void*)(uintptr_t)cb, data);
  3488. int err = lfs_fs_traverseraw(lfs, cb, data, true);
  3489. LFS_TRACE("lfs_fs_traverse -> %d", 0);
  3490. return err;
  3491. }
  3492. #ifndef LFS_READONLY
  3493. static int lfs_fs_pred(lfs_t *lfs,
  3494. const lfs_block_t pair[2], lfs_mdir_t *pdir) {
  3495. // iterate over all directory directory entries
  3496. pdir->tail[0] = 0;
  3497. pdir->tail[1] = 1;
  3498. lfs_block_t cycle = 0;
  3499. while (!lfs_pair_isnull(pdir->tail)) {
  3500. if (cycle >= lfs->cfg->block_count/2) {
  3501. // loop detected
  3502. return LFS_ERR_CORRUPT;
  3503. }
  3504. cycle += 1;
  3505. if (lfs_pair_cmp(pdir->tail, pair) == 0) {
  3506. return 0;
  3507. }
  3508. int err = lfs_dir_fetch(lfs, pdir, pdir->tail);
  3509. if (err) {
  3510. return err;
  3511. }
  3512. }
  3513. return LFS_ERR_NOENT;
  3514. }
  3515. #endif
  3516. #ifndef LFS_READONLY
  3517. struct lfs_fs_parent_match {
  3518. lfs_t *lfs;
  3519. const lfs_block_t pair[2];
  3520. };
  3521. #endif
  3522. #ifndef LFS_READONLY
  3523. static int lfs_fs_parent_match(void *data,
  3524. lfs_tag_t tag, const void *buffer) {
  3525. struct lfs_fs_parent_match *find = data;
  3526. lfs_t *lfs = find->lfs;
  3527. const struct lfs_diskoff *disk = buffer;
  3528. (void)tag;
  3529. lfs_block_t child[2];
  3530. int err = lfs_bd_read(lfs,
  3531. &lfs->pcache, &lfs->rcache, lfs->cfg->block_size,
  3532. disk->block, disk->off, &child, sizeof(child));
  3533. if (err) {
  3534. return err;
  3535. }
  3536. lfs_pair_fromle32(child);
  3537. return (lfs_pair_cmp(child, find->pair) == 0) ? LFS_CMP_EQ : LFS_CMP_LT;
  3538. }
  3539. #endif
  3540. #ifndef LFS_READONLY
  3541. static lfs_stag_t lfs_fs_parent(lfs_t *lfs, const lfs_block_t pair[2],
  3542. lfs_mdir_t *parent) {
  3543. // use fetchmatch with callback to find pairs
  3544. parent->tail[0] = 0;
  3545. parent->tail[1] = 1;
  3546. lfs_block_t cycle = 0;
  3547. while (!lfs_pair_isnull(parent->tail)) {
  3548. if (cycle >= lfs->cfg->block_count/2) {
  3549. // loop detected
  3550. return LFS_ERR_CORRUPT;
  3551. }
  3552. cycle += 1;
  3553. lfs_stag_t tag = lfs_dir_fetchmatch(lfs, parent, parent->tail,
  3554. LFS_MKTAG(0x7ff, 0, 0x3ff),
  3555. LFS_MKTAG(LFS_TYPE_DIRSTRUCT, 0, 8),
  3556. NULL,
  3557. lfs_fs_parent_match, &(struct lfs_fs_parent_match){
  3558. lfs, {pair[0], pair[1]}});
  3559. if (tag && tag != LFS_ERR_NOENT) {
  3560. return tag;
  3561. }
  3562. }
  3563. return LFS_ERR_NOENT;
  3564. }
  3565. #endif
  3566. #ifndef LFS_READONLY
  3567. static int lfs_fs_relocate(lfs_t *lfs,
  3568. const lfs_block_t oldpair[2], lfs_block_t newpair[2]) {
  3569. // update internal root
  3570. if (lfs_pair_cmp(oldpair, lfs->root) == 0) {
  3571. lfs->root[0] = newpair[0];
  3572. lfs->root[1] = newpair[1];
  3573. }
  3574. // update internally tracked dirs
  3575. for (struct lfs_mlist *d = lfs->mlist; d; d = d->next) {
  3576. if (lfs_pair_cmp(oldpair, d->m.pair) == 0) {
  3577. d->m.pair[0] = newpair[0];
  3578. d->m.pair[1] = newpair[1];
  3579. }
  3580. if (d->type == LFS_TYPE_DIR &&
  3581. lfs_pair_cmp(oldpair, ((lfs_dir_t*)d)->head) == 0) {
  3582. ((lfs_dir_t*)d)->head[0] = newpair[0];
  3583. ((lfs_dir_t*)d)->head[1] = newpair[1];
  3584. }
  3585. }
  3586. // find parent
  3587. lfs_mdir_t parent;
  3588. lfs_stag_t tag = lfs_fs_parent(lfs, oldpair, &parent);
  3589. if (tag < 0 && tag != LFS_ERR_NOENT) {
  3590. return tag;
  3591. }
  3592. if (tag != LFS_ERR_NOENT) {
  3593. // update disk, this creates a desync
  3594. lfs_fs_preporphans(lfs, +1);
  3595. // fix pending move in this pair? this looks like an optimization but
  3596. // is in fact _required_ since relocating may outdate the move.
  3597. uint16_t moveid = 0x3ff;
  3598. if (lfs_gstate_hasmovehere(&lfs->gstate, parent.pair)) {
  3599. moveid = lfs_tag_id(lfs->gstate.tag);
  3600. LFS_DEBUG("Fixing move while relocating "
  3601. "{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
  3602. parent.pair[0], parent.pair[1], moveid);
  3603. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  3604. if (moveid < lfs_tag_id(tag)) {
  3605. tag -= LFS_MKTAG(0, 1, 0);
  3606. }
  3607. }
  3608. lfs_pair_tole32(newpair);
  3609. int err = lfs_dir_commit(lfs, &parent, LFS_MKATTRS(
  3610. {LFS_MKTAG_IF(moveid != 0x3ff,
  3611. LFS_TYPE_DELETE, moveid, 0), NULL},
  3612. {tag, newpair}));
  3613. lfs_pair_fromle32(newpair);
  3614. if (err) {
  3615. return err;
  3616. }
  3617. // next step, clean up orphans
  3618. lfs_fs_preporphans(lfs, -1);
  3619. }
  3620. // find pred
  3621. int err = lfs_fs_pred(lfs, oldpair, &parent);
  3622. if (err && err != LFS_ERR_NOENT) {
  3623. return err;
  3624. }
  3625. // if we can't find dir, it must be new
  3626. if (err != LFS_ERR_NOENT) {
  3627. // fix pending move in this pair? this looks like an optimization but
  3628. // is in fact _required_ since relocating may outdate the move.
  3629. uint16_t moveid = 0x3ff;
  3630. if (lfs_gstate_hasmovehere(&lfs->gstate, parent.pair)) {
  3631. moveid = lfs_tag_id(lfs->gstate.tag);
  3632. LFS_DEBUG("Fixing move while relocating "
  3633. "{0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16"\n",
  3634. parent.pair[0], parent.pair[1], moveid);
  3635. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  3636. }
  3637. // replace bad pair, either we clean up desync, or no desync occured
  3638. lfs_pair_tole32(newpair);
  3639. err = lfs_dir_commit(lfs, &parent, LFS_MKATTRS(
  3640. {LFS_MKTAG_IF(moveid != 0x3ff,
  3641. LFS_TYPE_DELETE, moveid, 0), NULL},
  3642. {LFS_MKTAG(LFS_TYPE_TAIL + parent.split, 0x3ff, 8), newpair}));
  3643. lfs_pair_fromle32(newpair);
  3644. if (err) {
  3645. return err;
  3646. }
  3647. }
  3648. return 0;
  3649. }
  3650. #endif
  3651. #ifndef LFS_READONLY
  3652. static void lfs_fs_preporphans(lfs_t *lfs, int8_t orphans) {
  3653. LFS_ASSERT(lfs_tag_size(lfs->gstate.tag) > 0 || orphans >= 0);
  3654. lfs->gstate.tag += orphans;
  3655. lfs->gstate.tag = ((lfs->gstate.tag & ~LFS_MKTAG(0x800, 0, 0)) |
  3656. ((uint32_t)lfs_gstate_hasorphans(&lfs->gstate) << 31));
  3657. }
  3658. #endif
  3659. #ifndef LFS_READONLY
  3660. static void lfs_fs_prepmove(lfs_t *lfs,
  3661. uint16_t id, const lfs_block_t pair[2]) {
  3662. lfs->gstate.tag = ((lfs->gstate.tag & ~LFS_MKTAG(0x7ff, 0x3ff, 0)) |
  3663. ((id != 0x3ff) ? LFS_MKTAG(LFS_TYPE_DELETE, id, 0) : 0));
  3664. lfs->gstate.pair[0] = (id != 0x3ff) ? pair[0] : 0;
  3665. lfs->gstate.pair[1] = (id != 0x3ff) ? pair[1] : 0;
  3666. }
  3667. #endif
  3668. #ifndef LFS_READONLY
  3669. static int lfs_fs_demove(lfs_t *lfs) {
  3670. if (!lfs_gstate_hasmove(&lfs->gdisk)) {
  3671. return 0;
  3672. }
  3673. // Fix bad moves
  3674. LFS_DEBUG("Fixing move {0x%"PRIx32", 0x%"PRIx32"} 0x%"PRIx16,
  3675. lfs->gdisk.pair[0],
  3676. lfs->gdisk.pair[1],
  3677. lfs_tag_id(lfs->gdisk.tag));
  3678. // fetch and delete the moved entry
  3679. lfs_mdir_t movedir;
  3680. int err = lfs_dir_fetch(lfs, &movedir, lfs->gdisk.pair);
  3681. if (err) {
  3682. return err;
  3683. }
  3684. // prep gstate and delete move id
  3685. uint16_t moveid = lfs_tag_id(lfs->gdisk.tag);
  3686. lfs_fs_prepmove(lfs, 0x3ff, NULL);
  3687. err = lfs_dir_commit(lfs, &movedir, LFS_MKATTRS(
  3688. {LFS_MKTAG(LFS_TYPE_DELETE, moveid, 0), NULL}));
  3689. if (err) {
  3690. return err;
  3691. }
  3692. return 0;
  3693. }
  3694. #endif
  3695. #ifndef LFS_READONLY
  3696. static int lfs_fs_deorphan(lfs_t *lfs) {
  3697. if (!lfs_gstate_hasorphans(&lfs->gstate)) {
  3698. return 0;
  3699. }
  3700. // Fix any orphans
  3701. lfs_mdir_t pdir = {.split = true, .tail = {0, 1}};
  3702. lfs_mdir_t dir;
  3703. // iterate over all directory directory entries
  3704. while (!lfs_pair_isnull(pdir.tail)) {
  3705. int err = lfs_dir_fetch(lfs, &dir, pdir.tail);
  3706. if (err) {
  3707. return err;
  3708. }
  3709. // check head blocks for orphans
  3710. if (!pdir.split) {
  3711. // check if we have a parent
  3712. lfs_mdir_t parent;
  3713. lfs_stag_t tag = lfs_fs_parent(lfs, pdir.tail, &parent);
  3714. if (tag < 0 && tag != LFS_ERR_NOENT) {
  3715. return tag;
  3716. }
  3717. if (tag == LFS_ERR_NOENT) {
  3718. // we are an orphan
  3719. LFS_DEBUG("Fixing orphan {0x%"PRIx32", 0x%"PRIx32"}",
  3720. pdir.tail[0], pdir.tail[1]);
  3721. err = lfs_dir_drop(lfs, &pdir, &dir);
  3722. if (err) {
  3723. return err;
  3724. }
  3725. // refetch tail
  3726. continue;
  3727. }
  3728. lfs_block_t pair[2];
  3729. lfs_stag_t res = lfs_dir_get(lfs, &parent,
  3730. LFS_MKTAG(0x7ff, 0x3ff, 0), tag, pair);
  3731. if (res < 0) {
  3732. return res;
  3733. }
  3734. lfs_pair_fromle32(pair);
  3735. if (!lfs_pair_sync(pair, pdir.tail)) {
  3736. // we have desynced
  3737. LFS_DEBUG("Fixing half-orphan {0x%"PRIx32", 0x%"PRIx32"} "
  3738. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  3739. pdir.tail[0], pdir.tail[1], pair[0], pair[1]);
  3740. lfs_pair_tole32(pair);
  3741. err = lfs_dir_commit(lfs, &pdir, LFS_MKATTRS(
  3742. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), pair}));
  3743. lfs_pair_fromle32(pair);
  3744. if (err) {
  3745. return err;
  3746. }
  3747. // refetch tail
  3748. continue;
  3749. }
  3750. }
  3751. pdir = dir;
  3752. }
  3753. // mark orphans as fixed
  3754. lfs_fs_preporphans(lfs, -lfs_gstate_getorphans(&lfs->gstate));
  3755. return 0;
  3756. }
  3757. #endif
  3758. #ifndef LFS_READONLY
  3759. static int lfs_fs_forceconsistency(lfs_t *lfs) {
  3760. int err = lfs_fs_demove(lfs);
  3761. if (err) {
  3762. return err;
  3763. }
  3764. err = lfs_fs_deorphan(lfs);
  3765. if (err) {
  3766. return err;
  3767. }
  3768. return 0;
  3769. }
  3770. #endif
  3771. static int lfs_fs_size_count(void *p, lfs_block_t block) {
  3772. (void)block;
  3773. lfs_size_t *size = p;
  3774. *size += 1;
  3775. return 0;
  3776. }
  3777. lfs_ssize_t lfs_fs_size(lfs_t *lfs) {
  3778. LFS_TRACE("lfs_fs_size(%p)", (void*)lfs);
  3779. lfs_size_t size = 0;
  3780. int err = lfs_fs_traverseraw(lfs, lfs_fs_size_count, &size, false);
  3781. if (err) {
  3782. LFS_TRACE("lfs_fs_size -> %d", err);
  3783. return err;
  3784. }
  3785. LFS_TRACE("lfs_fs_size -> %d", err);
  3786. return size;
  3787. }
  3788. #ifdef LFS_MIGRATE
  3789. ////// Migration from littelfs v1 below this //////
  3790. /// Version info ///
  3791. // Software library version
  3792. // Major (top-nibble), incremented on backwards incompatible changes
  3793. // Minor (bottom-nibble), incremented on feature additions
  3794. #define LFS1_VERSION 0x00010007
  3795. #define LFS1_VERSION_MAJOR (0xffff & (LFS1_VERSION >> 16))
  3796. #define LFS1_VERSION_MINOR (0xffff & (LFS1_VERSION >> 0))
  3797. // Version of On-disk data structures
  3798. // Major (top-nibble), incremented on backwards incompatible changes
  3799. // Minor (bottom-nibble), incremented on feature additions
  3800. #define LFS1_DISK_VERSION 0x00010001
  3801. #define LFS1_DISK_VERSION_MAJOR (0xffff & (LFS1_DISK_VERSION >> 16))
  3802. #define LFS1_DISK_VERSION_MINOR (0xffff & (LFS1_DISK_VERSION >> 0))
  3803. /// v1 Definitions ///
  3804. // File types
  3805. enum lfs1_type {
  3806. LFS1_TYPE_REG = 0x11,
  3807. LFS1_TYPE_DIR = 0x22,
  3808. LFS1_TYPE_SUPERBLOCK = 0x2e,
  3809. };
  3810. typedef struct lfs1 {
  3811. lfs_block_t root[2];
  3812. } lfs1_t;
  3813. typedef struct lfs1_entry {
  3814. lfs_off_t off;
  3815. struct lfs1_disk_entry {
  3816. uint8_t type;
  3817. uint8_t elen;
  3818. uint8_t alen;
  3819. uint8_t nlen;
  3820. union {
  3821. struct {
  3822. lfs_block_t head;
  3823. lfs_size_t size;
  3824. } file;
  3825. lfs_block_t dir[2];
  3826. } u;
  3827. } d;
  3828. } lfs1_entry_t;
  3829. typedef struct lfs1_dir {
  3830. struct lfs1_dir *next;
  3831. lfs_block_t pair[2];
  3832. lfs_off_t off;
  3833. lfs_block_t head[2];
  3834. lfs_off_t pos;
  3835. struct lfs1_disk_dir {
  3836. uint32_t rev;
  3837. lfs_size_t size;
  3838. lfs_block_t tail[2];
  3839. } d;
  3840. } lfs1_dir_t;
  3841. typedef struct lfs1_superblock {
  3842. lfs_off_t off;
  3843. struct lfs1_disk_superblock {
  3844. uint8_t type;
  3845. uint8_t elen;
  3846. uint8_t alen;
  3847. uint8_t nlen;
  3848. lfs_block_t root[2];
  3849. uint32_t block_size;
  3850. uint32_t block_count;
  3851. uint32_t version;
  3852. char magic[8];
  3853. } d;
  3854. } lfs1_superblock_t;
  3855. /// Low-level wrappers v1->v2 ///
  3856. static void lfs1_crc(uint32_t *crc, const void *buffer, size_t size) {
  3857. *crc = lfs_crc(*crc, buffer, size);
  3858. }
  3859. static int lfs1_bd_read(lfs_t *lfs, lfs_block_t block,
  3860. lfs_off_t off, void *buffer, lfs_size_t size) {
  3861. // if we ever do more than writes to alternating pairs,
  3862. // this may need to consider pcache
  3863. return lfs_bd_read(lfs, &lfs->pcache, &lfs->rcache, size,
  3864. block, off, buffer, size);
  3865. }
  3866. static int lfs1_bd_crc(lfs_t *lfs, lfs_block_t block,
  3867. lfs_off_t off, lfs_size_t size, uint32_t *crc) {
  3868. for (lfs_off_t i = 0; i < size; i++) {
  3869. uint8_t c;
  3870. int err = lfs1_bd_read(lfs, block, off+i, &c, 1);
  3871. if (err) {
  3872. return err;
  3873. }
  3874. lfs1_crc(crc, &c, 1);
  3875. }
  3876. return 0;
  3877. }
  3878. /// Endian swapping functions ///
  3879. static void lfs1_dir_fromle32(struct lfs1_disk_dir *d) {
  3880. d->rev = lfs_fromle32(d->rev);
  3881. d->size = lfs_fromle32(d->size);
  3882. d->tail[0] = lfs_fromle32(d->tail[0]);
  3883. d->tail[1] = lfs_fromle32(d->tail[1]);
  3884. }
  3885. static void lfs1_dir_tole32(struct lfs1_disk_dir *d) {
  3886. d->rev = lfs_tole32(d->rev);
  3887. d->size = lfs_tole32(d->size);
  3888. d->tail[0] = lfs_tole32(d->tail[0]);
  3889. d->tail[1] = lfs_tole32(d->tail[1]);
  3890. }
  3891. static void lfs1_entry_fromle32(struct lfs1_disk_entry *d) {
  3892. d->u.dir[0] = lfs_fromle32(d->u.dir[0]);
  3893. d->u.dir[1] = lfs_fromle32(d->u.dir[1]);
  3894. }
  3895. static void lfs1_entry_tole32(struct lfs1_disk_entry *d) {
  3896. d->u.dir[0] = lfs_tole32(d->u.dir[0]);
  3897. d->u.dir[1] = lfs_tole32(d->u.dir[1]);
  3898. }
  3899. static void lfs1_superblock_fromle32(struct lfs1_disk_superblock *d) {
  3900. d->root[0] = lfs_fromle32(d->root[0]);
  3901. d->root[1] = lfs_fromle32(d->root[1]);
  3902. d->block_size = lfs_fromle32(d->block_size);
  3903. d->block_count = lfs_fromle32(d->block_count);
  3904. d->version = lfs_fromle32(d->version);
  3905. }
  3906. ///// Metadata pair and directory operations ///
  3907. static inline lfs_size_t lfs1_entry_size(const lfs1_entry_t *entry) {
  3908. return 4 + entry->d.elen + entry->d.alen + entry->d.nlen;
  3909. }
  3910. static int lfs1_dir_fetch(lfs_t *lfs,
  3911. lfs1_dir_t *dir, const lfs_block_t pair[2]) {
  3912. // copy out pair, otherwise may be aliasing dir
  3913. const lfs_block_t tpair[2] = {pair[0], pair[1]};
  3914. bool valid = false;
  3915. // check both blocks for the most recent revision
  3916. for (int i = 0; i < 2; i++) {
  3917. struct lfs1_disk_dir test;
  3918. int err = lfs1_bd_read(lfs, tpair[i], 0, &test, sizeof(test));
  3919. lfs1_dir_fromle32(&test);
  3920. if (err) {
  3921. if (err == LFS_ERR_CORRUPT) {
  3922. continue;
  3923. }
  3924. return err;
  3925. }
  3926. if (valid && lfs_scmp(test.rev, dir->d.rev) < 0) {
  3927. continue;
  3928. }
  3929. if ((0x7fffffff & test.size) < sizeof(test)+4 ||
  3930. (0x7fffffff & test.size) > lfs->cfg->block_size) {
  3931. continue;
  3932. }
  3933. uint32_t crc = 0xffffffff;
  3934. lfs1_dir_tole32(&test);
  3935. lfs1_crc(&crc, &test, sizeof(test));
  3936. lfs1_dir_fromle32(&test);
  3937. err = lfs1_bd_crc(lfs, tpair[i], sizeof(test),
  3938. (0x7fffffff & test.size) - sizeof(test), &crc);
  3939. if (err) {
  3940. if (err == LFS_ERR_CORRUPT) {
  3941. continue;
  3942. }
  3943. return err;
  3944. }
  3945. if (crc != 0) {
  3946. continue;
  3947. }
  3948. valid = true;
  3949. // setup dir in case it's valid
  3950. dir->pair[0] = tpair[(i+0) % 2];
  3951. dir->pair[1] = tpair[(i+1) % 2];
  3952. dir->off = sizeof(dir->d);
  3953. dir->d = test;
  3954. }
  3955. if (!valid) {
  3956. LFS_ERROR("Corrupted dir pair at {0x%"PRIx32", 0x%"PRIx32"}",
  3957. tpair[0], tpair[1]);
  3958. return LFS_ERR_CORRUPT;
  3959. }
  3960. return 0;
  3961. }
  3962. static int lfs1_dir_next(lfs_t *lfs, lfs1_dir_t *dir, lfs1_entry_t *entry) {
  3963. while (dir->off + sizeof(entry->d) > (0x7fffffff & dir->d.size)-4) {
  3964. if (!(0x80000000 & dir->d.size)) {
  3965. entry->off = dir->off;
  3966. return LFS_ERR_NOENT;
  3967. }
  3968. int err = lfs1_dir_fetch(lfs, dir, dir->d.tail);
  3969. if (err) {
  3970. return err;
  3971. }
  3972. dir->off = sizeof(dir->d);
  3973. dir->pos += sizeof(dir->d) + 4;
  3974. }
  3975. int err = lfs1_bd_read(lfs, dir->pair[0], dir->off,
  3976. &entry->d, sizeof(entry->d));
  3977. lfs1_entry_fromle32(&entry->d);
  3978. if (err) {
  3979. return err;
  3980. }
  3981. entry->off = dir->off;
  3982. dir->off += lfs1_entry_size(entry);
  3983. dir->pos += lfs1_entry_size(entry);
  3984. return 0;
  3985. }
  3986. /// littlefs v1 specific operations ///
  3987. int lfs1_traverse(lfs_t *lfs, int (*cb)(void*, lfs_block_t), void *data) {
  3988. if (lfs_pair_isnull(lfs->lfs1->root)) {
  3989. return 0;
  3990. }
  3991. // iterate over metadata pairs
  3992. lfs1_dir_t dir;
  3993. lfs1_entry_t entry;
  3994. lfs_block_t cwd[2] = {0, 1};
  3995. while (true) {
  3996. for (int i = 0; i < 2; i++) {
  3997. int err = cb(data, cwd[i]);
  3998. if (err) {
  3999. return err;
  4000. }
  4001. }
  4002. int err = lfs1_dir_fetch(lfs, &dir, cwd);
  4003. if (err) {
  4004. return err;
  4005. }
  4006. // iterate over contents
  4007. while (dir.off + sizeof(entry.d) <= (0x7fffffff & dir.d.size)-4) {
  4008. err = lfs1_bd_read(lfs, dir.pair[0], dir.off,
  4009. &entry.d, sizeof(entry.d));
  4010. lfs1_entry_fromle32(&entry.d);
  4011. if (err) {
  4012. return err;
  4013. }
  4014. dir.off += lfs1_entry_size(&entry);
  4015. if ((0x70 & entry.d.type) == (0x70 & LFS1_TYPE_REG)) {
  4016. err = lfs_ctz_traverse(lfs, NULL, &lfs->rcache,
  4017. entry.d.u.file.head, entry.d.u.file.size, cb, data);
  4018. if (err) {
  4019. return err;
  4020. }
  4021. }
  4022. }
  4023. // we also need to check if we contain a threaded v2 directory
  4024. lfs_mdir_t dir2 = {.split=true, .tail={cwd[0], cwd[1]}};
  4025. while (dir2.split) {
  4026. err = lfs_dir_fetch(lfs, &dir2, dir2.tail);
  4027. if (err) {
  4028. break;
  4029. }
  4030. for (int i = 0; i < 2; i++) {
  4031. err = cb(data, dir2.pair[i]);
  4032. if (err) {
  4033. return err;
  4034. }
  4035. }
  4036. }
  4037. cwd[0] = dir.d.tail[0];
  4038. cwd[1] = dir.d.tail[1];
  4039. if (lfs_pair_isnull(cwd)) {
  4040. break;
  4041. }
  4042. }
  4043. return 0;
  4044. }
  4045. static int lfs1_moved(lfs_t *lfs, const void *e) {
  4046. if (lfs_pair_isnull(lfs->lfs1->root)) {
  4047. return 0;
  4048. }
  4049. // skip superblock
  4050. lfs1_dir_t cwd;
  4051. int err = lfs1_dir_fetch(lfs, &cwd, (const lfs_block_t[2]){0, 1});
  4052. if (err) {
  4053. return err;
  4054. }
  4055. // iterate over all directory directory entries
  4056. lfs1_entry_t entry;
  4057. while (!lfs_pair_isnull(cwd.d.tail)) {
  4058. err = lfs1_dir_fetch(lfs, &cwd, cwd.d.tail);
  4059. if (err) {
  4060. return err;
  4061. }
  4062. while (true) {
  4063. err = lfs1_dir_next(lfs, &cwd, &entry);
  4064. if (err && err != LFS_ERR_NOENT) {
  4065. return err;
  4066. }
  4067. if (err == LFS_ERR_NOENT) {
  4068. break;
  4069. }
  4070. if (!(0x80 & entry.d.type) &&
  4071. memcmp(&entry.d.u, e, sizeof(entry.d.u)) == 0) {
  4072. return true;
  4073. }
  4074. }
  4075. }
  4076. return false;
  4077. }
  4078. /// Filesystem operations ///
  4079. static int lfs1_mount(lfs_t *lfs, struct lfs1 *lfs1,
  4080. const struct lfs_config *cfg) {
  4081. int err = 0;
  4082. {
  4083. err = lfs_init(lfs, cfg);
  4084. if (err) {
  4085. return err;
  4086. }
  4087. lfs->lfs1 = lfs1;
  4088. lfs->lfs1->root[0] = LFS_BLOCK_NULL;
  4089. lfs->lfs1->root[1] = LFS_BLOCK_NULL;
  4090. // setup free lookahead
  4091. lfs->free.off = 0;
  4092. lfs->free.size = 0;
  4093. lfs->free.i = 0;
  4094. lfs_alloc_ack(lfs);
  4095. // load superblock
  4096. lfs1_dir_t dir;
  4097. lfs1_superblock_t superblock;
  4098. err = lfs1_dir_fetch(lfs, &dir, (const lfs_block_t[2]){0, 1});
  4099. if (err && err != LFS_ERR_CORRUPT) {
  4100. goto cleanup;
  4101. }
  4102. if (!err) {
  4103. err = lfs1_bd_read(lfs, dir.pair[0], sizeof(dir.d),
  4104. &superblock.d, sizeof(superblock.d));
  4105. lfs1_superblock_fromle32(&superblock.d);
  4106. if (err) {
  4107. goto cleanup;
  4108. }
  4109. lfs->lfs1->root[0] = superblock.d.root[0];
  4110. lfs->lfs1->root[1] = superblock.d.root[1];
  4111. }
  4112. if (err || memcmp(superblock.d.magic, "littlefs", 8) != 0) {
  4113. LFS_ERROR("Invalid superblock at {0x%"PRIx32", 0x%"PRIx32"}",
  4114. 0, 1);
  4115. err = LFS_ERR_CORRUPT;
  4116. goto cleanup;
  4117. }
  4118. uint16_t major_version = (0xffff & (superblock.d.version >> 16));
  4119. uint16_t minor_version = (0xffff & (superblock.d.version >> 0));
  4120. if ((major_version != LFS1_DISK_VERSION_MAJOR ||
  4121. minor_version > LFS1_DISK_VERSION_MINOR)) {
  4122. LFS_ERROR("Invalid version v%d.%d", major_version, minor_version);
  4123. err = LFS_ERR_INVAL;
  4124. goto cleanup;
  4125. }
  4126. return 0;
  4127. }
  4128. cleanup:
  4129. lfs_deinit(lfs);
  4130. return err;
  4131. }
  4132. static int lfs1_unmount(lfs_t *lfs) {
  4133. return lfs_deinit(lfs);
  4134. }
  4135. /// v1 migration ///
  4136. int lfs_migrate(lfs_t *lfs, const struct lfs_config *cfg) {
  4137. LFS_TRACE("lfs_migrate(%p, %p {.context=%p, "
  4138. ".read=%p, .prog=%p, .erase=%p, .sync=%p, "
  4139. ".read_size=%"PRIu32", .prog_size=%"PRIu32", "
  4140. ".block_size=%"PRIu32", .block_count=%"PRIu32", "
  4141. ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", "
  4142. ".lookahead_size=%"PRIu32", .read_buffer=%p, "
  4143. ".prog_buffer=%p, .lookahead_buffer=%p, "
  4144. ".name_max=%"PRIu32", .file_max=%"PRIu32", "
  4145. ".attr_max=%"PRIu32"})",
  4146. (void*)lfs, (void*)cfg, cfg->context,
  4147. (void*)(uintptr_t)cfg->read, (void*)(uintptr_t)cfg->prog,
  4148. (void*)(uintptr_t)cfg->erase, (void*)(uintptr_t)cfg->sync,
  4149. cfg->read_size, cfg->prog_size, cfg->block_size, cfg->block_count,
  4150. cfg->block_cycles, cfg->cache_size, cfg->lookahead_size,
  4151. cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer,
  4152. cfg->name_max, cfg->file_max, cfg->attr_max);
  4153. struct lfs1 lfs1;
  4154. int err = lfs1_mount(lfs, &lfs1, cfg);
  4155. if (err) {
  4156. LFS_TRACE("lfs_migrate -> %d", err);
  4157. return err;
  4158. }
  4159. {
  4160. // iterate through each directory, copying over entries
  4161. // into new directory
  4162. lfs1_dir_t dir1;
  4163. lfs_mdir_t dir2;
  4164. dir1.d.tail[0] = lfs->lfs1->root[0];
  4165. dir1.d.tail[1] = lfs->lfs1->root[1];
  4166. while (!lfs_pair_isnull(dir1.d.tail)) {
  4167. // iterate old dir
  4168. err = lfs1_dir_fetch(lfs, &dir1, dir1.d.tail);
  4169. if (err) {
  4170. goto cleanup;
  4171. }
  4172. // create new dir and bind as temporary pretend root
  4173. err = lfs_dir_alloc(lfs, &dir2);
  4174. if (err) {
  4175. goto cleanup;
  4176. }
  4177. dir2.rev = dir1.d.rev;
  4178. dir1.head[0] = dir1.pair[0];
  4179. dir1.head[1] = dir1.pair[1];
  4180. lfs->root[0] = dir2.pair[0];
  4181. lfs->root[1] = dir2.pair[1];
  4182. err = lfs_dir_commit(lfs, &dir2, NULL, 0);
  4183. if (err) {
  4184. goto cleanup;
  4185. }
  4186. while (true) {
  4187. lfs1_entry_t entry1;
  4188. err = lfs1_dir_next(lfs, &dir1, &entry1);
  4189. if (err && err != LFS_ERR_NOENT) {
  4190. goto cleanup;
  4191. }
  4192. if (err == LFS_ERR_NOENT) {
  4193. break;
  4194. }
  4195. // check that entry has not been moved
  4196. if (entry1.d.type & 0x80) {
  4197. int moved = lfs1_moved(lfs, &entry1.d.u);
  4198. if (moved < 0) {
  4199. err = moved;
  4200. goto cleanup;
  4201. }
  4202. if (moved) {
  4203. continue;
  4204. }
  4205. entry1.d.type &= ~0x80;
  4206. }
  4207. // also fetch name
  4208. char name[LFS_NAME_MAX+1];
  4209. memset(name, 0, sizeof(name));
  4210. err = lfs1_bd_read(lfs, dir1.pair[0],
  4211. entry1.off + 4+entry1.d.elen+entry1.d.alen,
  4212. name, entry1.d.nlen);
  4213. if (err) {
  4214. goto cleanup;
  4215. }
  4216. bool isdir = (entry1.d.type == LFS1_TYPE_DIR);
  4217. // create entry in new dir
  4218. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4219. if (err) {
  4220. goto cleanup;
  4221. }
  4222. uint16_t id;
  4223. err = lfs_dir_find(lfs, &dir2, &(const char*){name}, &id);
  4224. if (!(err == LFS_ERR_NOENT && id != 0x3ff)) {
  4225. err = (err < 0) ? err : LFS_ERR_EXIST;
  4226. goto cleanup;
  4227. }
  4228. lfs1_entry_tole32(&entry1.d);
  4229. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4230. {LFS_MKTAG(LFS_TYPE_CREATE, id, 0)},
  4231. {LFS_MKTAG_IF_ELSE(isdir,
  4232. LFS_TYPE_DIR, id, entry1.d.nlen,
  4233. LFS_TYPE_REG, id, entry1.d.nlen),
  4234. name},
  4235. {LFS_MKTAG_IF_ELSE(isdir,
  4236. LFS_TYPE_DIRSTRUCT, id, sizeof(entry1.d.u),
  4237. LFS_TYPE_CTZSTRUCT, id, sizeof(entry1.d.u)),
  4238. &entry1.d.u}));
  4239. lfs1_entry_fromle32(&entry1.d);
  4240. if (err) {
  4241. goto cleanup;
  4242. }
  4243. }
  4244. if (!lfs_pair_isnull(dir1.d.tail)) {
  4245. // find last block and update tail to thread into fs
  4246. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4247. if (err) {
  4248. goto cleanup;
  4249. }
  4250. while (dir2.split) {
  4251. err = lfs_dir_fetch(lfs, &dir2, dir2.tail);
  4252. if (err) {
  4253. goto cleanup;
  4254. }
  4255. }
  4256. lfs_pair_tole32(dir2.pair);
  4257. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4258. {LFS_MKTAG(LFS_TYPE_SOFTTAIL, 0x3ff, 8), dir1.d.tail}));
  4259. lfs_pair_fromle32(dir2.pair);
  4260. if (err) {
  4261. goto cleanup;
  4262. }
  4263. }
  4264. // Copy over first block to thread into fs. Unfortunately
  4265. // if this fails there is not much we can do.
  4266. LFS_DEBUG("Migrating {0x%"PRIx32", 0x%"PRIx32"} "
  4267. "-> {0x%"PRIx32", 0x%"PRIx32"}",
  4268. lfs->root[0], lfs->root[1], dir1.head[0], dir1.head[1]);
  4269. err = lfs_bd_erase(lfs, dir1.head[1]);
  4270. if (err) {
  4271. goto cleanup;
  4272. }
  4273. err = lfs_dir_fetch(lfs, &dir2, lfs->root);
  4274. if (err) {
  4275. goto cleanup;
  4276. }
  4277. for (lfs_off_t i = 0; i < dir2.off; i++) {
  4278. uint8_t dat;
  4279. err = lfs_bd_read(lfs,
  4280. NULL, &lfs->rcache, dir2.off,
  4281. dir2.pair[0], i, &dat, 1);
  4282. if (err) {
  4283. goto cleanup;
  4284. }
  4285. err = lfs_bd_prog(lfs,
  4286. &lfs->pcache, &lfs->rcache, true,
  4287. dir1.head[1], i, &dat, 1);
  4288. if (err) {
  4289. goto cleanup;
  4290. }
  4291. }
  4292. err = lfs_bd_flush(lfs, &lfs->pcache, &lfs->rcache, true);
  4293. if (err) {
  4294. goto cleanup;
  4295. }
  4296. }
  4297. // Create new superblock. This marks a successful migration!
  4298. err = lfs1_dir_fetch(lfs, &dir1, (const lfs_block_t[2]){0, 1});
  4299. if (err) {
  4300. goto cleanup;
  4301. }
  4302. dir2.pair[0] = dir1.pair[0];
  4303. dir2.pair[1] = dir1.pair[1];
  4304. dir2.rev = dir1.d.rev;
  4305. dir2.off = sizeof(dir2.rev);
  4306. dir2.etag = 0xffffffff;
  4307. dir2.count = 0;
  4308. dir2.tail[0] = lfs->lfs1->root[0];
  4309. dir2.tail[1] = lfs->lfs1->root[1];
  4310. dir2.erased = false;
  4311. dir2.split = true;
  4312. lfs_superblock_t superblock = {
  4313. .version = LFS_DISK_VERSION,
  4314. .block_size = lfs->cfg->block_size,
  4315. .block_count = lfs->cfg->block_count,
  4316. .name_max = lfs->name_max,
  4317. .file_max = lfs->file_max,
  4318. .attr_max = lfs->attr_max,
  4319. };
  4320. lfs_superblock_tole32(&superblock);
  4321. err = lfs_dir_commit(lfs, &dir2, LFS_MKATTRS(
  4322. {LFS_MKTAG(LFS_TYPE_CREATE, 0, 0)},
  4323. {LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
  4324. {LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
  4325. &superblock}));
  4326. if (err) {
  4327. goto cleanup;
  4328. }
  4329. // sanity check that fetch works
  4330. err = lfs_dir_fetch(lfs, &dir2, (const lfs_block_t[2]){0, 1});
  4331. if (err) {
  4332. goto cleanup;
  4333. }
  4334. // force compaction to prevent accidentally mounting v1
  4335. dir2.erased = false;
  4336. err = lfs_dir_commit(lfs, &dir2, NULL, 0);
  4337. if (err) {
  4338. goto cleanup;
  4339. }
  4340. }
  4341. cleanup:
  4342. lfs1_unmount(lfs);
  4343. LFS_TRACE("lfs_migrate -> %d", err);
  4344. return err;
  4345. }
  4346. #endif