lfs.c 193 KB

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