lfs.c 180 KB

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