lfs.c 190 KB

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