lfs.c 171 KB

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