lfs.c 171 KB

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