ff.c 242 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983
  1. /*----------------------------------------------------------------------------/
  2. / FatFs - Generic FAT Filesystem Module R0.14b /
  3. /-----------------------------------------------------------------------------/
  4. /
  5. / Copyright (C) 2021, ChaN, all right reserved.
  6. /
  7. / FatFs module is an open source software. Redistribution and use of FatFs in
  8. / source and binary forms, with or without modification, are permitted provided
  9. / that the following condition is met:
  10. /
  11. / 1. Redistributions of source code must retain the above copyright notice,
  12. / this condition and the following disclaimer.
  13. /
  14. / This software is provided by the copyright holder and contributors "AS IS"
  15. / and any warranties related to this software are DISCLAIMED.
  16. / The copyright owner or contributors be NOT LIABLE for any damages caused
  17. / by use of this software.
  18. /
  19. /----------------------------------------------------------------------------*/
  20. #include <string.h>
  21. #include "ff.h" /* Declarations of FatFs API */
  22. #include "diskio.h" /* Declarations of device I/O functions */
  23. /*--------------------------------------------------------------------------
  24. Module Private Definitions
  25. ---------------------------------------------------------------------------*/
  26. #if FF_DEFINED != 86631 /* Revision ID */
  27. #error Wrong include file (ff.h).
  28. #endif
  29. /* Limits and boundaries */
  30. #define MAX_DIR 0x200000 /* Max size of FAT directory */
  31. #define MAX_DIR_EX 0x10000000 /* Max size of exFAT directory */
  32. #define MAX_FAT12 0xFF5 /* Max FAT12 clusters (differs from specs, but right for real DOS/Windows behavior) */
  33. #define MAX_FAT16 0xFFF5 /* Max FAT16 clusters (differs from specs, but right for real DOS/Windows behavior) */
  34. #define MAX_FAT32 0x0FFFFFF5 /* Max FAT32 clusters (not specified, practical limit) */
  35. #define MAX_EXFAT 0x7FFFFFFD /* Max exFAT clusters (differs from specs, implementation limit) */
  36. /* Character code support macros */
  37. #define IsUpper(c) ((c) >= 'A' && (c) <= 'Z')
  38. #define IsLower(c) ((c) >= 'a' && (c) <= 'z')
  39. #define IsDigit(c) ((c) >= '0' && (c) <= '9')
  40. #define IsSeparator(c) ((c) == '/' || (c) == '\\')
  41. #define IsTerminator(c) ((UINT)(c) < (FF_USE_LFN ? ' ' : '!'))
  42. #define IsSurrogate(c) ((c) >= 0xD800 && (c) <= 0xDFFF)
  43. #define IsSurrogateH(c) ((c) >= 0xD800 && (c) <= 0xDBFF)
  44. #define IsSurrogateL(c) ((c) >= 0xDC00 && (c) <= 0xDFFF)
  45. /* Additional file access control and file status flags for internal use */
  46. #define FA_SEEKEND 0x20 /* Seek to end of the file on file open */
  47. #define FA_MODIFIED 0x40 /* File has been modified */
  48. #define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */
  49. /* Additional file attribute bits for internal use */
  50. #define AM_VOL 0x08 /* Volume label */
  51. #define AM_LFN 0x0F /* LFN entry */
  52. #define AM_MASK 0x3F /* Mask of defined bits in FAT */
  53. #define AM_MASKX 0x37 /* Mask of defined bits in exFAT */
  54. /* Name status flags in fn[11] */
  55. #define NSFLAG 11 /* Index of the name status byte */
  56. #define NS_LOSS 0x01 /* Out of 8.3 format */
  57. #define NS_LFN 0x02 /* Force to create LFN entry */
  58. #define NS_LAST 0x04 /* Last segment */
  59. #define NS_BODY 0x08 /* Lower case flag (body) */
  60. #define NS_EXT 0x10 /* Lower case flag (ext) */
  61. #define NS_DOT 0x20 /* Dot entry */
  62. #define NS_NOLFN 0x40 /* Do not find LFN */
  63. #define NS_NONAME 0x80 /* Not followed */
  64. /* exFAT directory entry types */
  65. #define ET_BITMAP 0x81 /* Allocation bitmap */
  66. #define ET_UPCASE 0x82 /* Up-case table */
  67. #define ET_VLABEL 0x83 /* Volume label */
  68. #define ET_FILEDIR 0x85 /* File and directory */
  69. #define ET_STREAM 0xC0 /* Stream extension */
  70. #define ET_FILENAME 0xC1 /* Name extension */
  71. /* FatFs refers the FAT structure as simple byte array instead of structure member
  72. / because the C structure is not binary compatible between different platforms */
  73. #define BS_JmpBoot 0 /* x86 jump instruction (3-byte) */
  74. #define BS_OEMName 3 /* OEM name (8-byte) */
  75. #define BPB_BytsPerSec 11 /* Sector size [byte] (WORD) */
  76. #define BPB_SecPerClus 13 /* Cluster size [sector] (BYTE) */
  77. #define BPB_RsvdSecCnt 14 /* Size of reserved area [sector] (WORD) */
  78. #define BPB_NumFATs 16 /* Number of FATs (BYTE) */
  79. #define BPB_RootEntCnt 17 /* Size of root directory area for FAT [entry] (WORD) */
  80. #define BPB_TotSec16 19 /* Volume size (16-bit) [sector] (WORD) */
  81. #define BPB_Media 21 /* Media descriptor byte (BYTE) */
  82. #define BPB_FATSz16 22 /* FAT size (16-bit) [sector] (WORD) */
  83. #define BPB_SecPerTrk 24 /* Number of sectors per track for int13h [sector] (WORD) */
  84. #define BPB_NumHeads 26 /* Number of heads for int13h (WORD) */
  85. #define BPB_HiddSec 28 /* Volume offset from top of the drive (DWORD) */
  86. #define BPB_TotSec32 32 /* Volume size (32-bit) [sector] (DWORD) */
  87. #define BS_DrvNum 36 /* Physical drive number for int13h (BYTE) */
  88. #define BS_NTres 37 /* WindowsNT error flag (BYTE) */
  89. #define BS_BootSig 38 /* Extended boot signature (BYTE) */
  90. #define BS_VolID 39 /* Volume serial number (DWORD) */
  91. #define BS_VolLab 43 /* Volume label string (8-byte) */
  92. #define BS_FilSysType 54 /* Filesystem type string (8-byte) */
  93. #define BS_BootCode 62 /* Boot code (448-byte) */
  94. #define BS_55AA 510 /* Signature word (WORD) */
  95. #define BPB_FATSz32 36 /* FAT32: FAT size [sector] (DWORD) */
  96. #define BPB_ExtFlags32 40 /* FAT32: Extended flags (WORD) */
  97. #define BPB_FSVer32 42 /* FAT32: Filesystem version (WORD) */
  98. #define BPB_RootClus32 44 /* FAT32: Root directory cluster (DWORD) */
  99. #define BPB_FSInfo32 48 /* FAT32: Offset of FSINFO sector (WORD) */
  100. #define BPB_BkBootSec32 50 /* FAT32: Offset of backup boot sector (WORD) */
  101. #define BS_DrvNum32 64 /* FAT32: Physical drive number for int13h (BYTE) */
  102. #define BS_NTres32 65 /* FAT32: Error flag (BYTE) */
  103. #define BS_BootSig32 66 /* FAT32: Extended boot signature (BYTE) */
  104. #define BS_VolID32 67 /* FAT32: Volume serial number (DWORD) */
  105. #define BS_VolLab32 71 /* FAT32: Volume label string (8-byte) */
  106. #define BS_FilSysType32 82 /* FAT32: Filesystem type string (8-byte) */
  107. #define BS_BootCode32 90 /* FAT32: Boot code (420-byte) */
  108. #define BPB_ZeroedEx 11 /* exFAT: MBZ field (53-byte) */
  109. #define BPB_VolOfsEx 64 /* exFAT: Volume offset from top of the drive [sector] (QWORD) */
  110. #define BPB_TotSecEx 72 /* exFAT: Volume size [sector] (QWORD) */
  111. #define BPB_FatOfsEx 80 /* exFAT: FAT offset from top of the volume [sector] (DWORD) */
  112. #define BPB_FatSzEx 84 /* exFAT: FAT size [sector] (DWORD) */
  113. #define BPB_DataOfsEx 88 /* exFAT: Data offset from top of the volume [sector] (DWORD) */
  114. #define BPB_NumClusEx 92 /* exFAT: Number of clusters (DWORD) */
  115. #define BPB_RootClusEx 96 /* exFAT: Root directory start cluster (DWORD) */
  116. #define BPB_VolIDEx 100 /* exFAT: Volume serial number (DWORD) */
  117. #define BPB_FSVerEx 104 /* exFAT: Filesystem version (WORD) */
  118. #define BPB_VolFlagEx 106 /* exFAT: Volume flags (WORD) */
  119. #define BPB_BytsPerSecEx 108 /* exFAT: Log2 of sector size in unit of byte (BYTE) */
  120. #define BPB_SecPerClusEx 109 /* exFAT: Log2 of cluster size in unit of sector (BYTE) */
  121. #define BPB_NumFATsEx 110 /* exFAT: Number of FATs (BYTE) */
  122. #define BPB_DrvNumEx 111 /* exFAT: Physical drive number for int13h (BYTE) */
  123. #define BPB_PercInUseEx 112 /* exFAT: Percent in use (BYTE) */
  124. #define BPB_RsvdEx 113 /* exFAT: Reserved (7-byte) */
  125. #define BS_BootCodeEx 120 /* exFAT: Boot code (390-byte) */
  126. #define DIR_Name 0 /* Short file name (11-byte) */
  127. #define DIR_Attr 11 /* Attribute (BYTE) */
  128. #define DIR_NTres 12 /* Lower case flag (BYTE) */
  129. #define DIR_CrtTime10 13 /* Created time sub-second (BYTE) */
  130. #define DIR_CrtTime 14 /* Created time (DWORD) */
  131. #define DIR_LstAccDate 18 /* Last accessed date (WORD) */
  132. #define DIR_FstClusHI 20 /* Higher 16-bit of first cluster (WORD) */
  133. #define DIR_ModTime 22 /* Modified time (DWORD) */
  134. #define DIR_FstClusLO 26 /* Lower 16-bit of first cluster (WORD) */
  135. #define DIR_FileSize 28 /* File size (DWORD) */
  136. #define LDIR_Ord 0 /* LFN: LFN order and LLE flag (BYTE) */
  137. #define LDIR_Attr 11 /* LFN: LFN attribute (BYTE) */
  138. #define LDIR_Type 12 /* LFN: Entry type (BYTE) */
  139. #define LDIR_Chksum 13 /* LFN: Checksum of the SFN (BYTE) */
  140. #define LDIR_FstClusLO 26 /* LFN: MBZ field (WORD) */
  141. #define XDIR_Type 0 /* exFAT: Type of exFAT directory entry (BYTE) */
  142. #define XDIR_NumLabel 1 /* exFAT: Number of volume label characters (BYTE) */
  143. #define XDIR_Label 2 /* exFAT: Volume label (11-WORD) */
  144. #define XDIR_CaseSum 4 /* exFAT: Sum of case conversion table (DWORD) */
  145. #define XDIR_NumSec 1 /* exFAT: Number of secondary entries (BYTE) */
  146. #define XDIR_SetSum 2 /* exFAT: Sum of the set of directory entries (WORD) */
  147. #define XDIR_Attr 4 /* exFAT: File attribute (WORD) */
  148. #define XDIR_CrtTime 8 /* exFAT: Created time (DWORD) */
  149. #define XDIR_ModTime 12 /* exFAT: Modified time (DWORD) */
  150. #define XDIR_AccTime 16 /* exFAT: Last accessed time (DWORD) */
  151. #define XDIR_CrtTime10 20 /* exFAT: Created time subsecond (BYTE) */
  152. #define XDIR_ModTime10 21 /* exFAT: Modified time subsecond (BYTE) */
  153. #define XDIR_CrtTZ 22 /* exFAT: Created timezone (BYTE) */
  154. #define XDIR_ModTZ 23 /* exFAT: Modified timezone (BYTE) */
  155. #define XDIR_AccTZ 24 /* exFAT: Last accessed timezone (BYTE) */
  156. #define XDIR_GenFlags 33 /* exFAT: General secondary flags (BYTE) */
  157. #define XDIR_NumName 35 /* exFAT: Number of file name characters (BYTE) */
  158. #define XDIR_NameHash 36 /* exFAT: Hash of file name (WORD) */
  159. #define XDIR_ValidFileSize 40 /* exFAT: Valid file size (QWORD) */
  160. #define XDIR_FstClus 52 /* exFAT: First cluster of the file data (DWORD) */
  161. #define XDIR_FileSize 56 /* exFAT: File/Directory size (QWORD) */
  162. #define SZDIRE 32 /* Size of a directory entry */
  163. #define DDEM 0xE5 /* Deleted directory entry mark set to DIR_Name[0] */
  164. #define RDDEM 0x05 /* Replacement of the character collides with DDEM */
  165. #define LLEF 0x40 /* Last long entry flag in LDIR_Ord */
  166. #define FSI_LeadSig 0 /* FAT32 FSI: Leading signature (DWORD) */
  167. #define FSI_StrucSig 484 /* FAT32 FSI: Structure signature (DWORD) */
  168. #define FSI_Free_Count 488 /* FAT32 FSI: Number of free clusters (DWORD) */
  169. #define FSI_Nxt_Free 492 /* FAT32 FSI: Last allocated cluster (DWORD) */
  170. #define MBR_Table 446 /* MBR: Offset of partition table in the MBR */
  171. #define SZ_PTE 16 /* MBR: Size of a partition table entry */
  172. #define PTE_Boot 0 /* MBR PTE: Boot indicator */
  173. #define PTE_StHead 1 /* MBR PTE: Start head */
  174. #define PTE_StSec 2 /* MBR PTE: Start sector */
  175. #define PTE_StCyl 3 /* MBR PTE: Start cylinder */
  176. #define PTE_System 4 /* MBR PTE: System ID */
  177. #define PTE_EdHead 5 /* MBR PTE: End head */
  178. #define PTE_EdSec 6 /* MBR PTE: End sector */
  179. #define PTE_EdCyl 7 /* MBR PTE: End cylinder */
  180. #define PTE_StLba 8 /* MBR PTE: Start in LBA */
  181. #define PTE_SizLba 12 /* MBR PTE: Size in LBA */
  182. #define GPTH_Sign 0 /* GPT: Header signature (8-byte) */
  183. #define GPTH_Rev 8 /* GPT: Revision (DWORD) */
  184. #define GPTH_Size 12 /* GPT: Header size (DWORD) */
  185. #define GPTH_Bcc 16 /* GPT: Header BCC (DWORD) */
  186. #define GPTH_CurLba 24 /* GPT: Main header LBA (QWORD) */
  187. #define GPTH_BakLba 32 /* GPT: Backup header LBA (QWORD) */
  188. #define GPTH_FstLba 40 /* GPT: First LBA for partitions (QWORD) */
  189. #define GPTH_LstLba 48 /* GPT: Last LBA for partitions (QWORD) */
  190. #define GPTH_DskGuid 56 /* GPT: Disk GUID (16-byte) */
  191. #define GPTH_PtOfs 72 /* GPT: Partation table LBA (QWORD) */
  192. #define GPTH_PtNum 80 /* GPT: Number of table entries (DWORD) */
  193. #define GPTH_PteSize 84 /* GPT: Size of table entry (DWORD) */
  194. #define GPTH_PtBcc 88 /* GPT: Partation table BCC (DWORD) */
  195. #define SZ_GPTE 128 /* GPT: Size of partition table entry */
  196. #define GPTE_PtGuid 0 /* GPT PTE: Partition type GUID (16-byte) */
  197. #define GPTE_UpGuid 16 /* GPT PTE: Partition unique GUID (16-byte) */
  198. #define GPTE_FstLba 32 /* GPT PTE: First LBA (QWORD) */
  199. #define GPTE_LstLba 40 /* GPT PTE: Last LBA inclusive (QWORD) */
  200. #define GPTE_Flags 48 /* GPT PTE: Flags (QWORD) */
  201. #define GPTE_Name 56 /* GPT PTE: Name */
  202. /* Post process on fatal error in the file operations */
  203. #define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }
  204. /* Re-entrancy related */
  205. #if FF_FS_REENTRANT
  206. #if FF_USE_LFN == 1
  207. #error Static LFN work area cannot be used in thread-safe configuration
  208. #endif
  209. #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }
  210. #else
  211. #define LEAVE_FF(fs, res) return res
  212. #endif
  213. /* Definitions of logical drive - physical location conversion */
  214. #if FF_MULTI_PARTITION
  215. #define LD2PD(vol) VolToPart[vol].pd /* Get physical drive number */
  216. #define LD2PT(vol) VolToPart[vol].pt /* Get partition number (0:auto search, 1..:forced partition number) */
  217. #else
  218. #define LD2PD(vol) (BYTE)(vol) /* Each logical drive is associated with the same physical drive number */
  219. #define LD2PT(vol) 0 /* Auto partition search */
  220. #endif
  221. /* Definitions of sector size */
  222. #if (FF_MAX_SS < FF_MIN_SS) || (FF_MAX_SS != 512 && FF_MAX_SS != 1024 && FF_MAX_SS != 2048 && FF_MAX_SS != 4096) || (FF_MIN_SS != 512 && FF_MIN_SS != 1024 && FF_MIN_SS != 2048 && FF_MIN_SS != 4096)
  223. #error Wrong sector size configuration
  224. #endif
  225. #if FF_MAX_SS == FF_MIN_SS
  226. #define SS(fs) ((UINT)FF_MAX_SS) /* Fixed sector size */
  227. #else
  228. #define SS(fs) ((fs)->ssize) /* Variable sector size */
  229. #endif
  230. /* Timestamp */
  231. #if FF_FS_NORTC == 1
  232. #if FF_NORTC_YEAR < 1980 || FF_NORTC_YEAR > 2107 || FF_NORTC_MON < 1 || FF_NORTC_MON > 12 || FF_NORTC_MDAY < 1 || FF_NORTC_MDAY > 31
  233. #error Invalid FF_FS_NORTC settings
  234. #endif
  235. #define GET_FATTIME() ((DWORD)(FF_NORTC_YEAR - 1980) << 25 | (DWORD)FF_NORTC_MON << 21 | (DWORD)FF_NORTC_MDAY << 16)
  236. #else
  237. #define GET_FATTIME() get_fattime()
  238. #endif
  239. /* File lock controls */
  240. #if FF_FS_LOCK != 0
  241. #if FF_FS_READONLY
  242. #error FF_FS_LOCK must be 0 at read-only configuration
  243. #endif
  244. typedef struct {
  245. FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */
  246. DWORD clu; /* Object ID 2, containing directory (0:root) */
  247. DWORD ofs; /* Object ID 3, offset in the directory */
  248. WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */
  249. } FILESEM;
  250. #endif
  251. /* SBCS up-case tables (\x80-\xFF) */
  252. #define TBL_CT437 {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  253. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  254. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  255. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  256. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  257. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  258. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  259. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  260. #define TBL_CT720 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  261. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  262. 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  263. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  264. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  265. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  266. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  267. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  268. #define TBL_CT737 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  269. 0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
  270. 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96, \
  271. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  272. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  273. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  274. 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xEF,0xF5,0xF0,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  275. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  276. #define TBL_CT771 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  277. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  278. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  279. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  280. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  281. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDC,0xDE,0xDE, \
  282. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  283. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFE,0xFF}
  284. #define TBL_CT775 {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F, \
  285. 0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  286. 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  287. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  288. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  289. 0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  290. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF, \
  291. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  292. #define TBL_CT850 {0x43,0x55,0x45,0x41,0x41,0x41,0x41,0x43,0x45,0x45,0x45,0x49,0x49,0x49,0x41,0x41, \
  293. 0x45,0x92,0x92,0x4F,0x4F,0x4F,0x55,0x55,0x59,0x4F,0x55,0x4F,0x9C,0x4F,0x9E,0x9F, \
  294. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  295. 0xB0,0xB1,0xB2,0xB3,0xB4,0x41,0x41,0x41,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  296. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0x41,0x41,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  297. 0xD1,0xD1,0x45,0x45,0x45,0x49,0x49,0x49,0x49,0xD9,0xDA,0xDB,0xDC,0xDD,0x49,0xDF, \
  298. 0x4F,0xE1,0x4F,0x4F,0x4F,0x4F,0xE6,0xE8,0xE8,0x55,0x55,0x55,0x59,0x59,0xEE,0xEF, \
  299. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  300. #define TBL_CT852 {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F, \
  301. 0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0xAC, \
  302. 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF, \
  303. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
  304. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  305. 0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  306. 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF, \
  307. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
  308. #define TBL_CT855 {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F, \
  309. 0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
  310. 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF, \
  311. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
  312. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  313. 0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
  314. 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF, \
  315. 0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
  316. #define TBL_CT857 {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x49,0x8E,0x8F, \
  317. 0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
  318. 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  319. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  320. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  321. 0xD0,0xD1,0xD2,0xD3,0xD4,0x49,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  322. 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0xED,0xEE,0xEF, \
  323. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  324. #define TBL_CT860 {0x80,0x9A,0x90,0x8F,0x8E,0x91,0x86,0x80,0x89,0x89,0x92,0x8B,0x8C,0x98,0x8E,0x8F, \
  325. 0x90,0x91,0x92,0x8C,0x99,0xA9,0x96,0x9D,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  326. 0x86,0x8B,0x9F,0x96,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  327. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  328. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  329. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  330. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  331. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  332. #define TBL_CT861 {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x8B,0x8B,0x8D,0x8E,0x8F, \
  333. 0x90,0x92,0x92,0x4F,0x99,0x8D,0x55,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
  334. 0xA4,0xA5,0xA6,0xA7,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  335. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  336. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  337. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  338. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  339. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  340. #define TBL_CT862 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  341. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  342. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  343. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  344. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  345. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  346. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  347. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  348. #define TBL_CT863 {0x43,0x55,0x45,0x41,0x41,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x41,0x8F, \
  349. 0x45,0x45,0x45,0x4F,0x45,0x49,0x55,0x55,0x98,0x4F,0x55,0x9B,0x9C,0x55,0x55,0x9F, \
  350. 0xA0,0xA1,0x4F,0x55,0xA4,0xA5,0xA6,0xA7,0x49,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  351. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  352. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  353. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  354. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  355. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  356. #define TBL_CT864 {0x80,0x9A,0x45,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  357. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  358. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  359. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  360. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  361. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  362. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  363. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  364. #define TBL_CT865 {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F, \
  365. 0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  366. 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  367. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  368. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  369. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  370. 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, \
  371. 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  372. #define TBL_CT866 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  373. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  374. 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  375. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  376. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  377. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
  378. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
  379. 0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
  380. #define TBL_CT869 {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, \
  381. 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x86,0x9C,0x8D,0x8F,0x90, \
  382. 0x91,0x90,0x92,0x95,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, \
  383. 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
  384. 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, \
  385. 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xA4,0xA5,0xA6,0xD9,0xDA,0xDB,0xDC,0xA7,0xA8,0xDF, \
  386. 0xA9,0xAA,0xAC,0xAD,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xCF,0xCF,0xD0,0xEF, \
  387. 0xF0,0xF1,0xD1,0xD2,0xD3,0xF5,0xD4,0xF7,0xF8,0xF9,0xD5,0x96,0x95,0x98,0xFE,0xFF}
  388. /* DBCS code range |----- 1st byte -----| |----------- 2nd byte -----------| */
  389. /* <------> <------> <------> <------> <------> */
  390. #define TBL_DC932 {0x81, 0x9F, 0xE0, 0xFC, 0x40, 0x7E, 0x80, 0xFC, 0x00, 0x00}
  391. #define TBL_DC936 {0x81, 0xFE, 0x00, 0x00, 0x40, 0x7E, 0x80, 0xFE, 0x00, 0x00}
  392. #define TBL_DC949 {0x81, 0xFE, 0x00, 0x00, 0x41, 0x5A, 0x61, 0x7A, 0x81, 0xFE}
  393. #define TBL_DC950 {0x81, 0xFE, 0x00, 0x00, 0x40, 0x7E, 0xA1, 0xFE, 0x00, 0x00}
  394. /* Macros for table definitions */
  395. #define MERGE_2STR(a, b) a ## b
  396. #define MKCVTBL(hd, cp) MERGE_2STR(hd, cp)
  397. /*--------------------------------------------------------------------------
  398. Module Private Work Area
  399. ---------------------------------------------------------------------------*/
  400. /* Remark: Variables defined here without initial value shall be guaranteed
  401. / zero/null at start-up. If not, the linker option or start-up routine is
  402. / not compliance with C standard. */
  403. /*--------------------------------*/
  404. /* File/Volume controls */
  405. /*--------------------------------*/
  406. #if FF_VOLUMES < 1 || FF_VOLUMES > 10
  407. #error Wrong FF_VOLUMES setting
  408. #endif
  409. static FATFS* FatFs[FF_VOLUMES]; /* Pointer to the filesystem objects (logical drives) */
  410. static WORD Fsid; /* Filesystem mount ID */
  411. #if FF_FS_RPATH != 0
  412. static BYTE CurrVol; /* Current drive */
  413. #endif
  414. #if FF_FS_LOCK != 0
  415. static FILESEM Files[FF_FS_LOCK]; /* Open object lock semaphores */
  416. #endif
  417. #if FF_STR_VOLUME_ID
  418. #ifdef FF_VOLUME_STRS
  419. static const char* const VolumeStr[FF_VOLUMES] = {FF_VOLUME_STRS}; /* Pre-defined volume ID */
  420. #endif
  421. #endif
  422. #if FF_LBA64
  423. #if FF_MIN_GPT > 0x100000000
  424. #error Wrong FF_MIN_GPT setting
  425. #endif
  426. static const BYTE GUID_MS_Basic[16] = {0xA2,0xA0,0xD0,0xEB,0xE5,0xB9,0x33,0x44,0x87,0xC0,0x68,0xB6,0xB7,0x26,0x99,0xC7};
  427. #endif
  428. /*--------------------------------*/
  429. /* LFN/Directory working buffer */
  430. /*--------------------------------*/
  431. #if FF_USE_LFN == 0 /* Non-LFN configuration */
  432. #if FF_FS_EXFAT
  433. #error LFN must be enabled when enable exFAT
  434. #endif
  435. #define DEF_NAMBUF
  436. #define INIT_NAMBUF(fs)
  437. #define FREE_NAMBUF()
  438. #define LEAVE_MKFS(res) return res
  439. #else /* LFN configurations */
  440. #if FF_MAX_LFN < 12 || FF_MAX_LFN > 255
  441. #error Wrong setting of FF_MAX_LFN
  442. #endif
  443. #if FF_LFN_BUF < FF_SFN_BUF || FF_SFN_BUF < 12
  444. #error Wrong setting of FF_LFN_BUF or FF_SFN_BUF
  445. #endif
  446. #if FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3
  447. #error Wrong setting of FF_LFN_UNICODE
  448. #endif
  449. static const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* FAT: Offset of LFN characters in the directory entry */
  450. #define MAXDIRB(nc) ((nc + 44U) / 15 * SZDIRE) /* exFAT: Size of directory entry block scratchpad buffer needed for the name length */
  451. #if FF_USE_LFN == 1 /* LFN enabled with static working buffer */
  452. #if FF_FS_EXFAT
  453. static BYTE DirBuf[MAXDIRB(FF_MAX_LFN)]; /* Directory entry block scratchpad buffer */
  454. #endif
  455. static WCHAR LfnBuf[FF_MAX_LFN + 1]; /* LFN working buffer */
  456. #define DEF_NAMBUF
  457. #define INIT_NAMBUF(fs)
  458. #define FREE_NAMBUF()
  459. #define LEAVE_MKFS(res) return res
  460. #elif FF_USE_LFN == 2 /* LFN enabled with dynamic working buffer on the stack */
  461. #if FF_FS_EXFAT
  462. #define DEF_NAMBUF WCHAR lbuf[FF_MAX_LFN+1]; BYTE dbuf[MAXDIRB(FF_MAX_LFN)]; /* LFN working buffer and directory entry block scratchpad buffer */
  463. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; (fs)->dirbuf = dbuf; }
  464. #define FREE_NAMBUF()
  465. #else
  466. #define DEF_NAMBUF WCHAR lbuf[FF_MAX_LFN+1]; /* LFN working buffer */
  467. #define INIT_NAMBUF(fs) { (fs)->lfnbuf = lbuf; }
  468. #define FREE_NAMBUF()
  469. #endif
  470. #define LEAVE_MKFS(res) return res
  471. #elif FF_USE_LFN == 3 /* LFN enabled with dynamic working buffer on the heap */
  472. #if FF_FS_EXFAT
  473. #define DEF_NAMBUF WCHAR *lfn; /* Pointer to LFN working buffer and directory entry block scratchpad buffer */
  474. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((FF_MAX_LFN+1)*2 + MAXDIRB(FF_MAX_LFN)); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; (fs)->dirbuf = (BYTE*)(lfn+FF_MAX_LFN+1); }
  475. #define FREE_NAMBUF() ff_memfree(lfn)
  476. #else
  477. #define DEF_NAMBUF WCHAR *lfn; /* Pointer to LFN working buffer */
  478. #define INIT_NAMBUF(fs) { lfn = ff_memalloc((FF_MAX_LFN+1)*2); if (!lfn) LEAVE_FF(fs, FR_NOT_ENOUGH_CORE); (fs)->lfnbuf = lfn; }
  479. #define FREE_NAMBUF() ff_memfree(lfn)
  480. #endif
  481. #define LEAVE_MKFS(res) { if (!work) ff_memfree(buf); return res; }
  482. #define MAX_MALLOC 0x8000 /* Must be >=FF_MAX_SS */
  483. #else
  484. #error Wrong setting of FF_USE_LFN
  485. #endif /* FF_USE_LFN == 1 */
  486. #endif /* FF_USE_LFN == 0 */
  487. /*--------------------------------*/
  488. /* Code conversion tables */
  489. /*--------------------------------*/
  490. #if FF_CODE_PAGE == 0 /* Run-time code page configuration */
  491. #define CODEPAGE CodePage
  492. static WORD CodePage; /* Current code page */
  493. static const BYTE *ExCvt, *DbcTbl; /* Pointer to current SBCS up-case table and DBCS code range table below */
  494. static const BYTE Ct437[] = TBL_CT437;
  495. static const BYTE Ct720[] = TBL_CT720;
  496. static const BYTE Ct737[] = TBL_CT737;
  497. static const BYTE Ct771[] = TBL_CT771;
  498. static const BYTE Ct775[] = TBL_CT775;
  499. static const BYTE Ct850[] = TBL_CT850;
  500. static const BYTE Ct852[] = TBL_CT852;
  501. static const BYTE Ct855[] = TBL_CT855;
  502. static const BYTE Ct857[] = TBL_CT857;
  503. static const BYTE Ct860[] = TBL_CT860;
  504. static const BYTE Ct861[] = TBL_CT861;
  505. static const BYTE Ct862[] = TBL_CT862;
  506. static const BYTE Ct863[] = TBL_CT863;
  507. static const BYTE Ct864[] = TBL_CT864;
  508. static const BYTE Ct865[] = TBL_CT865;
  509. static const BYTE Ct866[] = TBL_CT866;
  510. static const BYTE Ct869[] = TBL_CT869;
  511. static const BYTE Dc932[] = TBL_DC932;
  512. static const BYTE Dc936[] = TBL_DC936;
  513. static const BYTE Dc949[] = TBL_DC949;
  514. static const BYTE Dc950[] = TBL_DC950;
  515. #elif FF_CODE_PAGE < 900 /* Static code page configuration (SBCS) */
  516. #define CODEPAGE FF_CODE_PAGE
  517. static const BYTE ExCvt[] = MKCVTBL(TBL_CT, FF_CODE_PAGE);
  518. #else /* Static code page configuration (DBCS) */
  519. #define CODEPAGE FF_CODE_PAGE
  520. static const BYTE DbcTbl[] = MKCVTBL(TBL_DC, FF_CODE_PAGE);
  521. #endif
  522. /*--------------------------------------------------------------------------
  523. Module Private Functions
  524. ---------------------------------------------------------------------------*/
  525. /*-----------------------------------------------------------------------*/
  526. /* Load/Store multi-byte word in the FAT structure */
  527. /*-----------------------------------------------------------------------*/
  528. static WORD ld_word (const BYTE* ptr) /* Load a 2-byte little-endian word */
  529. {
  530. WORD rv;
  531. rv = ptr[1];
  532. rv = rv << 8 | ptr[0];
  533. return rv;
  534. }
  535. static DWORD ld_dword (const BYTE* ptr) /* Load a 4-byte little-endian word */
  536. {
  537. DWORD rv;
  538. rv = ptr[3];
  539. rv = rv << 8 | ptr[2];
  540. rv = rv << 8 | ptr[1];
  541. rv = rv << 8 | ptr[0];
  542. return rv;
  543. }
  544. #if FF_FS_EXFAT
  545. static QWORD ld_qword (const BYTE* ptr) /* Load an 8-byte little-endian word */
  546. {
  547. QWORD rv;
  548. rv = ptr[7];
  549. rv = rv << 8 | ptr[6];
  550. rv = rv << 8 | ptr[5];
  551. rv = rv << 8 | ptr[4];
  552. rv = rv << 8 | ptr[3];
  553. rv = rv << 8 | ptr[2];
  554. rv = rv << 8 | ptr[1];
  555. rv = rv << 8 | ptr[0];
  556. return rv;
  557. }
  558. #endif
  559. #if !FF_FS_READONLY
  560. static void st_word (BYTE* ptr, WORD val) /* Store a 2-byte word in little-endian */
  561. {
  562. *ptr++ = (BYTE)val; val >>= 8;
  563. *ptr++ = (BYTE)val;
  564. }
  565. static void st_dword (BYTE* ptr, DWORD val) /* Store a 4-byte word in little-endian */
  566. {
  567. *ptr++ = (BYTE)val; val >>= 8;
  568. *ptr++ = (BYTE)val; val >>= 8;
  569. *ptr++ = (BYTE)val; val >>= 8;
  570. *ptr++ = (BYTE)val;
  571. }
  572. #if FF_FS_EXFAT
  573. static void st_qword (BYTE* ptr, QWORD val) /* Store an 8-byte word in little-endian */
  574. {
  575. *ptr++ = (BYTE)val; val >>= 8;
  576. *ptr++ = (BYTE)val; val >>= 8;
  577. *ptr++ = (BYTE)val; val >>= 8;
  578. *ptr++ = (BYTE)val; val >>= 8;
  579. *ptr++ = (BYTE)val; val >>= 8;
  580. *ptr++ = (BYTE)val; val >>= 8;
  581. *ptr++ = (BYTE)val; val >>= 8;
  582. *ptr++ = (BYTE)val;
  583. }
  584. #endif
  585. #endif /* !FF_FS_READONLY */
  586. /*-----------------------------------------------------------------------*/
  587. /* String functions */
  588. /*-----------------------------------------------------------------------*/
  589. /* Test if the byte is DBC 1st byte */
  590. static int dbc_1st (BYTE c)
  591. {
  592. #if FF_CODE_PAGE == 0 /* Variable code page */
  593. if (DbcTbl && c >= DbcTbl[0]) {
  594. if (c <= DbcTbl[1]) return 1; /* 1st byte range 1 */
  595. if (c >= DbcTbl[2] && c <= DbcTbl[3]) return 1; /* 1st byte range 2 */
  596. }
  597. #elif FF_CODE_PAGE >= 900 /* DBCS fixed code page */
  598. if (c >= DbcTbl[0]) {
  599. if (c <= DbcTbl[1]) return 1;
  600. if (c >= DbcTbl[2] && c <= DbcTbl[3]) return 1;
  601. }
  602. #else /* SBCS fixed code page */
  603. if (c != 0) return 0; /* Always false */
  604. #endif
  605. return 0;
  606. }
  607. /* Test if the byte is DBC 2nd byte */
  608. static int dbc_2nd (BYTE c)
  609. {
  610. #if FF_CODE_PAGE == 0 /* Variable code page */
  611. if (DbcTbl && c >= DbcTbl[4]) {
  612. if (c <= DbcTbl[5]) return 1; /* 2nd byte range 1 */
  613. if (c >= DbcTbl[6] && c <= DbcTbl[7]) return 1; /* 2nd byte range 2 */
  614. if (c >= DbcTbl[8] && c <= DbcTbl[9]) return 1; /* 2nd byte range 3 */
  615. }
  616. #elif FF_CODE_PAGE >= 900 /* DBCS fixed code page */
  617. if (c >= DbcTbl[4]) {
  618. if (c <= DbcTbl[5]) return 1;
  619. if (c >= DbcTbl[6] && c <= DbcTbl[7]) return 1;
  620. if (c >= DbcTbl[8] && c <= DbcTbl[9]) return 1;
  621. }
  622. #else /* SBCS fixed code page */
  623. if (c != 0) return 0; /* Always false */
  624. #endif
  625. return 0;
  626. }
  627. #if FF_USE_LFN
  628. /* Get a Unicode code point from the FATFS_TCHAR string in defined API encodeing */
  629. static DWORD tchar2uni ( /* Returns a character in UTF-16 encoding (>=0x10000 on surrogate pair, 0xFFFFFFFF on decode error) */
  630. const FATFS_TCHAR** str /* Pointer to pointer to FATFS_TCHAR string in configured encoding */
  631. )
  632. {
  633. DWORD uc;
  634. const FATFS_TCHAR *p = *str;
  635. #if FF_LFN_UNICODE == 1 /* UTF-16 input */
  636. WCHAR wc;
  637. uc = *p++; /* Get a unit */
  638. if (IsSurrogate(uc)) { /* Surrogate? */
  639. wc = *p++; /* Get low surrogate */
  640. if (!IsSurrogateH(uc) || !IsSurrogateL(wc)) return 0xFFFFFFFF; /* Wrong surrogate? */
  641. uc = uc << 16 | wc;
  642. }
  643. #elif FF_LFN_UNICODE == 2 /* UTF-8 input */
  644. BYTE b;
  645. int nf;
  646. uc = (BYTE)*p++; /* Get an encoding unit */
  647. if (uc & 0x80) { /* Multiple byte code? */
  648. if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */
  649. uc &= 0x1F; nf = 1;
  650. } else if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */
  651. uc &= 0x0F; nf = 2;
  652. } else if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */
  653. uc &= 0x07; nf = 3;
  654. } else { /* Wrong sequence */
  655. return 0xFFFFFFFF;
  656. }
  657. do { /* Get trailing bytes */
  658. b = (BYTE)*p++;
  659. if ((b & 0xC0) != 0x80) return 0xFFFFFFFF; /* Wrong sequence? */
  660. uc = uc << 6 | (b & 0x3F);
  661. } while (--nf != 0);
  662. if (uc < 0x80 || IsSurrogate(uc) || uc >= 0x110000) return 0xFFFFFFFF; /* Wrong code? */
  663. if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */
  664. }
  665. #elif FF_LFN_UNICODE == 3 /* UTF-32 input */
  666. uc = (FATFS_TCHAR)*p++; /* Get a unit */
  667. if (uc >= 0x110000 || IsSurrogate(uc)) return 0xFFFFFFFF; /* Wrong code? */
  668. if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */
  669. #else /* ANSI/OEM input */
  670. BYTE b;
  671. WCHAR wc;
  672. wc = (BYTE)*p++; /* Get a byte */
  673. if (dbc_1st((BYTE)wc)) { /* Is it a DBC 1st byte? */
  674. b = (BYTE)*p++; /* Get 2nd byte */
  675. if (!dbc_2nd(b)) return 0xFFFFFFFF; /* Invalid code? */
  676. wc = (wc << 8) + b; /* Make a DBC */
  677. }
  678. if (wc != 0) {
  679. wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM ==> Unicode */
  680. if (wc == 0) return 0xFFFFFFFF; /* Invalid code? */
  681. }
  682. uc = wc;
  683. #endif
  684. *str = p; /* Next read pointer */
  685. return uc;
  686. }
  687. /* Store a Unicode char in defined API encoding */
  688. static UINT put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */
  689. DWORD chr, /* UTF-16 encoded character (Surrogate pair if >=0x10000) */
  690. FATFS_TCHAR* buf, /* Output buffer */
  691. UINT szb /* Size of the buffer */
  692. )
  693. {
  694. #if FF_LFN_UNICODE == 1 /* UTF-16 output */
  695. WCHAR hs, wc;
  696. hs = (WCHAR)(chr >> 16);
  697. wc = (WCHAR)chr;
  698. if (hs == 0) { /* Single encoding unit? */
  699. if (szb < 1 || IsSurrogate(wc)) return 0; /* Buffer overflow or wrong code? */
  700. *buf = wc;
  701. return 1;
  702. }
  703. if (szb < 2 || !IsSurrogateH(hs) || !IsSurrogateL(wc)) return 0; /* Buffer overflow or wrong surrogate? */
  704. *buf++ = hs;
  705. *buf++ = wc;
  706. return 2;
  707. #elif FF_LFN_UNICODE == 2 /* UTF-8 output */
  708. DWORD hc;
  709. if (chr < 0x80) { /* Single byte code? */
  710. if (szb < 1) return 0; /* Buffer overflow? */
  711. *buf = (FATFS_TCHAR)chr;
  712. return 1;
  713. }
  714. if (chr < 0x800) { /* 2-byte sequence? */
  715. if (szb < 2) return 0; /* Buffer overflow? */
  716. *buf++ = (FATFS_TCHAR)(0xC0 | (chr >> 6 & 0x1F));
  717. *buf++ = (FATFS_TCHAR)(0x80 | (chr >> 0 & 0x3F));
  718. return 2;
  719. }
  720. if (chr < 0x10000) { /* 3-byte sequence? */
  721. if (szb < 3 || IsSurrogate(chr)) return 0; /* Buffer overflow or wrong code? */
  722. *buf++ = (FATFS_TCHAR)(0xE0 | (chr >> 12 & 0x0F));
  723. *buf++ = (FATFS_TCHAR)(0x80 | (chr >> 6 & 0x3F));
  724. *buf++ = (FATFS_TCHAR)(0x80 | (chr >> 0 & 0x3F));
  725. return 3;
  726. }
  727. /* 4-byte sequence */
  728. if (szb < 4) return 0; /* Buffer overflow? */
  729. hc = ((chr & 0xFFFF0000) - 0xD8000000) >> 6; /* Get high 10 bits */
  730. chr = (chr & 0xFFFF) - 0xDC00; /* Get low 10 bits */
  731. if (hc >= 0x100000 || chr >= 0x400) return 0; /* Wrong surrogate? */
  732. chr = (hc | chr) + 0x10000;
  733. *buf++ = (FATFS_TCHAR)(0xF0 | (chr >> 18 & 0x07));
  734. *buf++ = (FATFS_TCHAR)(0x80 | (chr >> 12 & 0x3F));
  735. *buf++ = (FATFS_TCHAR)(0x80 | (chr >> 6 & 0x3F));
  736. *buf++ = (FATFS_TCHAR)(0x80 | (chr >> 0 & 0x3F));
  737. return 4;
  738. #elif FF_LFN_UNICODE == 3 /* UTF-32 output */
  739. DWORD hc;
  740. if (szb < 1) return 0; /* Buffer overflow? */
  741. if (chr >= 0x10000) { /* Out of BMP? */
  742. hc = ((chr & 0xFFFF0000) - 0xD8000000) >> 6; /* Get high 10 bits */
  743. chr = (chr & 0xFFFF) - 0xDC00; /* Get low 10 bits */
  744. if (hc >= 0x100000 || chr >= 0x400) return 0; /* Wrong surrogate? */
  745. chr = (hc | chr) + 0x10000;
  746. }
  747. *buf++ = (FATFS_TCHAR)chr;
  748. return 1;
  749. #else /* ANSI/OEM output */
  750. WCHAR wc;
  751. wc = ff_uni2oem(chr, CODEPAGE);
  752. if (wc >= 0x100) { /* Is this a DBC? */
  753. if (szb < 2) return 0;
  754. *buf++ = (char)(wc >> 8); /* Store DBC 1st byte */
  755. *buf++ = (FATFS_TCHAR)wc; /* Store DBC 2nd byte */
  756. return 2;
  757. }
  758. if (wc == 0 || szb < 1) return 0; /* Invalid char or buffer overflow? */
  759. *buf++ = (FATFS_TCHAR)wc; /* Store the character */
  760. return 1;
  761. #endif
  762. }
  763. #endif /* FF_USE_LFN */
  764. #if FF_FS_REENTRANT
  765. /*-----------------------------------------------------------------------*/
  766. /* Request/Release grant to access the volume */
  767. /*-----------------------------------------------------------------------*/
  768. static int lock_fs ( /* 1:Ok, 0:timeout */
  769. FATFS* fs /* Filesystem object */
  770. )
  771. {
  772. return ff_req_grant(fs->sobj);
  773. }
  774. static void unlock_fs (
  775. FATFS* fs, /* Filesystem object */
  776. FRESULT res /* Result code to be returned */
  777. )
  778. {
  779. if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {
  780. ff_rel_grant(fs->sobj);
  781. }
  782. }
  783. #endif
  784. #if FF_FS_LOCK != 0
  785. /*-----------------------------------------------------------------------*/
  786. /* File lock control functions */
  787. /*-----------------------------------------------------------------------*/
  788. static FRESULT chk_lock ( /* Check if the file can be accessed */
  789. DIR* dp, /* Directory object pointing the file to be checked */
  790. int acc /* Desired access type (0:Read mode open, 1:Write mode open, 2:Delete or rename) */
  791. )
  792. {
  793. UINT i, be;
  794. /* Search open object table for the object */
  795. be = 0;
  796. for (i = 0; i < FF_FS_LOCK; i++) {
  797. if (Files[i].fs) { /* Existing entry */
  798. if (Files[i].fs == dp->obj.fs && /* Check if the object matches with an open object */
  799. Files[i].clu == dp->obj.sclust &&
  800. Files[i].ofs == dp->dptr) break;
  801. } else { /* Blank entry */
  802. be = 1;
  803. }
  804. }
  805. if (i == FF_FS_LOCK) { /* The object has not been opened */
  806. return (!be && acc != 2) ? FR_TOO_MANY_OPEN_FILES : FR_OK; /* Is there a blank entry for new object? */
  807. }
  808. /* The object was opened. Reject any open against writing file and all write mode open */
  809. return (acc != 0 || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
  810. }
  811. static int enq_lock (void) /* Check if an entry is available for a new object */
  812. {
  813. UINT i;
  814. for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ;
  815. return (i == FF_FS_LOCK) ? 0 : 1;
  816. }
  817. static UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */
  818. DIR* dp, /* Directory object pointing the file to register or increment */
  819. int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
  820. )
  821. {
  822. UINT i;
  823. for (i = 0; i < FF_FS_LOCK; i++) { /* Find the object */
  824. if (Files[i].fs == dp->obj.fs
  825. && Files[i].clu == dp->obj.sclust
  826. && Files[i].ofs == dp->dptr) break;
  827. }
  828. if (i == FF_FS_LOCK) { /* Not opened. Register it as new. */
  829. for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ;
  830. if (i == FF_FS_LOCK) return 0; /* No free entry to register (int err) */
  831. Files[i].fs = dp->obj.fs;
  832. Files[i].clu = dp->obj.sclust;
  833. Files[i].ofs = dp->dptr;
  834. Files[i].ctr = 0;
  835. }
  836. if (acc >= 1 && Files[i].ctr) return 0; /* Access violation (int err) */
  837. Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1; /* Set semaphore value */
  838. return i + 1; /* Index number origin from 1 */
  839. }
  840. static FRESULT dec_lock ( /* Decrement object open counter */
  841. UINT i /* Semaphore index (1..) */
  842. )
  843. {
  844. WORD n;
  845. FRESULT res;
  846. if (--i < FF_FS_LOCK) { /* Index number origin from 0 */
  847. n = Files[i].ctr;
  848. if (n == 0x100) n = 0; /* If write mode open, delete the entry */
  849. if (n > 0) n--; /* Decrement read mode open count */
  850. Files[i].ctr = n;
  851. if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */
  852. res = FR_OK;
  853. } else {
  854. res = FR_INT_ERR; /* Invalid index nunber */
  855. }
  856. return res;
  857. }
  858. static void clear_lock ( /* Clear lock entries of the volume */
  859. FATFS *fs
  860. )
  861. {
  862. UINT i;
  863. for (i = 0; i < FF_FS_LOCK; i++) {
  864. if (Files[i].fs == fs) Files[i].fs = 0;
  865. }
  866. }
  867. #endif /* FF_FS_LOCK != 0 */
  868. /*-----------------------------------------------------------------------*/
  869. /* Move/Flush disk access window in the filesystem object */
  870. /*-----------------------------------------------------------------------*/
  871. #if !FF_FS_READONLY
  872. static FRESULT sync_window ( /* Returns FR_OK or FR_DISK_ERR */
  873. FATFS* fs /* Filesystem object */
  874. )
  875. {
  876. FRESULT res = FR_OK;
  877. if (fs->wflag) { /* Is the disk access window dirty? */
  878. if (disk_write(fs->pdrv, fs->win, fs->winsect, 1) == RES_OK) { /* Write it back into the volume */
  879. fs->wflag = 0; /* Clear window dirty flag */
  880. if (fs->winsect - fs->fatbase < fs->fsize) { /* Is it in the 1st FAT? */
  881. if (fs->n_fats == 2) disk_write(fs->pdrv, fs->win, fs->winsect + fs->fsize, 1); /* Reflect it to 2nd FAT if needed */
  882. }
  883. } else {
  884. res = FR_DISK_ERR;
  885. }
  886. }
  887. return res;
  888. }
  889. #endif
  890. static FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERR */
  891. FATFS* fs, /* Filesystem object */
  892. LBA_t sect /* Sector LBA to make appearance in the fs->win[] */
  893. )
  894. {
  895. FRESULT res = FR_OK;
  896. if (sect != fs->winsect) { /* Window offset changed? */
  897. #if !FF_FS_READONLY
  898. res = sync_window(fs); /* Flush the window */
  899. #endif
  900. if (res == FR_OK) { /* Fill sector window with new data */
  901. if (disk_read(fs->pdrv, fs->win, sect, 1) != RES_OK) {
  902. sect = (LBA_t)0 - 1; /* Invalidate window if read data is not valid */
  903. res = FR_DISK_ERR;
  904. }
  905. fs->winsect = sect;
  906. }
  907. }
  908. return res;
  909. }
  910. #if !FF_FS_READONLY
  911. /*-----------------------------------------------------------------------*/
  912. /* Synchronize filesystem and data on the storage */
  913. /*-----------------------------------------------------------------------*/
  914. static FRESULT sync_fs ( /* Returns FR_OK or FR_DISK_ERR */
  915. FATFS* fs /* Filesystem object */
  916. )
  917. {
  918. FRESULT res;
  919. res = sync_window(fs);
  920. if (res == FR_OK) {
  921. if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) { /* FAT32: Update FSInfo sector if needed */
  922. /* Create FSInfo structure */
  923. memset(fs->win, 0, sizeof fs->win);
  924. st_word(fs->win + BS_55AA, 0xAA55); /* Boot signature */
  925. st_dword(fs->win + FSI_LeadSig, 0x41615252); /* Leading signature */
  926. st_dword(fs->win + FSI_StrucSig, 0x61417272); /* Structure signature */
  927. st_dword(fs->win + FSI_Free_Count, fs->free_clst); /* Number of free clusters */
  928. st_dword(fs->win + FSI_Nxt_Free, fs->last_clst); /* Last allocated culuster */
  929. fs->winsect = fs->volbase + 1; /* Write it into the FSInfo sector (Next to VBR) */
  930. disk_write(fs->pdrv, fs->win, fs->winsect, 1);
  931. fs->fsi_flag = 0;
  932. }
  933. /* Make sure that no pending write process in the lower layer */
  934. if (disk_ioctl(fs->pdrv, CTRL_SYNC, 0) != RES_OK) res = FR_DISK_ERR;
  935. }
  936. return res;
  937. }
  938. #endif
  939. /*-----------------------------------------------------------------------*/
  940. /* Get physical sector number from cluster number */
  941. /*-----------------------------------------------------------------------*/
  942. static LBA_t clst2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */
  943. FATFS* fs, /* Filesystem object */
  944. DWORD clst /* Cluster# to be converted */
  945. )
  946. {
  947. clst -= 2; /* Cluster number is origin from 2 */
  948. if (clst >= fs->n_fatent - 2) return 0; /* Is it invalid cluster number? */
  949. return fs->database + (LBA_t)fs->csize * clst; /* Start sector number of the cluster */
  950. }
  951. /*-----------------------------------------------------------------------*/
  952. /* FAT access - Read value of an FAT entry */
  953. /*-----------------------------------------------------------------------*/
  954. static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */
  955. FFOBJID* obj, /* Corresponding object */
  956. DWORD clst /* Cluster number to get the value */
  957. )
  958. {
  959. UINT wc, bc;
  960. DWORD val;
  961. FATFS *fs = obj->fs;
  962. if (clst < 2 || clst >= fs->n_fatent) { /* Check if in valid range */
  963. val = 1; /* Internal error */
  964. } else {
  965. val = 0xFFFFFFFF; /* Default value falls on disk error */
  966. switch (fs->fs_type) {
  967. case FS_FAT12 :
  968. bc = (UINT)clst; bc += bc / 2;
  969. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  970. wc = fs->win[bc++ % SS(fs)]; /* Get 1st byte of the entry */
  971. if (move_window(fs, fs->fatbase + (bc / SS(fs))) != FR_OK) break;
  972. wc |= fs->win[bc % SS(fs)] << 8; /* Merge 2nd byte of the entry */
  973. val = (clst & 1) ? (wc >> 4) : (wc & 0xFFF); /* Adjust bit position */
  974. break;
  975. case FS_FAT16 :
  976. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2))) != FR_OK) break;
  977. val = ld_word(fs->win + clst * 2 % SS(fs)); /* Simple WORD array */
  978. break;
  979. case FS_FAT32 :
  980. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  981. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x0FFFFFFF; /* Simple DWORD array but mask out upper 4 bits */
  982. break;
  983. #if FF_FS_EXFAT
  984. case FS_EXFAT :
  985. if ((obj->objsize != 0 && obj->sclust != 0) || obj->stat == 0) { /* Object except root dir must have valid data length */
  986. DWORD cofs = clst - obj->sclust; /* Offset from start cluster */
  987. DWORD clen = (DWORD)((LBA_t)((obj->objsize - 1) / SS(fs)) / fs->csize); /* Number of clusters - 1 */
  988. if (obj->stat == 2 && cofs <= clen) { /* Is it a contiguous chain? */
  989. val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* No data on the FAT, generate the value */
  990. break;
  991. }
  992. if (obj->stat == 3 && cofs < obj->n_cont) { /* Is it in the 1st fragment? */
  993. val = clst + 1; /* Generate the value */
  994. break;
  995. }
  996. if (obj->stat != 2) { /* Get value from FAT if FAT chain is valid */
  997. if (obj->n_frag != 0) { /* Is it on the growing edge? */
  998. val = 0x7FFFFFFF; /* Generate EOC */
  999. } else {
  1000. if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4))) != FR_OK) break;
  1001. val = ld_dword(fs->win + clst * 4 % SS(fs)) & 0x7FFFFFFF;
  1002. }
  1003. break;
  1004. }
  1005. }
  1006. val = 1; /* Internal error */
  1007. break;
  1008. #endif
  1009. default:
  1010. val = 1; /* Internal error */
  1011. }
  1012. }
  1013. return val;
  1014. }
  1015. #if !FF_FS_READONLY
  1016. /*-----------------------------------------------------------------------*/
  1017. /* FAT access - Change value of an FAT entry */
  1018. /*-----------------------------------------------------------------------*/
  1019. static FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */
  1020. FATFS* fs, /* Corresponding filesystem object */
  1021. DWORD clst, /* FAT index number (cluster number) to be changed */
  1022. DWORD val /* New value to be set to the entry */
  1023. )
  1024. {
  1025. UINT bc;
  1026. BYTE *p;
  1027. FRESULT res = FR_INT_ERR;
  1028. if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */
  1029. switch (fs->fs_type) {
  1030. case FS_FAT12:
  1031. bc = (UINT)clst; bc += bc / 2; /* bc: byte offset of the entry */
  1032. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  1033. if (res != FR_OK) break;
  1034. p = fs->win + bc++ % SS(fs);
  1035. *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Update 1st byte */
  1036. fs->wflag = 1;
  1037. res = move_window(fs, fs->fatbase + (bc / SS(fs)));
  1038. if (res != FR_OK) break;
  1039. p = fs->win + bc % SS(fs);
  1040. *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); /* Update 2nd byte */
  1041. fs->wflag = 1;
  1042. break;
  1043. case FS_FAT16:
  1044. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
  1045. if (res != FR_OK) break;
  1046. st_word(fs->win + clst * 2 % SS(fs), (WORD)val); /* Simple WORD array */
  1047. fs->wflag = 1;
  1048. break;
  1049. case FS_FAT32:
  1050. #if FF_FS_EXFAT
  1051. case FS_EXFAT:
  1052. #endif
  1053. res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
  1054. if (res != FR_OK) break;
  1055. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1056. val = (val & 0x0FFFFFFF) | (ld_dword(fs->win + clst * 4 % SS(fs)) & 0xF0000000);
  1057. }
  1058. st_dword(fs->win + clst * 4 % SS(fs), val);
  1059. fs->wflag = 1;
  1060. break;
  1061. }
  1062. }
  1063. return res;
  1064. }
  1065. #endif /* !FF_FS_READONLY */
  1066. #if FF_FS_EXFAT && !FF_FS_READONLY
  1067. /*-----------------------------------------------------------------------*/
  1068. /* exFAT: Accessing FAT and Allocation Bitmap */
  1069. /*-----------------------------------------------------------------------*/
  1070. /*--------------------------------------*/
  1071. /* Find a contiguous free cluster block */
  1072. /*--------------------------------------*/
  1073. static DWORD find_bitmap ( /* 0:Not found, 2..:Cluster block found, 0xFFFFFFFF:Disk error */
  1074. FATFS* fs, /* Filesystem object */
  1075. DWORD clst, /* Cluster number to scan from */
  1076. DWORD ncl /* Number of contiguous clusters to find (1..) */
  1077. )
  1078. {
  1079. BYTE bm, bv;
  1080. UINT i;
  1081. DWORD val, scl, ctr;
  1082. clst -= 2; /* The first bit in the bitmap corresponds to cluster #2 */
  1083. if (clst >= fs->n_fatent - 2) clst = 0;
  1084. scl = val = clst; ctr = 0;
  1085. for (;;) {
  1086. if (move_window(fs, fs->bitbase + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF;
  1087. i = val / 8 % SS(fs); bm = 1 << (val % 8);
  1088. do {
  1089. do {
  1090. bv = fs->win[i] & bm; bm <<= 1; /* Get bit value */
  1091. if (++val >= fs->n_fatent - 2) { /* Next cluster (with wrap-around) */
  1092. val = 0; bm = 0; i = SS(fs);
  1093. }
  1094. if (bv == 0) { /* Is it a free cluster? */
  1095. if (++ctr == ncl) return scl + 2; /* Check if run length is sufficient for required */
  1096. } else {
  1097. scl = val; ctr = 0; /* Encountered a cluster in-use, restart to scan */
  1098. }
  1099. if (val == clst) return 0; /* All cluster scanned? */
  1100. } while (bm != 0);
  1101. bm = 1;
  1102. } while (++i < SS(fs));
  1103. }
  1104. }
  1105. /*----------------------------------------*/
  1106. /* Set/Clear a block of allocation bitmap */
  1107. /*----------------------------------------*/
  1108. static FRESULT change_bitmap (
  1109. FATFS* fs, /* Filesystem object */
  1110. DWORD clst, /* Cluster number to change from */
  1111. DWORD ncl, /* Number of clusters to be changed */
  1112. int bv /* bit value to be set (0 or 1) */
  1113. )
  1114. {
  1115. BYTE bm;
  1116. UINT i;
  1117. LBA_t sect;
  1118. clst -= 2; /* The first bit corresponds to cluster #2 */
  1119. sect = fs->bitbase + clst / 8 / SS(fs); /* Sector address */
  1120. i = clst / 8 % SS(fs); /* Byte offset in the sector */
  1121. bm = 1 << (clst % 8); /* Bit mask in the byte */
  1122. for (;;) {
  1123. if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;
  1124. do {
  1125. do {
  1126. if (bv == (int)((fs->win[i] & bm) != 0)) return FR_INT_ERR; /* Is the bit expected value? */
  1127. fs->win[i] ^= bm; /* Flip the bit */
  1128. fs->wflag = 1;
  1129. if (--ncl == 0) return FR_OK; /* All bits processed? */
  1130. } while (bm <<= 1); /* Next bit */
  1131. bm = 1;
  1132. } while (++i < SS(fs)); /* Next byte */
  1133. i = 0;
  1134. }
  1135. }
  1136. /*---------------------------------------------*/
  1137. /* Fill the first fragment of the FAT chain */
  1138. /*---------------------------------------------*/
  1139. static FRESULT fill_first_frag (
  1140. FFOBJID* obj /* Pointer to the corresponding object */
  1141. )
  1142. {
  1143. FRESULT res;
  1144. DWORD cl, n;
  1145. if (obj->stat == 3) { /* Has the object been changed 'fragmented' in this session? */
  1146. for (cl = obj->sclust, n = obj->n_cont; n; cl++, n--) { /* Create cluster chain on the FAT */
  1147. res = put_fat(obj->fs, cl, cl + 1);
  1148. if (res != FR_OK) return res;
  1149. }
  1150. obj->stat = 0; /* Change status 'FAT chain is valid' */
  1151. }
  1152. return FR_OK;
  1153. }
  1154. /*---------------------------------------------*/
  1155. /* Fill the last fragment of the FAT chain */
  1156. /*---------------------------------------------*/
  1157. static FRESULT fill_last_frag (
  1158. FFOBJID* obj, /* Pointer to the corresponding object */
  1159. DWORD lcl, /* Last cluster of the fragment */
  1160. DWORD term /* Value to set the last FAT entry */
  1161. )
  1162. {
  1163. FRESULT res;
  1164. while (obj->n_frag > 0) { /* Create the chain of last fragment */
  1165. res = put_fat(obj->fs, lcl - obj->n_frag + 1, (obj->n_frag > 1) ? lcl - obj->n_frag + 2 : term);
  1166. if (res != FR_OK) return res;
  1167. obj->n_frag--;
  1168. }
  1169. return FR_OK;
  1170. }
  1171. #endif /* FF_FS_EXFAT && !FF_FS_READONLY */
  1172. #if !FF_FS_READONLY
  1173. /*-----------------------------------------------------------------------*/
  1174. /* FAT handling - Remove a cluster chain */
  1175. /*-----------------------------------------------------------------------*/
  1176. static FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */
  1177. FFOBJID* obj, /* Corresponding object */
  1178. DWORD clst, /* Cluster to remove a chain from */
  1179. DWORD pclst /* Previous cluster of clst (0 if entire chain) */
  1180. )
  1181. {
  1182. FRESULT res = FR_OK;
  1183. DWORD nxt;
  1184. FATFS *fs = obj->fs;
  1185. #if FF_FS_EXFAT || FF_USE_TRIM
  1186. DWORD scl = clst, ecl = clst;
  1187. #endif
  1188. #if FF_USE_TRIM
  1189. LBA_t rt[2];
  1190. #endif
  1191. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */
  1192. /* Mark the previous cluster 'EOC' on the FAT if it exists */
  1193. if (pclst != 0 && (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT || obj->stat != 2)) {
  1194. res = put_fat(fs, pclst, 0xFFFFFFFF);
  1195. if (res != FR_OK) return res;
  1196. }
  1197. /* Remove the chain */
  1198. do {
  1199. nxt = get_fat(obj, clst); /* Get cluster status */
  1200. if (nxt == 0) break; /* Empty cluster? */
  1201. if (nxt == 1) return FR_INT_ERR; /* Internal error? */
  1202. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error? */
  1203. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) {
  1204. res = put_fat(fs, clst, 0); /* Mark the cluster 'free' on the FAT */
  1205. if (res != FR_OK) return res;
  1206. }
  1207. if (fs->free_clst < fs->n_fatent - 2) { /* Update FSINFO */
  1208. fs->free_clst++;
  1209. fs->fsi_flag |= 1;
  1210. }
  1211. #if FF_FS_EXFAT || FF_USE_TRIM
  1212. if (ecl + 1 == nxt) { /* Is next cluster contiguous? */
  1213. ecl = nxt;
  1214. } else { /* End of contiguous cluster block */
  1215. #if FF_FS_EXFAT
  1216. if (fs->fs_type == FS_EXFAT) {
  1217. res = change_bitmap(fs, scl, ecl - scl + 1, 0); /* Mark the cluster block 'free' on the bitmap */
  1218. if (res != FR_OK) return res;
  1219. }
  1220. #endif
  1221. #if FF_USE_TRIM
  1222. rt[0] = clst2sect(fs, scl); /* Start of data area to be freed */
  1223. rt[1] = clst2sect(fs, ecl) + fs->csize - 1; /* End of data area to be freed */
  1224. disk_ioctl(fs->pdrv, CTRL_TRIM, rt); /* Inform storage device that the data in the block may be erased */
  1225. #endif
  1226. scl = ecl = nxt;
  1227. }
  1228. #endif
  1229. clst = nxt; /* Next cluster */
  1230. } while (clst < fs->n_fatent); /* Repeat while not the last link */
  1231. #if FF_FS_EXFAT
  1232. /* Some post processes for chain status */
  1233. if (fs->fs_type == FS_EXFAT) {
  1234. if (pclst == 0) { /* Has the entire chain been removed? */
  1235. obj->stat = 0; /* Change the chain status 'initial' */
  1236. } else {
  1237. if (obj->stat == 0) { /* Is it a fragmented chain from the beginning of this session? */
  1238. clst = obj->sclust; /* Follow the chain to check if it gets contiguous */
  1239. while (clst != pclst) {
  1240. nxt = get_fat(obj, clst);
  1241. if (nxt < 2) return FR_INT_ERR;
  1242. if (nxt == 0xFFFFFFFF) return FR_DISK_ERR;
  1243. if (nxt != clst + 1) break; /* Not contiguous? */
  1244. clst++;
  1245. }
  1246. if (clst == pclst) { /* Has the chain got contiguous again? */
  1247. obj->stat = 2; /* Change the chain status 'contiguous' */
  1248. }
  1249. } else {
  1250. if (obj->stat == 3 && pclst >= obj->sclust && pclst <= obj->sclust + obj->n_cont) { /* Was the chain fragmented in this session and got contiguous again? */
  1251. obj->stat = 2; /* Change the chain status 'contiguous' */
  1252. }
  1253. }
  1254. }
  1255. }
  1256. #endif
  1257. return FR_OK;
  1258. }
  1259. /*-----------------------------------------------------------------------*/
  1260. /* FAT handling - Stretch a chain or Create a new chain */
  1261. /*-----------------------------------------------------------------------*/
  1262. static DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
  1263. FFOBJID* obj, /* Corresponding object */
  1264. DWORD clst /* Cluster# to stretch, 0:Create a new chain */
  1265. )
  1266. {
  1267. DWORD cs, ncl, scl;
  1268. FRESULT res;
  1269. FATFS *fs = obj->fs;
  1270. if (clst == 0) { /* Create a new chain */
  1271. scl = fs->last_clst; /* Suggested cluster to start to find */
  1272. if (scl == 0 || scl >= fs->n_fatent) scl = 1;
  1273. }
  1274. else { /* Stretch a chain */
  1275. cs = get_fat(obj, clst); /* Check the cluster status */
  1276. if (cs < 2) return 1; /* Test for insanity */
  1277. if (cs == 0xFFFFFFFF) return cs; /* Test for disk error */
  1278. if (cs < fs->n_fatent) return cs; /* It is already followed by next cluster */
  1279. scl = clst; /* Cluster to start to find */
  1280. }
  1281. if (fs->free_clst == 0) return 0; /* No free cluster */
  1282. #if FF_FS_EXFAT
  1283. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1284. ncl = find_bitmap(fs, scl, 1); /* Find a free cluster */
  1285. if (ncl == 0 || ncl == 0xFFFFFFFF) return ncl; /* No free cluster or hard error? */
  1286. res = change_bitmap(fs, ncl, 1, 1); /* Mark the cluster 'in use' */
  1287. if (res == FR_INT_ERR) return 1;
  1288. if (res == FR_DISK_ERR) return 0xFFFFFFFF;
  1289. if (clst == 0) { /* Is it a new chain? */
  1290. obj->stat = 2; /* Set status 'contiguous' */
  1291. } else { /* It is a stretched chain */
  1292. if (obj->stat == 2 && ncl != scl + 1) { /* Is the chain got fragmented? */
  1293. obj->n_cont = scl - obj->sclust; /* Set size of the contiguous part */
  1294. obj->stat = 3; /* Change status 'just fragmented' */
  1295. }
  1296. }
  1297. if (obj->stat != 2) { /* Is the file non-contiguous? */
  1298. if (ncl == clst + 1) { /* Is the cluster next to previous one? */
  1299. obj->n_frag = obj->n_frag ? obj->n_frag + 1 : 2; /* Increment size of last framgent */
  1300. } else { /* New fragment */
  1301. if (obj->n_frag == 0) obj->n_frag = 1;
  1302. res = fill_last_frag(obj, clst, ncl); /* Fill last fragment on the FAT and link it to new one */
  1303. if (res == FR_OK) obj->n_frag = 1;
  1304. }
  1305. }
  1306. } else
  1307. #endif
  1308. { /* On the FAT/FAT32 volume */
  1309. ncl = 0;
  1310. if (scl == clst) { /* Stretching an existing chain? */
  1311. ncl = scl + 1; /* Test if next cluster is free */
  1312. if (ncl >= fs->n_fatent) ncl = 2;
  1313. cs = get_fat(obj, ncl); /* Get next cluster status */
  1314. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* Test for error */
  1315. if (cs != 0) { /* Not free? */
  1316. cs = fs->last_clst; /* Start at suggested cluster if it is valid */
  1317. if (cs >= 2 && cs < fs->n_fatent) scl = cs;
  1318. ncl = 0;
  1319. }
  1320. }
  1321. if (ncl == 0) { /* The new cluster cannot be contiguous and find another fragment */
  1322. ncl = scl; /* Start cluster */
  1323. for (;;) {
  1324. ncl++; /* Next cluster */
  1325. if (ncl >= fs->n_fatent) { /* Check wrap-around */
  1326. ncl = 2;
  1327. if (ncl > scl) return 0; /* No free cluster found? */
  1328. }
  1329. cs = get_fat(obj, ncl); /* Get the cluster status */
  1330. if (cs == 0) break; /* Found a free cluster? */
  1331. if (cs == 1 || cs == 0xFFFFFFFF) return cs; /* Test for error */
  1332. if (ncl == scl) return 0; /* No free cluster found? */
  1333. }
  1334. }
  1335. res = put_fat(fs, ncl, 0xFFFFFFFF); /* Mark the new cluster 'EOC' */
  1336. if (res == FR_OK && clst != 0) {
  1337. res = put_fat(fs, clst, ncl); /* Link it from the previous one if needed */
  1338. }
  1339. }
  1340. if (res == FR_OK) { /* Update FSINFO if function succeeded. */
  1341. fs->last_clst = ncl;
  1342. if (fs->free_clst <= fs->n_fatent - 2) fs->free_clst--;
  1343. fs->fsi_flag |= 1;
  1344. } else {
  1345. ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1; /* Failed. Generate error status */
  1346. }
  1347. return ncl; /* Return new cluster number or error status */
  1348. }
  1349. #endif /* !FF_FS_READONLY */
  1350. #if FF_USE_FASTSEEK
  1351. /*-----------------------------------------------------------------------*/
  1352. /* FAT handling - Convert offset into cluster with link map table */
  1353. /*-----------------------------------------------------------------------*/
  1354. static DWORD clmt_clust ( /* <2:Error, >=2:Cluster number */
  1355. FIL* fp, /* Pointer to the file object */
  1356. FSIZE_t ofs /* File offset to be converted to cluster# */
  1357. )
  1358. {
  1359. DWORD cl, ncl, *tbl;
  1360. FATFS *fs = fp->obj.fs;
  1361. tbl = fp->cltbl + 1; /* Top of CLMT */
  1362. cl = (DWORD)(ofs / SS(fs) / fs->csize); /* Cluster order from top of the file */
  1363. for (;;) {
  1364. ncl = *tbl++; /* Number of cluters in the fragment */
  1365. if (ncl == 0) return 0; /* End of table? (error) */
  1366. if (cl < ncl) break; /* In this fragment? */
  1367. cl -= ncl; tbl++; /* Next fragment */
  1368. }
  1369. return cl + *tbl; /* Return the cluster number */
  1370. }
  1371. #endif /* FF_USE_FASTSEEK */
  1372. /*-----------------------------------------------------------------------*/
  1373. /* Directory handling - Fill a cluster with zeros */
  1374. /*-----------------------------------------------------------------------*/
  1375. #if !FF_FS_READONLY
  1376. static FRESULT dir_clear ( /* Returns FR_OK or FR_DISK_ERR */
  1377. FATFS *fs, /* Filesystem object */
  1378. DWORD clst /* Directory table to clear */
  1379. )
  1380. {
  1381. LBA_t sect;
  1382. UINT n, szb;
  1383. BYTE *ibuf;
  1384. if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */
  1385. sect = clst2sect(fs, clst); /* Top of the cluster */
  1386. fs->winsect = sect; /* Set window to top of the cluster */
  1387. memset(fs->win, 0, sizeof fs->win); /* Clear window buffer */
  1388. #if FF_USE_LFN == 3 /* Quick table clear by using multi-secter write */
  1389. /* Allocate a temporary buffer */
  1390. for (szb = ((DWORD)fs->csize * SS(fs) >= MAX_MALLOC) ? MAX_MALLOC : fs->csize * SS(fs), ibuf = 0; szb > SS(fs) && (ibuf = ff_memalloc(szb)) == 0; szb /= 2) ;
  1391. if (szb > SS(fs)) { /* Buffer allocated? */
  1392. memset(ibuf, 0, szb);
  1393. szb /= SS(fs); /* Bytes -> Sectors */
  1394. for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */
  1395. ff_memfree(ibuf);
  1396. } else
  1397. #endif
  1398. {
  1399. ibuf = fs->win; szb = 1; /* Use window buffer (many single-sector writes may take a time) */
  1400. for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */
  1401. }
  1402. return (n == fs->csize) ? FR_OK : FR_DISK_ERR;
  1403. }
  1404. #endif /* !FF_FS_READONLY */
  1405. /*-----------------------------------------------------------------------*/
  1406. /* Directory handling - Set directory index */
  1407. /*-----------------------------------------------------------------------*/
  1408. static FRESULT dir_sdi ( /* FR_OK(0):succeeded, !=0:error */
  1409. DIR* dp, /* Pointer to directory object */
  1410. DWORD ofs /* Offset of directory table */
  1411. )
  1412. {
  1413. DWORD csz, clst;
  1414. FATFS *fs = dp->obj.fs;
  1415. if (ofs >= (DWORD)((FF_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR) || ofs % SZDIRE) { /* Check range of offset and alignment */
  1416. return FR_INT_ERR;
  1417. }
  1418. dp->dptr = ofs; /* Set current offset */
  1419. clst = dp->obj.sclust; /* Table start cluster (0:root) */
  1420. if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */
  1421. clst = (DWORD)fs->dirbase;
  1422. if (FF_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */
  1423. }
  1424. if (clst == 0) { /* Static table (root-directory on the FAT volume) */
  1425. if (ofs / SZDIRE >= fs->n_rootdir) return FR_INT_ERR; /* Is index out of range? */
  1426. dp->sect = fs->dirbase;
  1427. } else { /* Dynamic table (sub-directory or root-directory on the FAT32/exFAT volume) */
  1428. csz = (DWORD)fs->csize * SS(fs); /* Bytes per cluster */
  1429. while (ofs >= csz) { /* Follow cluster chain */
  1430. clst = get_fat(&dp->obj, clst); /* Get next cluster */
  1431. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1432. if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Reached to end of table or internal error */
  1433. ofs -= csz;
  1434. }
  1435. dp->sect = clst2sect(fs, clst);
  1436. }
  1437. dp->clust = clst; /* Current cluster# */
  1438. if (dp->sect == 0) return FR_INT_ERR;
  1439. dp->sect += ofs / SS(fs); /* Sector# of the directory entry */
  1440. dp->dir = fs->win + (ofs % SS(fs)); /* Pointer to the entry in the win[] */
  1441. return FR_OK;
  1442. }
  1443. /*-----------------------------------------------------------------------*/
  1444. /* Directory handling - Move directory table index next */
  1445. /*-----------------------------------------------------------------------*/
  1446. static FRESULT dir_next ( /* FR_OK(0):succeeded, FR_NO_FILE:End of table, FR_DENIED:Could not stretch */
  1447. DIR* dp, /* Pointer to the directory object */
  1448. int stretch /* 0: Do not stretch table, 1: Stretch table if needed */
  1449. )
  1450. {
  1451. DWORD ofs, clst;
  1452. FATFS *fs = dp->obj.fs;
  1453. ofs = dp->dptr + SZDIRE; /* Next entry */
  1454. if (ofs >= (DWORD)((FF_FS_EXFAT && fs->fs_type == FS_EXFAT) ? MAX_DIR_EX : MAX_DIR)) dp->sect = 0; /* Disable it if the offset reached the max value */
  1455. if (dp->sect == 0) return FR_NO_FILE; /* Report EOT if it has been disabled */
  1456. if (ofs % SS(fs) == 0) { /* Sector changed? */
  1457. dp->sect++; /* Next sector */
  1458. if (dp->clust == 0) { /* Static table */
  1459. if (ofs / SZDIRE >= fs->n_rootdir) { /* Report EOT if it reached end of static table */
  1460. dp->sect = 0; return FR_NO_FILE;
  1461. }
  1462. }
  1463. else { /* Dynamic table */
  1464. if ((ofs / SS(fs) & (fs->csize - 1)) == 0) { /* Cluster changed? */
  1465. clst = get_fat(&dp->obj, dp->clust); /* Get next cluster */
  1466. if (clst <= 1) return FR_INT_ERR; /* Internal error */
  1467. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1468. if (clst >= fs->n_fatent) { /* It reached end of dynamic table */
  1469. #if !FF_FS_READONLY
  1470. if (!stretch) { /* If no stretch, report EOT */
  1471. dp->sect = 0; return FR_NO_FILE;
  1472. }
  1473. clst = create_chain(&dp->obj, dp->clust); /* Allocate a cluster */
  1474. if (clst == 0) return FR_DENIED; /* No free cluster */
  1475. if (clst == 1) return FR_INT_ERR; /* Internal error */
  1476. if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */
  1477. if (dir_clear(fs, clst) != FR_OK) return FR_DISK_ERR; /* Clean up the stretched table */
  1478. if (FF_FS_EXFAT) dp->obj.stat |= 4; /* exFAT: The directory has been stretched */
  1479. #else
  1480. if (!stretch) dp->sect = 0; /* (this line is to suppress compiler warning) */
  1481. dp->sect = 0; return FR_NO_FILE; /* Report EOT */
  1482. #endif
  1483. }
  1484. dp->clust = clst; /* Initialize data for new cluster */
  1485. dp->sect = clst2sect(fs, clst);
  1486. }
  1487. }
  1488. }
  1489. dp->dptr = ofs; /* Current entry */
  1490. dp->dir = fs->win + ofs % SS(fs); /* Pointer to the entry in the win[] */
  1491. return FR_OK;
  1492. }
  1493. #if !FF_FS_READONLY
  1494. /*-----------------------------------------------------------------------*/
  1495. /* Directory handling - Reserve a block of directory entries */
  1496. /*-----------------------------------------------------------------------*/
  1497. static FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */
  1498. DIR* dp, /* Pointer to the directory object */
  1499. UINT n_ent /* Number of contiguous entries to allocate */
  1500. )
  1501. {
  1502. FRESULT res;
  1503. UINT n;
  1504. FATFS *fs = dp->obj.fs;
  1505. res = dir_sdi(dp, 0);
  1506. if (res == FR_OK) {
  1507. n = 0;
  1508. do {
  1509. res = move_window(fs, dp->sect);
  1510. if (res != FR_OK) break;
  1511. #if FF_FS_EXFAT
  1512. if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) { /* Is the entry free? */
  1513. #else
  1514. if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) { /* Is the entry free? */
  1515. #endif
  1516. if (++n == n_ent) break; /* Is a block of contiguous free entries found? */
  1517. } else {
  1518. n = 0; /* Not a free entry, restart to search */
  1519. }
  1520. res = dir_next(dp, 1); /* Next entry with table stretch enabled */
  1521. } while (res == FR_OK);
  1522. }
  1523. if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */
  1524. return res;
  1525. }
  1526. #endif /* !FF_FS_READONLY */
  1527. /*-----------------------------------------------------------------------*/
  1528. /* FAT: Directory handling - Load/Store start cluster number */
  1529. /*-----------------------------------------------------------------------*/
  1530. static DWORD ld_clust ( /* Returns the top cluster value of the SFN entry */
  1531. FATFS* fs, /* Pointer to the fs object */
  1532. const BYTE* dir /* Pointer to the key entry */
  1533. )
  1534. {
  1535. DWORD cl;
  1536. cl = ld_word(dir + DIR_FstClusLO);
  1537. if (fs->fs_type == FS_FAT32) {
  1538. cl |= (DWORD)ld_word(dir + DIR_FstClusHI) << 16;
  1539. }
  1540. return cl;
  1541. }
  1542. #if !FF_FS_READONLY
  1543. static void st_clust (
  1544. FATFS* fs, /* Pointer to the fs object */
  1545. BYTE* dir, /* Pointer to the key entry */
  1546. DWORD cl /* Value to be set */
  1547. )
  1548. {
  1549. st_word(dir + DIR_FstClusLO, (WORD)cl);
  1550. if (fs->fs_type == FS_FAT32) {
  1551. st_word(dir + DIR_FstClusHI, (WORD)(cl >> 16));
  1552. }
  1553. }
  1554. #endif
  1555. #if FF_USE_LFN
  1556. /*--------------------------------------------------------*/
  1557. /* FAT-LFN: Compare a part of file name with an LFN entry */
  1558. /*--------------------------------------------------------*/
  1559. static int cmp_lfn ( /* 1:matched, 0:not matched */
  1560. const WCHAR* lfnbuf, /* Pointer to the LFN working buffer to be compared */
  1561. BYTE* dir /* Pointer to the directory entry containing the part of LFN */
  1562. )
  1563. {
  1564. UINT i, s;
  1565. WCHAR wc, uc;
  1566. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO */
  1567. i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */
  1568. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1569. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1570. if (wc != 0) {
  1571. if (i >= FF_MAX_LFN + 1 || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */
  1572. return 0; /* Not matched */
  1573. }
  1574. wc = uc;
  1575. } else {
  1576. if (uc != 0xFFFF) return 0; /* Check filler */
  1577. }
  1578. }
  1579. if ((dir[LDIR_Ord] & LLEF) && wc && lfnbuf[i]) return 0; /* Last segment matched but different length */
  1580. return 1; /* The part of LFN matched */
  1581. }
  1582. #if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 || FF_USE_LABEL || FF_FS_EXFAT
  1583. /*-----------------------------------------------------*/
  1584. /* FAT-LFN: Pick a part of file name from an LFN entry */
  1585. /*-----------------------------------------------------*/
  1586. static int pick_lfn ( /* 1:succeeded, 0:buffer overflow or invalid LFN entry */
  1587. WCHAR* lfnbuf, /* Pointer to the LFN working buffer */
  1588. BYTE* dir /* Pointer to the LFN entry */
  1589. )
  1590. {
  1591. UINT i, s;
  1592. WCHAR wc, uc;
  1593. if (ld_word(dir + LDIR_FstClusLO) != 0) return 0; /* Check LDIR_FstClusLO is 0 */
  1594. i = ((dir[LDIR_Ord] & ~LLEF) - 1) * 13; /* Offset in the LFN buffer */
  1595. for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */
  1596. uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */
  1597. if (wc != 0) {
  1598. if (i >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */
  1599. lfnbuf[i++] = wc = uc; /* Store it */
  1600. } else {
  1601. if (uc != 0xFFFF) return 0; /* Check filler */
  1602. }
  1603. }
  1604. if (dir[LDIR_Ord] & LLEF && wc != 0) { /* Put terminator if it is the last LFN part and not terminated */
  1605. if (i >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */
  1606. lfnbuf[i] = 0;
  1607. }
  1608. return 1; /* The part of LFN is valid */
  1609. }
  1610. #endif
  1611. #if !FF_FS_READONLY
  1612. /*-----------------------------------------*/
  1613. /* FAT-LFN: Create an entry of LFN entries */
  1614. /*-----------------------------------------*/
  1615. static void put_lfn (
  1616. const WCHAR* lfn, /* Pointer to the LFN */
  1617. BYTE* dir, /* Pointer to the LFN entry to be created */
  1618. BYTE ord, /* LFN order (1-20) */
  1619. BYTE sum /* Checksum of the corresponding SFN */
  1620. )
  1621. {
  1622. UINT i, s;
  1623. WCHAR wc;
  1624. dir[LDIR_Chksum] = sum; /* Set checksum */
  1625. dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */
  1626. dir[LDIR_Type] = 0;
  1627. st_word(dir + LDIR_FstClusLO, 0);
  1628. i = (ord - 1) * 13; /* Get offset in the LFN working buffer */
  1629. s = wc = 0;
  1630. do {
  1631. if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */
  1632. st_word(dir + LfnOfs[s], wc); /* Put it */
  1633. if (wc == 0) wc = 0xFFFF; /* Padding characters for following items */
  1634. } while (++s < 13);
  1635. if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */
  1636. dir[LDIR_Ord] = ord; /* Set the LFN order */
  1637. }
  1638. #endif /* !FF_FS_READONLY */
  1639. #endif /* FF_USE_LFN */
  1640. #if FF_USE_LFN && !FF_FS_READONLY
  1641. /*-----------------------------------------------------------------------*/
  1642. /* FAT-LFN: Create a Numbered SFN */
  1643. /*-----------------------------------------------------------------------*/
  1644. static void gen_numname (
  1645. BYTE* dst, /* Pointer to the buffer to store numbered SFN */
  1646. const BYTE* src, /* Pointer to SFN in directory form */
  1647. const WCHAR* lfn, /* Pointer to LFN */
  1648. UINT seq /* Sequence number */
  1649. )
  1650. {
  1651. BYTE ns[8], c;
  1652. UINT i, j;
  1653. WCHAR wc;
  1654. DWORD sreg;
  1655. memcpy(dst, src, 11); /* Prepare the SFN to be modified */
  1656. if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */
  1657. sreg = seq;
  1658. while (*lfn) { /* Create a CRC as hash value */
  1659. wc = *lfn++;
  1660. for (i = 0; i < 16; i++) {
  1661. sreg = (sreg << 1) + (wc & 1);
  1662. wc >>= 1;
  1663. if (sreg & 0x10000) sreg ^= 0x11021;
  1664. }
  1665. }
  1666. seq = (UINT)sreg;
  1667. }
  1668. /* Make suffix (~ + hexdecimal) */
  1669. i = 7;
  1670. do {
  1671. c = (BYTE)((seq % 16) + '0'); seq /= 16;
  1672. if (c > '9') c += 7;
  1673. ns[i--] = c;
  1674. } while (i && seq);
  1675. ns[i] = '~';
  1676. /* Append the suffix to the SFN body */
  1677. for (j = 0; j < i && dst[j] != ' '; j++) { /* Find the offset to append */
  1678. if (dbc_1st(dst[j])) { /* To avoid DBC break up */
  1679. if (j == i - 1) break;
  1680. j++;
  1681. }
  1682. }
  1683. do { /* Append the suffix */
  1684. dst[j++] = (i < 8) ? ns[i++] : ' ';
  1685. } while (j < 8);
  1686. }
  1687. #endif /* FF_USE_LFN && !FF_FS_READONLY */
  1688. #if FF_USE_LFN
  1689. /*-----------------------------------------------------------------------*/
  1690. /* FAT-LFN: Calculate checksum of an SFN entry */
  1691. /*-----------------------------------------------------------------------*/
  1692. static BYTE sum_sfn (
  1693. const BYTE* dir /* Pointer to the SFN entry */
  1694. )
  1695. {
  1696. BYTE sum = 0;
  1697. UINT n = 11;
  1698. do {
  1699. sum = (sum >> 1) + (sum << 7) + *dir++;
  1700. } while (--n);
  1701. return sum;
  1702. }
  1703. #endif /* FF_USE_LFN */
  1704. #if FF_FS_EXFAT
  1705. /*-----------------------------------------------------------------------*/
  1706. /* exFAT: Checksum */
  1707. /*-----------------------------------------------------------------------*/
  1708. static WORD xdir_sum ( /* Get checksum of the directoly entry block */
  1709. const BYTE* dir /* Directory entry block to be calculated */
  1710. )
  1711. {
  1712. UINT i, szblk;
  1713. WORD sum;
  1714. szblk = (dir[XDIR_NumSec] + 1) * SZDIRE; /* Number of bytes of the entry block */
  1715. for (i = sum = 0; i < szblk; i++) {
  1716. if (i == XDIR_SetSum) { /* Skip 2-byte sum field */
  1717. i++;
  1718. } else {
  1719. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + dir[i];
  1720. }
  1721. }
  1722. return sum;
  1723. }
  1724. static WORD xname_sum ( /* Get check sum (to be used as hash) of the file name */
  1725. const WCHAR* name /* File name to be calculated */
  1726. )
  1727. {
  1728. WCHAR chr;
  1729. WORD sum = 0;
  1730. while ((chr = *name++) != 0) {
  1731. chr = (WCHAR)ff_wtoupper(chr); /* File name needs to be up-case converted */
  1732. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr & 0xFF);
  1733. sum = ((sum & 1) ? 0x8000 : 0) + (sum >> 1) + (chr >> 8);
  1734. }
  1735. return sum;
  1736. }
  1737. #if !FF_FS_READONLY && FF_USE_MKFS
  1738. static DWORD xsum32 ( /* Returns 32-bit checksum */
  1739. BYTE dat, /* Byte to be calculated (byte-by-byte processing) */
  1740. DWORD sum /* Previous sum value */
  1741. )
  1742. {
  1743. sum = ((sum & 1) ? 0x80000000 : 0) + (sum >> 1) + dat;
  1744. return sum;
  1745. }
  1746. #endif
  1747. /*-----------------------------------*/
  1748. /* exFAT: Get a directry entry block */
  1749. /*-----------------------------------*/
  1750. static FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */
  1751. DIR* dp /* Reading direcotry object pointing top of the entry block to load */
  1752. )
  1753. {
  1754. FRESULT res;
  1755. UINT i, sz_ent;
  1756. BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */
  1757. /* Load file directory entry */
  1758. res = move_window(dp->obj.fs, dp->sect);
  1759. if (res != FR_OK) return res;
  1760. if (dp->dir[XDIR_Type] != ET_FILEDIR) return FR_INT_ERR; /* Invalid order */
  1761. memcpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE);
  1762. sz_ent = (dirb[XDIR_NumSec] + 1) * SZDIRE;
  1763. if (sz_ent < 3 * SZDIRE || sz_ent > 19 * SZDIRE) return FR_INT_ERR;
  1764. /* Load stream extension entry */
  1765. res = dir_next(dp, 0);
  1766. if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */
  1767. if (res != FR_OK) return res;
  1768. res = move_window(dp->obj.fs, dp->sect);
  1769. if (res != FR_OK) return res;
  1770. if (dp->dir[XDIR_Type] != ET_STREAM) return FR_INT_ERR; /* Invalid order */
  1771. memcpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE);
  1772. if (MAXDIRB(dirb[XDIR_NumName]) > sz_ent) return FR_INT_ERR;
  1773. /* Load file name entries */
  1774. i = 2 * SZDIRE; /* Name offset to load */
  1775. do {
  1776. res = dir_next(dp, 0);
  1777. if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */
  1778. if (res != FR_OK) return res;
  1779. res = move_window(dp->obj.fs, dp->sect);
  1780. if (res != FR_OK) return res;
  1781. if (dp->dir[XDIR_Type] != ET_FILENAME) return FR_INT_ERR; /* Invalid order */
  1782. if (i < MAXDIRB(FF_MAX_LFN)) memcpy(dirb + i, dp->dir, SZDIRE);
  1783. } while ((i += SZDIRE) < sz_ent);
  1784. /* Sanity check (do it for only accessible object) */
  1785. if (i <= MAXDIRB(FF_MAX_LFN)) {
  1786. if (xdir_sum(dirb) != ld_word(dirb + XDIR_SetSum)) return FR_INT_ERR;
  1787. }
  1788. return FR_OK;
  1789. }
  1790. /*------------------------------------------------------------------*/
  1791. /* exFAT: Initialize object allocation info with loaded entry block */
  1792. /*------------------------------------------------------------------*/
  1793. static void init_alloc_info (
  1794. FATFS* fs, /* Filesystem object */
  1795. FFOBJID* obj /* Object allocation information to be initialized */
  1796. )
  1797. {
  1798. obj->sclust = ld_dword(fs->dirbuf + XDIR_FstClus); /* Start cluster */
  1799. obj->objsize = ld_qword(fs->dirbuf + XDIR_FileSize); /* Size */
  1800. obj->stat = fs->dirbuf[XDIR_GenFlags] & 2; /* Allocation status */
  1801. obj->n_frag = 0; /* No last fragment info */
  1802. }
  1803. #if !FF_FS_READONLY || FF_FS_RPATH != 0
  1804. /*------------------------------------------------*/
  1805. /* exFAT: Load the object's directory entry block */
  1806. /*------------------------------------------------*/
  1807. static FRESULT load_obj_xdir (
  1808. DIR* dp, /* Blank directory object to be used to access containing direcotry */
  1809. const FFOBJID* obj /* Object with its containing directory information */
  1810. )
  1811. {
  1812. FRESULT res;
  1813. /* Open object containing directory */
  1814. dp->obj.fs = obj->fs;
  1815. dp->obj.sclust = obj->c_scl;
  1816. dp->obj.stat = (BYTE)obj->c_size;
  1817. dp->obj.objsize = obj->c_size & 0xFFFFFF00;
  1818. dp->obj.n_frag = 0;
  1819. dp->blk_ofs = obj->c_ofs;
  1820. res = dir_sdi(dp, dp->blk_ofs); /* Goto object's entry block */
  1821. if (res == FR_OK) {
  1822. res = load_xdir(dp); /* Load the object's entry block */
  1823. }
  1824. return res;
  1825. }
  1826. #endif
  1827. #if !FF_FS_READONLY
  1828. /*----------------------------------------*/
  1829. /* exFAT: Store the directory entry block */
  1830. /*----------------------------------------*/
  1831. static FRESULT store_xdir (
  1832. DIR* dp /* Pointer to the direcotry object */
  1833. )
  1834. {
  1835. FRESULT res;
  1836. UINT nent;
  1837. BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */
  1838. /* Create set sum */
  1839. st_word(dirb + XDIR_SetSum, xdir_sum(dirb));
  1840. nent = dirb[XDIR_NumSec] + 1;
  1841. /* Store the direcotry entry block to the directory */
  1842. res = dir_sdi(dp, dp->blk_ofs);
  1843. while (res == FR_OK) {
  1844. res = move_window(dp->obj.fs, dp->sect);
  1845. if (res != FR_OK) break;
  1846. memcpy(dp->dir, dirb, SZDIRE);
  1847. dp->obj.fs->wflag = 1;
  1848. if (--nent == 0) break;
  1849. dirb += SZDIRE;
  1850. res = dir_next(dp, 0);
  1851. }
  1852. return (res == FR_OK || res == FR_DISK_ERR) ? res : FR_INT_ERR;
  1853. }
  1854. /*-------------------------------------------*/
  1855. /* exFAT: Create a new directory enrty block */
  1856. /*-------------------------------------------*/
  1857. static void create_xdir (
  1858. BYTE* dirb, /* Pointer to the direcotry entry block buffer */
  1859. const WCHAR* lfn /* Pointer to the object name */
  1860. )
  1861. {
  1862. UINT i;
  1863. BYTE nc1, nlen;
  1864. WCHAR wc;
  1865. /* Create file-directory and stream-extension entry */
  1866. memset(dirb, 0, 2 * SZDIRE);
  1867. dirb[0 * SZDIRE + XDIR_Type] = ET_FILEDIR;
  1868. dirb[1 * SZDIRE + XDIR_Type] = ET_STREAM;
  1869. /* Create file-name entries */
  1870. i = SZDIRE * 2; /* Top of file_name entries */
  1871. nlen = nc1 = 0; wc = 1;
  1872. do {
  1873. dirb[i++] = ET_FILENAME; dirb[i++] = 0;
  1874. do { /* Fill name field */
  1875. if (wc != 0 && (wc = lfn[nlen]) != 0) nlen++; /* Get a character if exist */
  1876. st_word(dirb + i, wc); /* Store it */
  1877. i += 2;
  1878. } while (i % SZDIRE != 0);
  1879. nc1++;
  1880. } while (lfn[nlen]); /* Fill next entry if any char follows */
  1881. dirb[XDIR_NumName] = nlen; /* Set name length */
  1882. dirb[XDIR_NumSec] = 1 + nc1; /* Set secondary count (C0 + C1s) */
  1883. st_word(dirb + XDIR_NameHash, xname_sum(lfn)); /* Set name hash */
  1884. }
  1885. #endif /* !FF_FS_READONLY */
  1886. #endif /* FF_FS_EXFAT */
  1887. #if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 || FF_USE_LABEL || FF_FS_EXFAT
  1888. /*-----------------------------------------------------------------------*/
  1889. /* Read an object from the directory */
  1890. /*-----------------------------------------------------------------------*/
  1891. #define DIR_READ_FILE(dp) dir_read(dp, 0)
  1892. #define DIR_READ_LABEL(dp) dir_read(dp, 1)
  1893. static FRESULT dir_read (
  1894. DIR* dp, /* Pointer to the directory object */
  1895. int vol /* Filtered by 0:file/directory or 1:volume label */
  1896. )
  1897. {
  1898. FRESULT res = FR_NO_FILE;
  1899. FATFS *fs = dp->obj.fs;
  1900. BYTE attr, b;
  1901. #if FF_USE_LFN
  1902. BYTE ord = 0xFF, sum = 0xFF;
  1903. #endif
  1904. while (dp->sect) {
  1905. res = move_window(fs, dp->sect);
  1906. if (res != FR_OK) break;
  1907. b = dp->dir[DIR_Name]; /* Test for the entry type */
  1908. if (b == 0) {
  1909. res = FR_NO_FILE; break; /* Reached to end of the directory */
  1910. }
  1911. #if FF_FS_EXFAT
  1912. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1913. if (FF_USE_LABEL && vol) {
  1914. if (b == ET_VLABEL) break; /* Volume label entry? */
  1915. } else {
  1916. if (b == ET_FILEDIR) { /* Start of the file entry block? */
  1917. dp->blk_ofs = dp->dptr; /* Get location of the block */
  1918. res = load_xdir(dp); /* Load the entry block */
  1919. if (res == FR_OK) {
  1920. dp->obj.attr = fs->dirbuf[XDIR_Attr] & AM_MASK; /* Get attribute */
  1921. }
  1922. break;
  1923. }
  1924. }
  1925. } else
  1926. #endif
  1927. { /* On the FAT/FAT32 volume */
  1928. dp->obj.attr = attr = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */
  1929. #if FF_USE_LFN /* LFN configuration */
  1930. if (b == DDEM || b == '.' || (int)((attr & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */
  1931. ord = 0xFF;
  1932. } else {
  1933. if (attr == AM_LFN) { /* An LFN entry is found */
  1934. if (b & LLEF) { /* Is it start of an LFN sequence? */
  1935. sum = dp->dir[LDIR_Chksum];
  1936. b &= (BYTE)~LLEF; ord = b;
  1937. dp->blk_ofs = dp->dptr;
  1938. }
  1939. /* Check LFN validity and capture it */
  1940. ord = (b == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  1941. } else { /* An SFN entry is found */
  1942. if (ord != 0 || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */
  1943. dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */
  1944. }
  1945. break;
  1946. }
  1947. }
  1948. #else /* Non LFN configuration */
  1949. if (b != DDEM && b != '.' && attr != AM_LFN && (int)((attr & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */
  1950. break;
  1951. }
  1952. #endif
  1953. }
  1954. res = dir_next(dp, 0); /* Next entry */
  1955. if (res != FR_OK) break;
  1956. }
  1957. if (res != FR_OK) dp->sect = 0; /* Terminate the read operation on error or EOT */
  1958. return res;
  1959. }
  1960. #endif /* FF_FS_MINIMIZE <= 1 || FF_USE_LABEL || FF_FS_RPATH >= 2 */
  1961. /*-----------------------------------------------------------------------*/
  1962. /* Directory handling - Find an object in the directory */
  1963. /*-----------------------------------------------------------------------*/
  1964. static FRESULT dir_find ( /* FR_OK(0):succeeded, !=0:error */
  1965. DIR* dp /* Pointer to the directory object with the file name */
  1966. )
  1967. {
  1968. FRESULT res;
  1969. FATFS *fs = dp->obj.fs;
  1970. BYTE c;
  1971. #if FF_USE_LFN
  1972. BYTE a, ord, sum;
  1973. #endif
  1974. res = dir_sdi(dp, 0); /* Rewind directory object */
  1975. if (res != FR_OK) return res;
  1976. #if FF_FS_EXFAT
  1977. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  1978. BYTE nc;
  1979. UINT di, ni;
  1980. WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */
  1981. while ((res = DIR_READ_FILE(dp)) == FR_OK) { /* Read an item */
  1982. #if FF_MAX_LFN < 255
  1983. if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */
  1984. #endif
  1985. if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip comparison if hash mismatched */
  1986. for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */
  1987. if ((di % SZDIRE) == 0) di += 2;
  1988. if (ff_wtoupper(ld_word(fs->dirbuf + di)) != ff_wtoupper(fs->lfnbuf[ni])) break;
  1989. }
  1990. if (nc == 0 && !fs->lfnbuf[ni]) break; /* Name matched? */
  1991. }
  1992. return res;
  1993. }
  1994. #endif
  1995. /* On the FAT/FAT32 volume */
  1996. #if FF_USE_LFN
  1997. ord = sum = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  1998. #endif
  1999. do {
  2000. res = move_window(fs, dp->sect);
  2001. if (res != FR_OK) break;
  2002. c = dp->dir[DIR_Name];
  2003. if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */
  2004. #if FF_USE_LFN /* LFN configuration */
  2005. dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK;
  2006. if (c == DDEM || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */
  2007. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  2008. } else {
  2009. if (a == AM_LFN) { /* An LFN entry is found */
  2010. if (!(dp->fn[NSFLAG] & NS_NOLFN)) {
  2011. if (c & LLEF) { /* Is it start of LFN sequence? */
  2012. sum = dp->dir[LDIR_Chksum];
  2013. c &= (BYTE)~LLEF; ord = c; /* LFN start order */
  2014. dp->blk_ofs = dp->dptr; /* Start offset of LFN */
  2015. }
  2016. /* Check validity of the LFN entry and compare it with given name */
  2017. ord = (c == ord && sum == dp->dir[LDIR_Chksum] && cmp_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;
  2018. }
  2019. } else { /* An SFN entry is found */
  2020. if (ord == 0 && sum == sum_sfn(dp->dir)) break; /* LFN matched? */
  2021. if (!(dp->fn[NSFLAG] & NS_LOSS) && !memcmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */
  2022. ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */
  2023. }
  2024. }
  2025. #else /* Non LFN configuration */
  2026. dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;
  2027. if (!(dp->dir[DIR_Attr] & AM_VOL) && !memcmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */
  2028. #endif
  2029. res = dir_next(dp, 0); /* Next entry */
  2030. } while (res == FR_OK);
  2031. return res;
  2032. }
  2033. #if !FF_FS_READONLY
  2034. /*-----------------------------------------------------------------------*/
  2035. /* Register an object to the directory */
  2036. /*-----------------------------------------------------------------------*/
  2037. static FRESULT dir_register ( /* FR_OK:succeeded, FR_DENIED:no free entry or too many SFN collision, FR_DISK_ERR:disk error */
  2038. DIR* dp /* Target directory with object name to be created */
  2039. )
  2040. {
  2041. FRESULT res;
  2042. FATFS *fs = dp->obj.fs;
  2043. #if FF_USE_LFN /* LFN configuration */
  2044. UINT n, len, n_ent;
  2045. BYTE sn[12], sum;
  2046. if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */
  2047. for (len = 0; fs->lfnbuf[len]; len++) ; /* Get lfn length */
  2048. #if FF_FS_EXFAT
  2049. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2050. n_ent = (len + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */
  2051. res = dir_alloc(dp, n_ent); /* Allocate directory entries */
  2052. if (res != FR_OK) return res;
  2053. dp->blk_ofs = dp->dptr - SZDIRE * (n_ent - 1); /* Set the allocated entry block offset */
  2054. if (dp->obj.stat & 4) { /* Has the directory been stretched by new allocation? */
  2055. dp->obj.stat &= ~4;
  2056. res = fill_first_frag(&dp->obj); /* Fill the first fragment on the FAT if needed */
  2057. if (res != FR_OK) return res;
  2058. res = fill_last_frag(&dp->obj, dp->clust, 0xFFFFFFFF); /* Fill the last fragment on the FAT if needed */
  2059. if (res != FR_OK) return res;
  2060. if (dp->obj.sclust != 0) { /* Is it a sub-directory? */
  2061. DIR dj;
  2062. res = load_obj_xdir(&dj, &dp->obj); /* Load the object status */
  2063. if (res != FR_OK) return res;
  2064. dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */
  2065. st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize);
  2066. st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);
  2067. fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1; /* Update the allocation status */
  2068. res = store_xdir(&dj); /* Store the object status */
  2069. if (res != FR_OK) return res;
  2070. }
  2071. }
  2072. create_xdir(fs->dirbuf, fs->lfnbuf); /* Create on-memory directory block to be written later */
  2073. return FR_OK;
  2074. }
  2075. #endif
  2076. /* On the FAT/FAT32 volume */
  2077. memcpy(sn, dp->fn, 12);
  2078. if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */
  2079. dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */
  2080. for (n = 1; n < 100; n++) {
  2081. gen_numname(dp->fn, sn, fs->lfnbuf, n); /* Generate a numbered name */
  2082. res = dir_find(dp); /* Check if the name collides with existing SFN */
  2083. if (res != FR_OK) break;
  2084. }
  2085. if (n == 100) return FR_DENIED; /* Abort if too many collisions */
  2086. if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */
  2087. dp->fn[NSFLAG] = sn[NSFLAG];
  2088. }
  2089. /* Create an SFN with/without LFNs. */
  2090. n_ent = (sn[NSFLAG] & NS_LFN) ? (len + 12) / 13 + 1 : 1; /* Number of entries to allocate */
  2091. res = dir_alloc(dp, n_ent); /* Allocate entries */
  2092. if (res == FR_OK && --n_ent) { /* Set LFN entry if needed */
  2093. res = dir_sdi(dp, dp->dptr - n_ent * SZDIRE);
  2094. if (res == FR_OK) {
  2095. sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */
  2096. do { /* Store LFN entries in bottom first */
  2097. res = move_window(fs, dp->sect);
  2098. if (res != FR_OK) break;
  2099. put_lfn(fs->lfnbuf, dp->dir, (BYTE)n_ent, sum);
  2100. fs->wflag = 1;
  2101. res = dir_next(dp, 0); /* Next entry */
  2102. } while (res == FR_OK && --n_ent);
  2103. }
  2104. }
  2105. #else /* Non LFN configuration */
  2106. res = dir_alloc(dp, 1); /* Allocate an entry for SFN */
  2107. #endif
  2108. /* Set SFN entry */
  2109. if (res == FR_OK) {
  2110. res = move_window(fs, dp->sect);
  2111. if (res == FR_OK) {
  2112. memset(dp->dir, 0, SZDIRE); /* Clean the entry */
  2113. memcpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */
  2114. #if FF_USE_LFN
  2115. dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */
  2116. #endif
  2117. fs->wflag = 1;
  2118. }
  2119. }
  2120. return res;
  2121. }
  2122. #endif /* !FF_FS_READONLY */
  2123. #if !FF_FS_READONLY && FF_FS_MINIMIZE == 0
  2124. /*-----------------------------------------------------------------------*/
  2125. /* Remove an object from the directory */
  2126. /*-----------------------------------------------------------------------*/
  2127. static FRESULT dir_remove ( /* FR_OK:Succeeded, FR_DISK_ERR:A disk error */
  2128. DIR* dp /* Directory object pointing the entry to be removed */
  2129. )
  2130. {
  2131. FRESULT res;
  2132. FATFS *fs = dp->obj.fs;
  2133. #if FF_USE_LFN /* LFN configuration */
  2134. DWORD last = dp->dptr;
  2135. res = (dp->blk_ofs == 0xFFFFFFFF) ? FR_OK : dir_sdi(dp, dp->blk_ofs); /* Goto top of the entry block if LFN is exist */
  2136. if (res == FR_OK) {
  2137. do {
  2138. res = move_window(fs, dp->sect);
  2139. if (res != FR_OK) break;
  2140. if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  2141. dp->dir[XDIR_Type] &= 0x7F; /* Clear the entry InUse flag. */
  2142. } else { /* On the FAT/FAT32 volume */
  2143. dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'. */
  2144. }
  2145. fs->wflag = 1;
  2146. if (dp->dptr >= last) break; /* If reached last entry then all entries of the object has been deleted. */
  2147. res = dir_next(dp, 0); /* Next entry */
  2148. } while (res == FR_OK);
  2149. if (res == FR_NO_FILE) res = FR_INT_ERR;
  2150. }
  2151. #else /* Non LFN configuration */
  2152. res = move_window(fs, dp->sect);
  2153. if (res == FR_OK) {
  2154. dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'.*/
  2155. fs->wflag = 1;
  2156. }
  2157. #endif
  2158. return res;
  2159. }
  2160. #endif /* !FF_FS_READONLY && FF_FS_MINIMIZE == 0 */
  2161. #if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2
  2162. /*-----------------------------------------------------------------------*/
  2163. /* Get file information from directory entry */
  2164. /*-----------------------------------------------------------------------*/
  2165. static void get_fileinfo (
  2166. DIR* dp, /* Pointer to the directory object */
  2167. FILINFO* fno /* Pointer to the file information to be filled */
  2168. )
  2169. {
  2170. UINT si, di;
  2171. #if FF_USE_LFN
  2172. BYTE lcf;
  2173. WCHAR wc, hs;
  2174. FATFS *fs = dp->obj.fs;
  2175. UINT nw;
  2176. #else
  2177. FATFS_TCHAR c;
  2178. #endif
  2179. fno->fname[0] = 0; /* Invaidate file info */
  2180. if (dp->sect == 0) return; /* Exit if read pointer has reached end of directory */
  2181. #if FF_USE_LFN /* LFN configuration */
  2182. #if FF_FS_EXFAT
  2183. if (fs->fs_type == FS_EXFAT) { /* exFAT volume */
  2184. UINT nc = 0;
  2185. si = SZDIRE * 2; di = 0; /* 1st C1 entry in the entry block */
  2186. hs = 0;
  2187. while (nc < fs->dirbuf[XDIR_NumName]) {
  2188. if (si >= MAXDIRB(FF_MAX_LFN)) { di = 0; break; } /* Truncated directory block? */
  2189. if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */
  2190. wc = ld_word(fs->dirbuf + si); si += 2; nc++; /* Get a character */
  2191. if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */
  2192. hs = wc; continue; /* Get low surrogate */
  2193. }
  2194. nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */
  2195. if (nw == 0) { di = 0; break; } /* Buffer overflow or wrong char? */
  2196. di += nw;
  2197. hs = 0;
  2198. }
  2199. if (hs != 0) di = 0; /* Broken surrogate pair? */
  2200. if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object name? */
  2201. fno->fname[di] = 0; /* Terminate the name */
  2202. fno->altname[0] = 0; /* exFAT does not support SFN */
  2203. fno->fattrib = fs->dirbuf[XDIR_Attr] & AM_MASKX; /* Attribute */
  2204. fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(fs->dirbuf + XDIR_FileSize); /* Size */
  2205. fno->ftime = ld_word(fs->dirbuf + XDIR_ModTime + 0); /* Time */
  2206. fno->fdate = ld_word(fs->dirbuf + XDIR_ModTime + 2); /* Date */
  2207. return;
  2208. } else
  2209. #endif
  2210. { /* FAT/FAT32 volume */
  2211. if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */
  2212. si = di = 0;
  2213. hs = 0;
  2214. while (fs->lfnbuf[si] != 0) {
  2215. wc = fs->lfnbuf[si++]; /* Get an LFN character (UTF-16) */
  2216. if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */
  2217. hs = wc; continue; /* Get low surrogate */
  2218. }
  2219. nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */
  2220. if (nw == 0) { di = 0; break; } /* Buffer overflow or wrong char? */
  2221. di += nw;
  2222. hs = 0;
  2223. }
  2224. if (hs != 0) di = 0; /* Broken surrogate pair? */
  2225. fno->fname[di] = 0; /* Terminate the LFN (null string means LFN is invalid) */
  2226. }
  2227. }
  2228. si = di = 0;
  2229. while (si < 11) { /* Get SFN from SFN entry */
  2230. wc = dp->dir[si++]; /* Get a char */
  2231. if (wc == ' ') continue; /* Skip padding spaces */
  2232. if (wc == RDDEM) wc = DDEM; /* Restore replaced DDEM character */
  2233. if (si == 9 && di < FF_SFN_BUF) fno->altname[di++] = '.'; /* Insert a . if extension is exist */
  2234. #if FF_LFN_UNICODE >= 1 /* Unicode output */
  2235. if (dbc_1st((BYTE)wc) && si != 8 && si != 11 && dbc_2nd(dp->dir[si])) { /* Make a DBC if needed */
  2236. wc = wc << 8 | dp->dir[si++];
  2237. }
  2238. wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM -> Unicode */
  2239. if (wc == 0) { di = 0; break; } /* Wrong char in the current code page? */
  2240. nw = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in API encoding */
  2241. if (nw == 0) { di = 0; break; } /* Buffer overflow? */
  2242. di += nw;
  2243. #else /* ANSI/OEM output */
  2244. fno->altname[di++] = (FATFS_TCHAR)wc; /* Store it without any conversion */
  2245. #endif
  2246. }
  2247. fno->altname[di] = 0; /* Terminate the SFN (null string means SFN is invalid) */
  2248. if (fno->fname[0] == 0) { /* If LFN is invalid, altname[] needs to be copied to fname[] */
  2249. if (di == 0) { /* If LFN and SFN both are invalid, this object is inaccesible */
  2250. fno->fname[di++] = '?';
  2251. } else {
  2252. for (si = di = 0, lcf = NS_BODY; fno->altname[si]; si++, di++) { /* Copy altname[] to fname[] with case information */
  2253. wc = (WCHAR)fno->altname[si];
  2254. if (wc == '.') lcf = NS_EXT;
  2255. if (IsUpper(wc) && (dp->dir[DIR_NTres] & lcf)) wc += 0x20;
  2256. fno->fname[di] = (FATFS_TCHAR)wc;
  2257. }
  2258. }
  2259. fno->fname[di] = 0; /* Terminate the LFN */
  2260. if (!dp->dir[DIR_NTres]) fno->altname[0] = 0; /* Altname is not needed if neither LFN nor case info is exist. */
  2261. }
  2262. #else /* Non-LFN configuration */
  2263. si = di = 0;
  2264. while (si < 11) { /* Copy name body and extension */
  2265. c = (FATFS_TCHAR)dp->dir[si++];
  2266. if (c == ' ') continue; /* Skip padding spaces */
  2267. if (c == RDDEM) c = DDEM; /* Restore replaced DDEM character */
  2268. if (si == 9) fno->fname[di++] = '.';/* Insert a . if extension is exist */
  2269. fno->fname[di++] = c;
  2270. }
  2271. fno->fname[di] = 0; /* Terminate the SFN */
  2272. #endif
  2273. fno->fattrib = dp->dir[DIR_Attr] & AM_MASK; /* Attribute */
  2274. fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */
  2275. fno->ftime = ld_word(dp->dir + DIR_ModTime + 0); /* Time */
  2276. fno->fdate = ld_word(dp->dir + DIR_ModTime + 2); /* Date */
  2277. }
  2278. #endif /* FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 */
  2279. #if FF_USE_FIND && FF_FS_MINIMIZE <= 1
  2280. /*-----------------------------------------------------------------------*/
  2281. /* Pattern matching */
  2282. /*-----------------------------------------------------------------------*/
  2283. #define FIND_RECURS 4 /* Maximum number of wildcard terms in the pattern to limit recursion */
  2284. static DWORD get_achar ( /* Get a character and advance ptr */
  2285. const FATFS_TCHAR** ptr /* Pointer to pointer to the ANSI/OEM or Unicode string */
  2286. )
  2287. {
  2288. DWORD chr;
  2289. #if FF_USE_LFN && FF_LFN_UNICODE >= 1 /* Unicode input */
  2290. chr = tchar2uni(ptr);
  2291. if (chr == 0xFFFFFFFF) chr = 0; /* Wrong UTF encoding is recognized as end of the string */
  2292. chr = ff_wtoupper(chr);
  2293. #else /* ANSI/OEM input */
  2294. chr = (BYTE)*(*ptr)++; /* Get a byte */
  2295. if (IsLower(chr)) chr -= 0x20; /* To upper ASCII char */
  2296. #if FF_CODE_PAGE == 0
  2297. if (ExCvt && chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
  2298. #elif FF_CODE_PAGE < 900
  2299. if (chr >= 0x80) chr = ExCvt[chr - 0x80]; /* To upper SBCS extended char */
  2300. #endif
  2301. #if FF_CODE_PAGE == 0 || FF_CODE_PAGE >= 900
  2302. if (dbc_1st((BYTE)chr)) { /* Get DBC 2nd byte if needed */
  2303. chr = dbc_2nd((BYTE)**ptr) ? chr << 8 | (BYTE)*(*ptr)++ : 0;
  2304. }
  2305. #endif
  2306. #endif
  2307. return chr;
  2308. }
  2309. static int pattern_match ( /* 0:mismatched, 1:matched */
  2310. const FATFS_TCHAR* pat, /* Matching pattern */
  2311. const FATFS_TCHAR* nam, /* String to be tested */
  2312. UINT skip, /* Number of pre-skip chars (number of ?s, b8:infinite (* specified)) */
  2313. UINT recur /* Recursion count */
  2314. )
  2315. {
  2316. const FATFS_TCHAR *pptr, *nptr;
  2317. DWORD pchr, nchr;
  2318. UINT sk;
  2319. while ((skip & 0xFF) != 0) { /* Pre-skip name chars */
  2320. if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */
  2321. skip--;
  2322. }
  2323. if (*pat == 0 && skip) return 1; /* Matched? (short circuit) */
  2324. do {
  2325. pptr = pat; nptr = nam; /* Top of pattern and name to match */
  2326. for (;;) {
  2327. if (*pptr == '?' || *pptr == '*') { /* Wildcard term? */
  2328. if (recur == 0) return 0; /* Too many wildcard terms? */
  2329. sk = 0;
  2330. do { /* Analyze the wildcard term */
  2331. if (*pptr++ == '?') sk++; else sk |= 0x100;
  2332. } while (*pptr == '?' || *pptr == '*');
  2333. if (pattern_match(pptr, nptr, sk, recur - 1)) return 1; /* Test new branch (recursive call) */
  2334. nchr = *nptr; break; /* Branch mismatched */
  2335. }
  2336. pchr = get_achar(&pptr); /* Get a pattern char */
  2337. nchr = get_achar(&nptr); /* Get a name char */
  2338. if (pchr != nchr) break; /* Branch mismatched? */
  2339. if (pchr == 0) return 1; /* Branch matched? (matched at end of both strings) */
  2340. }
  2341. get_achar(&nam); /* nam++ */
  2342. } while (skip && nchr); /* Retry until end of name if infinite search is specified */
  2343. return 0;
  2344. }
  2345. #endif /* FF_USE_FIND && FF_FS_MINIMIZE <= 1 */
  2346. /*-----------------------------------------------------------------------*/
  2347. /* Pick a top segment and create the object name in directory form */
  2348. /*-----------------------------------------------------------------------*/
  2349. static FRESULT create_name ( /* FR_OK: successful, FR_INVALID_NAME: could not create */
  2350. DIR* dp, /* Pointer to the directory object */
  2351. const FATFS_TCHAR** path /* Pointer to pointer to the segment in the path string */
  2352. )
  2353. {
  2354. #if FF_USE_LFN /* LFN configuration */
  2355. BYTE b, cf;
  2356. WCHAR wc, *lfn;
  2357. DWORD uc;
  2358. UINT i, ni, si, di;
  2359. const FATFS_TCHAR *p;
  2360. /* Create LFN into LFN working buffer */
  2361. p = *path; lfn = dp->obj.fs->lfnbuf; di = 0;
  2362. for (;;) {
  2363. uc = tchar2uni(&p); /* Get a character */
  2364. if (uc == 0xFFFFFFFF) return FR_INVALID_NAME; /* Invalid code or UTF decode error */
  2365. if (uc >= 0x10000) lfn[di++] = (WCHAR)(uc >> 16); /* Store high surrogate if needed */
  2366. wc = (WCHAR)uc;
  2367. if (wc < ' ' || IsSeparator(wc)) break; /* Break if end of the path or a separator is found */
  2368. if (wc < 0x80 && strchr("*:<>|\"\?\x7F", (int)wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */
  2369. if (di >= FF_MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */
  2370. lfn[di++] = wc; /* Store the Unicode character */
  2371. }
  2372. if (wc < ' ') { /* Stopped at end of the path? */
  2373. cf = NS_LAST; /* Last segment */
  2374. } else { /* Stopped at a separator */
  2375. while (IsSeparator(*p)) p++; /* Skip duplicated separators if exist */
  2376. cf = 0; /* Next segment may follow */
  2377. if (IsTerminator(*p)) cf = NS_LAST; /* Ignore terminating separator */
  2378. }
  2379. *path = p; /* Return pointer to the next segment */
  2380. #if FF_FS_RPATH != 0
  2381. if ((di == 1 && lfn[di - 1] == '.') ||
  2382. (di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */
  2383. lfn[di] = 0;
  2384. for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */
  2385. dp->fn[i] = (i < di) ? '.' : ' ';
  2386. }
  2387. dp->fn[i] = cf | NS_DOT; /* This is a dot entry */
  2388. return FR_OK;
  2389. }
  2390. #endif
  2391. while (di) { /* Snip off trailing spaces and dots if exist */
  2392. wc = lfn[di - 1];
  2393. if (wc != ' ' && wc != '.') break;
  2394. di--;
  2395. }
  2396. lfn[di] = 0; /* LFN is created into the working buffer */
  2397. if (di == 0) return FR_INVALID_NAME; /* Reject null name */
  2398. /* Create SFN in directory form */
  2399. for (si = 0; lfn[si] == ' '; si++) ; /* Remove leading spaces */
  2400. if (si > 0 || lfn[si] == '.') cf |= NS_LOSS | NS_LFN; /* Is there any leading space or dot? */
  2401. while (di > 0 && lfn[di - 1] != '.') di--; /* Find last dot (di<=si: no extension) */
  2402. memset(dp->fn, ' ', 11);
  2403. i = b = 0; ni = 8;
  2404. for (;;) {
  2405. wc = lfn[si++]; /* Get an LFN character */
  2406. if (wc == 0) break; /* Break on end of the LFN */
  2407. if (wc == ' ' || (wc == '.' && si != di)) { /* Remove embedded spaces and dots */
  2408. cf |= NS_LOSS | NS_LFN;
  2409. continue;
  2410. }
  2411. if (i >= ni || si == di) { /* End of field? */
  2412. if (ni == 11) { /* Name extension overflow? */
  2413. cf |= NS_LOSS | NS_LFN;
  2414. break;
  2415. }
  2416. if (si != di) cf |= NS_LOSS | NS_LFN; /* Name body overflow? */
  2417. if (si > di) break; /* No name extension? */
  2418. si = di; i = 8; ni = 11; b <<= 2; /* Enter name extension */
  2419. continue;
  2420. }
  2421. if (wc >= 0x80) { /* Is this an extended character? */
  2422. cf |= NS_LFN; /* LFN entry needs to be created */
  2423. #if FF_CODE_PAGE == 0
  2424. if (ExCvt) { /* In SBCS cfg */
  2425. wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */
  2426. if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */
  2427. } else { /* In DBCS cfg */
  2428. wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */
  2429. }
  2430. #elif FF_CODE_PAGE < 900 /* In SBCS cfg */
  2431. wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */
  2432. if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */
  2433. #else /* In DBCS cfg */
  2434. wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */
  2435. #endif
  2436. }
  2437. if (wc >= 0x100) { /* Is this a DBC? */
  2438. if (i >= ni - 1) { /* Field overflow? */
  2439. cf |= NS_LOSS | NS_LFN;
  2440. i = ni; continue; /* Next field */
  2441. }
  2442. dp->fn[i++] = (BYTE)(wc >> 8); /* Put 1st byte */
  2443. } else { /* SBC */
  2444. if (wc == 0 || strchr("+,;=[]", (int)wc)) { /* Replace illegal characters for SFN */
  2445. wc = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
  2446. } else {
  2447. if (IsUpper(wc)) { /* ASCII upper case? */
  2448. b |= 2;
  2449. }
  2450. if (IsLower(wc)) { /* ASCII lower case? */
  2451. b |= 1; wc -= 0x20;
  2452. }
  2453. }
  2454. }
  2455. dp->fn[i++] = (BYTE)wc;
  2456. }
  2457. if (dp->fn[0] == DDEM) dp->fn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2458. if (ni == 8) b <<= 2; /* Shift capital flags if no extension */
  2459. if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) cf |= NS_LFN; /* LFN entry needs to be created if composite capitals */
  2460. if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended character, NT flags are created */
  2461. if (b & 0x01) cf |= NS_EXT; /* NT flag (Extension has small capital letters only) */
  2462. if (b & 0x04) cf |= NS_BODY; /* NT flag (Body has small capital letters only) */
  2463. }
  2464. dp->fn[NSFLAG] = cf; /* SFN is created into dp->fn[] */
  2465. return FR_OK;
  2466. #else /* FF_USE_LFN : Non-LFN configuration */
  2467. BYTE c, d, *sfn;
  2468. UINT ni, si, i;
  2469. const char *p;
  2470. /* Create file name in directory form */
  2471. p = *path; sfn = dp->fn;
  2472. memset(sfn, ' ', 11);
  2473. si = i = 0; ni = 8;
  2474. #if FF_FS_RPATH != 0
  2475. if (p[si] == '.') { /* Is this a dot entry? */
  2476. for (;;) {
  2477. c = (BYTE)p[si++];
  2478. if (c != '.' || si >= 3) break;
  2479. sfn[i++] = c;
  2480. }
  2481. if (!IsSeparator(c) && c > ' ') return FR_INVALID_NAME;
  2482. *path = p + si; /* Return pointer to the next segment */
  2483. sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */
  2484. return FR_OK;
  2485. }
  2486. #endif
  2487. for (;;) {
  2488. c = (BYTE)p[si++]; /* Get a byte */
  2489. if (c <= ' ') break; /* Break if end of the path name */
  2490. if (IsSeparator(c)) { /* Break if a separator is found */
  2491. while (IsSeparator(p[si])) si++; /* Skip duplicated separator if exist */
  2492. break;
  2493. }
  2494. if (c == '.' || i >= ni) { /* End of body or field overflow? */
  2495. if (ni == 11 || c != '.') return FR_INVALID_NAME; /* Field overflow or invalid dot? */
  2496. i = 8; ni = 11; /* Enter file extension field */
  2497. continue;
  2498. }
  2499. #if FF_CODE_PAGE == 0
  2500. if (ExCvt && c >= 0x80) { /* Is SBC extended character? */
  2501. c = ExCvt[c & 0x7F]; /* To upper SBC extended character */
  2502. }
  2503. #elif FF_CODE_PAGE < 900
  2504. if (c >= 0x80) { /* Is SBC extended character? */
  2505. c = ExCvt[c & 0x7F]; /* To upper SBC extended character */
  2506. }
  2507. #endif
  2508. if (dbc_1st(c)) { /* Check if it is a DBC 1st byte */
  2509. d = (BYTE)p[si++]; /* Get 2nd byte */
  2510. if (!dbc_2nd(d) || i >= ni - 1) return FR_INVALID_NAME; /* Reject invalid DBC */
  2511. sfn[i++] = c;
  2512. sfn[i++] = d;
  2513. } else { /* SBC */
  2514. if (strchr("*+,:;<=>[]|\"\?\x7F", (int)c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */
  2515. if (IsLower(c)) c -= 0x20; /* To upper */
  2516. sfn[i++] = c;
  2517. }
  2518. }
  2519. *path = &p[si]; /* Return pointer to the next segment */
  2520. if (i == 0) return FR_INVALID_NAME; /* Reject nul string */
  2521. if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */
  2522. sfn[NSFLAG] = (c <= ' ' || p[si] <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */
  2523. return FR_OK;
  2524. #endif /* FF_USE_LFN */
  2525. }
  2526. /*-----------------------------------------------------------------------*/
  2527. /* Follow a file path */
  2528. /*-----------------------------------------------------------------------*/
  2529. static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */
  2530. DIR* dp, /* Directory object to return last directory and found object */
  2531. const FATFS_TCHAR* path /* Full-path string to find a file or directory */
  2532. )
  2533. {
  2534. FRESULT res;
  2535. BYTE ns;
  2536. FATFS *fs = dp->obj.fs;
  2537. #if FF_FS_RPATH != 0
  2538. if (!IsSeparator(*path) && (FF_STR_VOLUME_ID != 2 || !IsTerminator(*path))) { /* Without heading separator */
  2539. dp->obj.sclust = fs->cdir; /* Start at the current directory */
  2540. } else
  2541. #endif
  2542. { /* With heading separator */
  2543. while (IsSeparator(*path)) path++; /* Strip separators */
  2544. dp->obj.sclust = 0; /* Start from the root directory */
  2545. }
  2546. #if FF_FS_EXFAT
  2547. dp->obj.n_frag = 0; /* Invalidate last fragment counter of the object */
  2548. #if FF_FS_RPATH != 0
  2549. if (fs->fs_type == FS_EXFAT && dp->obj.sclust) { /* exFAT: Retrieve the sub-directory's status */
  2550. DIR dj;
  2551. dp->obj.c_scl = fs->cdc_scl;
  2552. dp->obj.c_size = fs->cdc_size;
  2553. dp->obj.c_ofs = fs->cdc_ofs;
  2554. res = load_obj_xdir(&dj, &dp->obj);
  2555. if (res != FR_OK) return res;
  2556. dp->obj.objsize = ld_dword(fs->dirbuf + XDIR_FileSize);
  2557. dp->obj.stat = fs->dirbuf[XDIR_GenFlags] & 2;
  2558. }
  2559. #endif
  2560. #endif
  2561. if ((UINT)*path < ' ') { /* Null path name is the origin directory itself */
  2562. dp->fn[NSFLAG] = NS_NONAME;
  2563. res = dir_sdi(dp, 0);
  2564. } else { /* Follow path */
  2565. for (;;) {
  2566. res = create_name(dp, &path); /* Get a segment name of the path */
  2567. if (res != FR_OK) break;
  2568. res = dir_find(dp); /* Find an object with the segment name */
  2569. ns = dp->fn[NSFLAG];
  2570. if (res != FR_OK) { /* Failed to find the object */
  2571. if (res == FR_NO_FILE) { /* Object is not found */
  2572. if (FF_FS_RPATH && (ns & NS_DOT)) { /* If dot entry is not exist, stay there */
  2573. if (!(ns & NS_LAST)) continue; /* Continue to follow if not last segment */
  2574. dp->fn[NSFLAG] = NS_NONAME;
  2575. res = FR_OK;
  2576. } else { /* Could not find the object */
  2577. if (!(ns & NS_LAST)) res = FR_NO_PATH; /* Adjust error code if not last segment */
  2578. }
  2579. }
  2580. break;
  2581. }
  2582. if (ns & NS_LAST) break; /* Last segment matched. Function completed. */
  2583. /* Get into the sub-directory */
  2584. if (!(dp->obj.attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */
  2585. res = FR_NO_PATH; break;
  2586. }
  2587. #if FF_FS_EXFAT
  2588. if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */
  2589. dp->obj.c_scl = dp->obj.sclust;
  2590. dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat;
  2591. dp->obj.c_ofs = dp->blk_ofs;
  2592. init_alloc_info(fs, &dp->obj); /* Open next directory */
  2593. } else
  2594. #endif
  2595. {
  2596. dp->obj.sclust = ld_clust(fs, fs->win + dp->dptr % SS(fs)); /* Open next directory */
  2597. }
  2598. }
  2599. }
  2600. return res;
  2601. }
  2602. /*-----------------------------------------------------------------------*/
  2603. /* Get logical drive number from path name */
  2604. /*-----------------------------------------------------------------------*/
  2605. static int get_ldnumber ( /* Returns logical drive number (-1:invalid drive number or null pointer) */
  2606. const FATFS_TCHAR** path /* Pointer to pointer to the path name */
  2607. )
  2608. {
  2609. const FATFS_TCHAR *tp, *tt;
  2610. FATFS_TCHAR tc;
  2611. int i;
  2612. int vol = -1;
  2613. #if FF_STR_VOLUME_ID /* Find string volume ID */
  2614. const char *sp;
  2615. char c;
  2616. #endif
  2617. tt = tp = *path;
  2618. if (!tp) return vol; /* Invalid path name? */
  2619. do tc = *tt++; while (!IsTerminator(tc) && tc != ':'); /* Find a colon in the path */
  2620. if (tc == ':') { /* DOS/Windows style volume ID? */
  2621. i = FF_VOLUMES;
  2622. if (IsDigit(*tp) && tp + 2 == tt) { /* Is there a numeric volume ID + colon? */
  2623. i = (int)*tp - '0'; /* Get the LD number */
  2624. }
  2625. #if FF_STR_VOLUME_ID == 1 /* Arbitrary string is enabled */
  2626. else {
  2627. i = 0;
  2628. do {
  2629. sp = VolumeStr[i]; tp = *path; /* This string volume ID and path name */
  2630. do { /* Compare the volume ID with path name */
  2631. c = *sp++; tc = *tp++;
  2632. if (IsLower(c)) c -= 0x20;
  2633. if (IsLower(tc)) tc -= 0x20;
  2634. } while (c && (FATFS_TCHAR)c == tc);
  2635. } while ((c || tp != tt) && ++i < FF_VOLUMES); /* Repeat for each id until pattern match */
  2636. }
  2637. #endif
  2638. if (i < FF_VOLUMES) { /* If a volume ID is found, get the drive number and strip it */
  2639. vol = i; /* Drive number */
  2640. *path = tt; /* Snip the drive prefix off */
  2641. }
  2642. return vol;
  2643. }
  2644. #if FF_STR_VOLUME_ID == 2 /* Unix style volume ID is enabled */
  2645. if (*tp == '/') { /* Is there a volume ID? */
  2646. while (*(tp + 1) == '/') tp++; /* Skip duplicated separator */
  2647. i = 0;
  2648. do {
  2649. tt = tp; sp = VolumeStr[i]; /* Path name and this string volume ID */
  2650. do { /* Compare the volume ID with path name */
  2651. c = *sp++; tc = *(++tt);
  2652. if (IsLower(c)) c -= 0x20;
  2653. if (IsLower(tc)) tc -= 0x20;
  2654. } while (c && (FATFS_TCHAR)c == tc);
  2655. } while ((c || (tc != '/' && !IsTerminator(tc))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */
  2656. if (i < FF_VOLUMES) { /* If a volume ID is found, get the drive number and strip it */
  2657. vol = i; /* Drive number */
  2658. *path = tt; /* Snip the drive prefix off */
  2659. }
  2660. return vol;
  2661. }
  2662. #endif
  2663. /* No drive prefix is found */
  2664. #if FF_FS_RPATH != 0
  2665. vol = CurrVol; /* Default drive is current drive */
  2666. #else
  2667. vol = 0; /* Default drive is 0 */
  2668. #endif
  2669. return vol; /* Return the default drive */
  2670. }
  2671. /*-----------------------------------------------------------------------*/
  2672. /* GPT support functions */
  2673. /*-----------------------------------------------------------------------*/
  2674. #if FF_LBA64
  2675. /* Calculate CRC32 in byte-by-byte */
  2676. static DWORD crc32 ( /* Returns next CRC value */
  2677. DWORD crc, /* Current CRC value */
  2678. BYTE d /* A byte to be processed */
  2679. )
  2680. {
  2681. BYTE b;
  2682. for (b = 1; b; b <<= 1) {
  2683. crc ^= (d & b) ? 1 : 0;
  2684. crc = (crc & 1) ? crc >> 1 ^ 0xEDB88320 : crc >> 1;
  2685. }
  2686. return crc;
  2687. }
  2688. /* Check validity of GPT header */
  2689. static int test_gpt_header ( /* 0:Invalid, 1:Valid */
  2690. const BYTE* gpth /* Pointer to the GPT header */
  2691. )
  2692. {
  2693. UINT i;
  2694. DWORD bcc;
  2695. if (memcmp(gpth + GPTH_Sign, "EFI PART" "\0\0\1\0" "\x5C\0\0", 16)) return 0; /* Check sign, version (1.0) and length (92) */
  2696. for (i = 0, bcc = 0xFFFFFFFF; i < 92; i++) { /* Check header BCC */
  2697. bcc = crc32(bcc, i - GPTH_Bcc < 4 ? 0 : gpth[i]);
  2698. }
  2699. if (~bcc != ld_dword(gpth + GPTH_Bcc)) return 0;
  2700. if (ld_dword(gpth + GPTH_PteSize) != SZ_GPTE) return 0; /* Table entry size (must be SZ_GPTE bytes) */
  2701. if (ld_dword(gpth + GPTH_PtNum) > 128) return 0; /* Table size (must be 128 entries or less) */
  2702. return 1;
  2703. }
  2704. #if !FF_FS_READONLY && FF_USE_MKFS
  2705. /* Generate random value */
  2706. static DWORD make_rand (
  2707. DWORD seed, /* Seed value */
  2708. BYTE* buff, /* Output buffer */
  2709. UINT n /* Data length */
  2710. )
  2711. {
  2712. UINT r;
  2713. if (seed == 0) seed = 1;
  2714. do {
  2715. for (r = 0; r < 8; r++) seed = seed & 1 ? seed >> 1 ^ 0xA3000000 : seed >> 1; /* Shift 8 bits the 32-bit LFSR */
  2716. *buff++ = (BYTE)seed;
  2717. } while (--n);
  2718. return seed;
  2719. }
  2720. #endif
  2721. #endif
  2722. /*-----------------------------------------------------------------------*/
  2723. /* Load a sector and check if it is an FAT VBR */
  2724. /*-----------------------------------------------------------------------*/
  2725. /* Check what the sector is */
  2726. static UINT check_fs ( /* 0:FAT/FAT32 VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not FAT and invalid BS, 4:Disk error */
  2727. FATFS* fs, /* Filesystem object */
  2728. LBA_t sect /* Sector to load and check if it is an FAT-VBR or not */
  2729. )
  2730. {
  2731. WORD w, sign;
  2732. BYTE b;
  2733. fs->wflag = 0; fs->winsect = (LBA_t)0 - 1; /* Invaidate window */
  2734. if (move_window(fs, sect) != FR_OK) return 4; /* Load the boot sector */
  2735. sign = ld_word(fs->win + BS_55AA);
  2736. #if FF_FS_EXFAT
  2737. if (sign == 0xAA55 && !memcmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1; /* It is an exFAT VBR */
  2738. #endif
  2739. b = fs->win[BS_JmpBoot];
  2740. if (b == 0xEB || b == 0xE9 || b == 0xE8) { /* Valid JumpBoot code? (short jump, near jump or near call) */
  2741. if (sign == 0xAA55 && !memcmp(fs->win + BS_FilSysType32, "FAT32 ", 8)) {
  2742. return 0; /* It is an FAT32 VBR */
  2743. }
  2744. /* FAT volumes formatted with early MS-DOS lack BS_55AA and BS_FilSysType, so FAT VBR needs to be identified without them. */
  2745. w = ld_word(fs->win + BPB_BytsPerSec);
  2746. b = fs->win[BPB_SecPerClus];
  2747. if ((w & (w - 1)) == 0 && w >= FF_MIN_SS && w <= FF_MAX_SS /* Properness of sector size (512-4096 and 2^n) */
  2748. && b != 0 && (b & (b - 1)) == 0 /* Properness of cluster size (2^n) */
  2749. && ld_word(fs->win + BPB_RsvdSecCnt) != 0 /* Properness of reserved sectors (MNBZ) */
  2750. && (UINT)fs->win[BPB_NumFATs] - 1 <= 1 /* Properness of FATs (1 or 2) */
  2751. && ld_word(fs->win + BPB_RootEntCnt) != 0 /* Properness of root dir entries (MNBZ) */
  2752. && (ld_word(fs->win + BPB_TotSec16) >= 128 || ld_dword(fs->win + BPB_TotSec32) >= 0x10000) /* Properness of volume sectors (>=128) */
  2753. && ld_word(fs->win + BPB_FATSz16) != 0) { /* Properness of FAT size (MNBZ) */
  2754. return 0; /* It can be presumed an FAT VBR */
  2755. }
  2756. }
  2757. return sign == 0xAA55 ? 2 : 3; /* Not an FAT VBR (valid or invalid BS) */
  2758. }
  2759. /* Find an FAT volume */
  2760. /* (It supports only generic partitioning rules, MBR, GPT and SFD) */
  2761. static UINT find_volume ( /* Returns BS status found in the hosting drive */
  2762. FATFS* fs, /* Filesystem object */
  2763. UINT part /* Partition to fined = 0:auto, 1..:forced */
  2764. )
  2765. {
  2766. UINT fmt, i;
  2767. DWORD mbr_pt[4];
  2768. fmt = check_fs(fs, 0); /* Load sector 0 and check if it is an FAT VBR as SFD format */
  2769. if (fmt != 2 && (fmt >= 3 || part == 0)) return fmt; /* Returns if it is an FAT VBR as auto scan, not a BS or disk error */
  2770. /* Sector 0 is not an FAT VBR or forced partition number wants a partition */
  2771. #if FF_LBA64
  2772. if (fs->win[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */
  2773. DWORD n_ent, v_ent, ofs;
  2774. QWORD pt_lba;
  2775. if (move_window(fs, 1) != FR_OK) return 4; /* Load GPT header sector (next to MBR) */
  2776. if (!test_gpt_header(fs->win)) return 3; /* Check if GPT header is valid */
  2777. n_ent = ld_dword(fs->win + GPTH_PtNum); /* Number of entries */
  2778. pt_lba = ld_qword(fs->win + GPTH_PtOfs); /* Table location */
  2779. for (v_ent = i = 0; i < n_ent; i++) { /* Find FAT partition */
  2780. if (move_window(fs, pt_lba + i * SZ_GPTE / SS(fs)) != FR_OK) return 4; /* PT sector */
  2781. ofs = i * SZ_GPTE % SS(fs); /* Offset in the sector */
  2782. if (!memcmp(fs->win + ofs + GPTE_PtGuid, GUID_MS_Basic, 16)) { /* MS basic data partition? */
  2783. v_ent++;
  2784. fmt = check_fs(fs, ld_qword(fs->win + ofs + GPTE_FstLba)); /* Load VBR and check status */
  2785. if (part == 0 && fmt <= 1) return fmt; /* Auto search (valid FAT volume found first) */
  2786. if (part != 0 && v_ent == part) return fmt; /* Forced partition order (regardless of it is valid or not) */
  2787. }
  2788. }
  2789. return 3; /* Not found */
  2790. }
  2791. #endif
  2792. if (FF_MULTI_PARTITION && part > 4) return 3; /* MBR has 4 partitions max */
  2793. for (i = 0; i < 4; i++) { /* Load partition offset in the MBR */
  2794. mbr_pt[i] = ld_dword(fs->win + MBR_Table + i * SZ_PTE + PTE_StLba);
  2795. }
  2796. i = part ? part - 1 : 0; /* Table index to find first */
  2797. do { /* Find an FAT volume */
  2798. fmt = mbr_pt[i] ? check_fs(fs, mbr_pt[i]) : 3; /* Check if the partition is FAT */
  2799. } while (part == 0 && fmt >= 2 && ++i < 4);
  2800. return fmt;
  2801. }
  2802. /*-----------------------------------------------------------------------*/
  2803. /* Determine logical drive number and mount the volume if needed */
  2804. /*-----------------------------------------------------------------------*/
  2805. static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */
  2806. const FATFS_TCHAR** path, /* Pointer to pointer to the path name (drive number) */
  2807. FATFS** rfs, /* Pointer to pointer to the found filesystem object */
  2808. BYTE mode /* !=0: Check write protection for write access */
  2809. )
  2810. {
  2811. int vol;
  2812. DSTATUS stat;
  2813. LBA_t bsect;
  2814. DWORD tsect, sysect, fasize, nclst, szbfat;
  2815. WORD nrsv;
  2816. FATFS *fs;
  2817. UINT fmt;
  2818. /* Get logical drive number */
  2819. *rfs = 0;
  2820. vol = get_ldnumber(path);
  2821. if (vol < 0) return FR_INVALID_DRIVE;
  2822. /* Check if the filesystem object is valid or not */
  2823. fs = FatFs[vol]; /* Get pointer to the filesystem object */
  2824. if (!fs) return FR_NOT_ENABLED; /* Is the filesystem object available? */
  2825. #if FF_FS_REENTRANT
  2826. if (!lock_fs(fs)) return FR_TIMEOUT; /* Lock the volume */
  2827. #endif
  2828. *rfs = fs; /* Return pointer to the filesystem object */
  2829. mode &= (BYTE)~FA_READ; /* Desired access mode, write access or not */
  2830. if (fs->fs_type != 0) { /* If the volume has been mounted */
  2831. stat = disk_status(fs->pdrv);
  2832. if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized */
  2833. if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */
  2834. return FR_WRITE_PROTECTED;
  2835. }
  2836. return FR_OK; /* The filesystem object is already valid */
  2837. }
  2838. }
  2839. /* The filesystem object is not valid. */
  2840. /* Following code attempts to mount the volume. (find an FAT volume, analyze the BPB and initialize the filesystem object) */
  2841. fs->fs_type = 0; /* Clear the filesystem object */
  2842. fs->pdrv = LD2PD(vol); /* Volume hosting physical drive */
  2843. stat = disk_initialize(fs->pdrv); /* Initialize the physical drive */
  2844. if (stat & STA_NOINIT) { /* Check if the initialization succeeded */
  2845. return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */
  2846. }
  2847. if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check disk write protection if needed */
  2848. return FR_WRITE_PROTECTED;
  2849. }
  2850. #if FF_MAX_SS != FF_MIN_SS /* Get sector size (multiple sector size cfg only) */
  2851. if (disk_ioctl(fs->pdrv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK) return FR_DISK_ERR;
  2852. if (SS(fs) > FF_MAX_SS || SS(fs) < FF_MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;
  2853. #endif
  2854. /* Find an FAT volume on the drive */
  2855. fmt = find_volume(fs, LD2PT(vol));
  2856. if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */
  2857. if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */
  2858. bsect = fs->winsect; /* Volume offset */
  2859. /* An FAT volume is found (bsect). Following code initializes the filesystem object */
  2860. #if FF_FS_EXFAT
  2861. if (fmt == 1) {
  2862. QWORD maxlba;
  2863. DWORD so, cv, bcl, i;
  2864. for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */
  2865. if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;
  2866. if (ld_word(fs->win + BPB_FSVerEx) != 0x100) return FR_NO_FILESYSTEM; /* Check exFAT version (must be version 1.0) */
  2867. if (1 << fs->win[BPB_BytsPerSecEx] != SS(fs)) { /* (BPB_BytsPerSecEx must be equal to the physical sector size) */
  2868. return FR_NO_FILESYSTEM;
  2869. }
  2870. maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA of the volume + 1 */
  2871. if (!FF_LBA64 && maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be accessed in 32-bit LBA) */
  2872. fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */
  2873. fs->n_fats = fs->win[BPB_NumFATsEx]; /* Number of FATs */
  2874. if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */
  2875. fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */
  2876. if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768 sectors) */
  2877. nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */
  2878. if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */
  2879. fs->n_fatent = nclst + 2;
  2880. /* Boundaries and Limits */
  2881. fs->volbase = bsect;
  2882. fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);
  2883. fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);
  2884. if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size requiered) */
  2885. fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);
  2886. /* Get bitmap location and check if it is contiguous (implementation assumption) */
  2887. so = i = 0;
  2888. for (;;) { /* Find the bitmap entry in the root directory (in only first cluster) */
  2889. if (i == 0) {
  2890. if (so >= fs->csize) return FR_NO_FILESYSTEM; /* Not found? */
  2891. if (move_window(fs, clst2sect(fs, (DWORD)fs->dirbase) + so) != FR_OK) return FR_DISK_ERR;
  2892. so++;
  2893. }
  2894. if (fs->win[i] == ET_BITMAP) break; /* Is it a bitmap entry? */
  2895. i = (i + SZDIRE) % SS(fs); /* Next entry */
  2896. }
  2897. bcl = ld_dword(fs->win + i + 20); /* Bitmap cluster */
  2898. if (bcl < 2 || bcl >= fs->n_fatent) return FR_NO_FILESYSTEM; /* (Wrong cluster#) */
  2899. fs->bitbase = fs->database + fs->csize * (bcl - 2); /* Bitmap sector */
  2900. for (;;) { /* Check if bitmap is contiguous */
  2901. if (move_window(fs, fs->fatbase + bcl / (SS(fs) / 4)) != FR_OK) return FR_DISK_ERR;
  2902. cv = ld_dword(fs->win + bcl % (SS(fs) / 4) * 4);
  2903. if (cv == 0xFFFFFFFF) break; /* Last link? */
  2904. if (cv != ++bcl) return FR_NO_FILESYSTEM; /* Fragmented? */
  2905. }
  2906. #if !FF_FS_READONLY
  2907. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2908. #endif
  2909. fmt = FS_EXFAT; /* FAT sub-type */
  2910. } else
  2911. #endif /* FF_FS_EXFAT */
  2912. {
  2913. if (ld_word(fs->win + BPB_BytsPerSec) != SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_BytsPerSec must be equal to the physical sector size) */
  2914. fasize = ld_word(fs->win + BPB_FATSz16); /* Number of sectors per FAT */
  2915. if (fasize == 0) fasize = ld_dword(fs->win + BPB_FATSz32);
  2916. fs->fsize = fasize;
  2917. fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FATs */
  2918. if (fs->n_fats != 1 && fs->n_fats != 2) return FR_NO_FILESYSTEM; /* (Must be 1 or 2) */
  2919. fasize *= fs->n_fats; /* Number of sectors for FAT area */
  2920. fs->csize = fs->win[BPB_SecPerClus]; /* Cluster size */
  2921. if (fs->csize == 0 || (fs->csize & (fs->csize - 1))) return FR_NO_FILESYSTEM; /* (Must be power of 2) */
  2922. fs->n_rootdir = ld_word(fs->win + BPB_RootEntCnt); /* Number of root directory entries */
  2923. if (fs->n_rootdir % (SS(fs) / SZDIRE)) return FR_NO_FILESYSTEM; /* (Must be sector aligned) */
  2924. tsect = ld_word(fs->win + BPB_TotSec16); /* Number of sectors on the volume */
  2925. if (tsect == 0) tsect = ld_dword(fs->win + BPB_TotSec32);
  2926. nrsv = ld_word(fs->win + BPB_RsvdSecCnt); /* Number of reserved sectors */
  2927. if (nrsv == 0) return FR_NO_FILESYSTEM; /* (Must not be 0) */
  2928. /* Determine the FAT sub type */
  2929. sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZDIRE); /* RSV + FAT + DIR */
  2930. if (tsect < sysect) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2931. nclst = (tsect - sysect) / fs->csize; /* Number of clusters */
  2932. if (nclst == 0) return FR_NO_FILESYSTEM; /* (Invalid volume size) */
  2933. fmt = 0;
  2934. if (nclst <= MAX_FAT32) fmt = FS_FAT32;
  2935. if (nclst <= MAX_FAT16) fmt = FS_FAT16;
  2936. if (nclst <= MAX_FAT12) fmt = FS_FAT12;
  2937. if (fmt == 0) return FR_NO_FILESYSTEM;
  2938. /* Boundaries and Limits */
  2939. fs->n_fatent = nclst + 2; /* Number of FAT entries */
  2940. fs->volbase = bsect; /* Volume start sector */
  2941. fs->fatbase = bsect + nrsv; /* FAT start sector */
  2942. fs->database = bsect + sysect; /* Data start sector */
  2943. if (fmt == FS_FAT32) {
  2944. if (ld_word(fs->win + BPB_FSVer32) != 0) return FR_NO_FILESYSTEM; /* (Must be FAT32 revision 0.0) */
  2945. if (fs->n_rootdir != 0) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must be 0) */
  2946. fs->dirbase = ld_dword(fs->win + BPB_RootClus32); /* Root directory start cluster */
  2947. szbfat = fs->n_fatent * 4; /* (Needed FAT size) */
  2948. } else {
  2949. if (fs->n_rootdir == 0) return FR_NO_FILESYSTEM; /* (BPB_RootEntCnt must not be 0) */
  2950. fs->dirbase = fs->fatbase + fasize; /* Root directory start sector */
  2951. szbfat = (fmt == FS_FAT16) ? /* (Needed FAT size) */
  2952. fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
  2953. }
  2954. if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs)) return FR_NO_FILESYSTEM; /* (BPB_FATSz must not be less than the size needed) */
  2955. #if !FF_FS_READONLY
  2956. /* Get FSInfo if available */
  2957. fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */
  2958. fs->fsi_flag = 0x80;
  2959. #if (FF_FS_NOFSINFO & 3) != 3
  2960. if (fmt == FS_FAT32 /* Allow to update FSInfo only if BPB_FSInfo32 == 1 */
  2961. && ld_word(fs->win + BPB_FSInfo32) == 1
  2962. && move_window(fs, bsect + 1) == FR_OK)
  2963. {
  2964. fs->fsi_flag = 0;
  2965. if (ld_word(fs->win + BS_55AA) == 0xAA55 /* Load FSInfo data if available */
  2966. && ld_dword(fs->win + FSI_LeadSig) == 0x41615252
  2967. && ld_dword(fs->win + FSI_StrucSig) == 0x61417272)
  2968. {
  2969. #if (FF_FS_NOFSINFO & 1) == 0
  2970. fs->free_clst = ld_dword(fs->win + FSI_Free_Count);
  2971. #endif
  2972. #if (FF_FS_NOFSINFO & 2) == 0
  2973. fs->last_clst = ld_dword(fs->win + FSI_Nxt_Free);
  2974. #endif
  2975. }
  2976. }
  2977. #endif /* (FF_FS_NOFSINFO & 3) != 3 */
  2978. #endif /* !FF_FS_READONLY */
  2979. }
  2980. fs->fs_type = (BYTE)fmt;/* FAT sub-type */
  2981. fs->id = ++Fsid; /* Volume mount ID */
  2982. #if FF_USE_LFN == 1
  2983. fs->lfnbuf = LfnBuf; /* Static LFN working buffer */
  2984. #if FF_FS_EXFAT
  2985. fs->dirbuf = DirBuf; /* Static directory block scratchpad buuffer */
  2986. #endif
  2987. #endif
  2988. #if FF_FS_RPATH != 0
  2989. fs->cdir = 0; /* Initialize current directory */
  2990. #endif
  2991. #if FF_FS_LOCK != 0 /* Clear file lock semaphores */
  2992. clear_lock(fs);
  2993. #endif
  2994. return FR_OK;
  2995. }
  2996. /*-----------------------------------------------------------------------*/
  2997. /* Check if the file/directory object is valid or not */
  2998. /*-----------------------------------------------------------------------*/
  2999. static FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */
  3000. FFOBJID* obj, /* Pointer to the FFOBJID, the 1st member in the FIL/DIR object, to check validity */
  3001. FATFS** rfs /* Pointer to pointer to the owner filesystem object to return */
  3002. )
  3003. {
  3004. FRESULT res = FR_INVALID_OBJECT;
  3005. if (obj && obj->fs && obj->fs->fs_type && obj->id == obj->fs->id) { /* Test if the object is valid */
  3006. #if FF_FS_REENTRANT
  3007. if (lock_fs(obj->fs)) { /* Obtain the filesystem object */
  3008. if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */
  3009. res = FR_OK;
  3010. } else {
  3011. unlock_fs(obj->fs, FR_OK);
  3012. }
  3013. } else {
  3014. res = FR_TIMEOUT;
  3015. }
  3016. #else
  3017. if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */
  3018. res = FR_OK;
  3019. }
  3020. #endif
  3021. }
  3022. *rfs = (res == FR_OK) ? obj->fs : 0; /* Corresponding filesystem object */
  3023. return res;
  3024. }
  3025. /*---------------------------------------------------------------------------
  3026. Public Functions (FatFs API)
  3027. ----------------------------------------------------------------------------*/
  3028. /*-----------------------------------------------------------------------*/
  3029. /* Mount/Unmount a Logical Drive */
  3030. /*-----------------------------------------------------------------------*/
  3031. FRESULT f_mount (
  3032. FATFS* fs, /* Pointer to the filesystem object to be registered (NULL:unmount)*/
  3033. const FATFS_TCHAR* path, /* Logical drive number to be mounted/unmounted */
  3034. BYTE opt /* Mount option: 0=Do not mount (delayed mount), 1=Mount immediately */
  3035. )
  3036. {
  3037. FATFS *cfs;
  3038. int vol;
  3039. FRESULT res;
  3040. const FATFS_TCHAR *rp = path;
  3041. /* Get logical drive number */
  3042. vol = get_ldnumber(&rp);
  3043. if (vol < 0) return FR_INVALID_DRIVE;
  3044. cfs = FatFs[vol]; /* Pointer to fs object */
  3045. if (cfs) {
  3046. #if FF_FS_LOCK != 0
  3047. clear_lock(cfs);
  3048. #endif
  3049. #if FF_FS_REENTRANT /* Discard sync object of the current volume */
  3050. if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;
  3051. #endif
  3052. cfs->fs_type = 0; /* Clear old fs object */
  3053. }
  3054. if (fs) {
  3055. fs->fs_type = 0; /* Clear new fs object */
  3056. #if FF_FS_REENTRANT /* Create sync object for the new volume */
  3057. if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;
  3058. #endif
  3059. }
  3060. FatFs[vol] = fs; /* Register new fs object */
  3061. if (opt == 0) return FR_OK; /* Do not mount now, it will be mounted later */
  3062. res = mount_volume(&path, &fs, 0); /* Force mounted the volume */
  3063. LEAVE_FF(fs, res);
  3064. }
  3065. /*-----------------------------------------------------------------------*/
  3066. /* Open or Create a File */
  3067. /*-----------------------------------------------------------------------*/
  3068. FRESULT f_open (
  3069. FIL* fp, /* Pointer to the blank file object */
  3070. const FATFS_TCHAR* path, /* Pointer to the file name */
  3071. BYTE mode /* Access mode and open mode flags */
  3072. )
  3073. {
  3074. FRESULT res;
  3075. DIR dj;
  3076. FATFS *fs;
  3077. #if !FF_FS_READONLY
  3078. DWORD cl, bcs, clst, tm;
  3079. LBA_t sc;
  3080. FSIZE_t ofs;
  3081. #endif
  3082. DEF_NAMBUF
  3083. if (!fp) return FR_INVALID_OBJECT;
  3084. /* Get logical drive number */
  3085. mode &= FF_FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
  3086. res = mount_volume(&path, &fs, mode);
  3087. if (res == FR_OK) {
  3088. dj.obj.fs = fs;
  3089. INIT_NAMBUF(fs);
  3090. res = follow_path(&dj, path); /* Follow the file path */
  3091. #if !FF_FS_READONLY /* Read/Write configuration */
  3092. if (res == FR_OK) {
  3093. if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */
  3094. res = FR_INVALID_NAME;
  3095. }
  3096. #if FF_FS_LOCK != 0
  3097. else {
  3098. res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */
  3099. }
  3100. #endif
  3101. }
  3102. /* Create or Open a file */
  3103. if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {
  3104. if (res != FR_OK) { /* No file, create new */
  3105. if (res == FR_NO_FILE) { /* There is no file to open, create a new entry */
  3106. #if FF_FS_LOCK != 0
  3107. res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
  3108. #else
  3109. res = dir_register(&dj);
  3110. #endif
  3111. }
  3112. mode |= FA_CREATE_ALWAYS; /* File is created */
  3113. }
  3114. else { /* Any object with the same name is already existing */
  3115. if (dj.obj.attr & (AM_RDO | AM_DIR)) { /* Cannot overwrite it (R/O or DIR) */
  3116. res = FR_DENIED;
  3117. } else {
  3118. if (mode & FA_CREATE_NEW) res = FR_EXIST; /* Cannot create as new file */
  3119. }
  3120. }
  3121. if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) { /* Truncate the file if overwrite mode */
  3122. #if FF_FS_EXFAT
  3123. if (fs->fs_type == FS_EXFAT) {
  3124. /* Get current allocation info */
  3125. fp->obj.fs = fs;
  3126. init_alloc_info(fs, &fp->obj);
  3127. /* Set directory entry block initial state */
  3128. memset(fs->dirbuf + 2, 0, 30); /* Clear 85 entry except for NumSec */
  3129. memset(fs->dirbuf + 38, 0, 26); /* Clear C0 entry except for NumName and NameHash */
  3130. fs->dirbuf[XDIR_Attr] = AM_ARC;
  3131. st_dword(fs->dirbuf + XDIR_CrtTime, GET_FATTIME());
  3132. fs->dirbuf[XDIR_GenFlags] = 1;
  3133. res = store_xdir(&dj);
  3134. if (res == FR_OK && fp->obj.sclust != 0) { /* Remove the cluster chain if exist */
  3135. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  3136. fs->last_clst = fp->obj.sclust - 1; /* Reuse the cluster hole */
  3137. }
  3138. } else
  3139. #endif
  3140. {
  3141. /* Set directory entry initial state */
  3142. tm = GET_FATTIME(); /* Set created time */
  3143. st_dword(dj.dir + DIR_CrtTime, tm);
  3144. st_dword(dj.dir + DIR_ModTime, tm);
  3145. cl = ld_clust(fs, dj.dir); /* Get current cluster chain */
  3146. dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */
  3147. st_clust(fs, dj.dir, 0); /* Reset file allocation info */
  3148. st_dword(dj.dir + DIR_FileSize, 0);
  3149. fs->wflag = 1;
  3150. if (cl != 0) { /* Remove the cluster chain if exist */
  3151. sc = fs->winsect;
  3152. res = remove_chain(&dj.obj, cl, 0);
  3153. if (res == FR_OK) {
  3154. res = move_window(fs, sc);
  3155. fs->last_clst = cl - 1; /* Reuse the cluster hole */
  3156. }
  3157. }
  3158. }
  3159. }
  3160. }
  3161. else { /* Open an existing file */
  3162. if (res == FR_OK) { /* Is the object exsiting? */
  3163. if (dj.obj.attr & AM_DIR) { /* File open against a directory */
  3164. res = FR_NO_FILE;
  3165. } else {
  3166. if ((mode & FA_WRITE) && (dj.obj.attr & AM_RDO)) { /* Write mode open against R/O file */
  3167. res = FR_DENIED;
  3168. }
  3169. }
  3170. }
  3171. }
  3172. if (res == FR_OK) {
  3173. if (mode & FA_CREATE_ALWAYS) mode |= FA_MODIFIED; /* Set file change flag if created or overwritten */
  3174. fp->dir_sect = fs->winsect; /* Pointer to the directory entry */
  3175. fp->dir_ptr = dj.dir;
  3176. #if FF_FS_LOCK != 0
  3177. fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0); /* Lock the file for this session */
  3178. if (fp->obj.lockid == 0) res = FR_INT_ERR;
  3179. #endif
  3180. }
  3181. #else /* R/O configuration */
  3182. if (res == FR_OK) {
  3183. if (dj.fn[NSFLAG] & NS_NONAME) { /* Is it origin directory itself? */
  3184. res = FR_INVALID_NAME;
  3185. } else {
  3186. if (dj.obj.attr & AM_DIR) { /* Is it a directory? */
  3187. res = FR_NO_FILE;
  3188. }
  3189. }
  3190. }
  3191. #endif
  3192. if (res == FR_OK) {
  3193. #if FF_FS_EXFAT
  3194. if (fs->fs_type == FS_EXFAT) {
  3195. fp->obj.c_scl = dj.obj.sclust; /* Get containing directory info */
  3196. fp->obj.c_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  3197. fp->obj.c_ofs = dj.blk_ofs;
  3198. init_alloc_info(fs, &fp->obj);
  3199. } else
  3200. #endif
  3201. {
  3202. fp->obj.sclust = ld_clust(fs, dj.dir); /* Get object allocation info */
  3203. fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);
  3204. }
  3205. #if FF_USE_FASTSEEK
  3206. fp->cltbl = 0; /* Disable fast seek mode */
  3207. #endif
  3208. fp->obj.fs = fs; /* Validate the file object */
  3209. fp->obj.id = fs->id;
  3210. fp->flag = mode; /* Set file access mode */
  3211. fp->err = 0; /* Clear error flag */
  3212. fp->sect = 0; /* Invalidate current data sector */
  3213. fp->fptr = 0; /* Set file pointer top of the file */
  3214. #if !FF_FS_READONLY
  3215. #if !FF_FS_TINY
  3216. memset(fp->buf, 0, sizeof fp->buf); /* Clear sector buffer */
  3217. #endif
  3218. if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */
  3219. fp->fptr = fp->obj.objsize; /* Offset to seek */
  3220. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size in byte */
  3221. clst = fp->obj.sclust; /* Follow the cluster chain */
  3222. for (ofs = fp->obj.objsize; res == FR_OK && ofs > bcs; ofs -= bcs) {
  3223. clst = get_fat(&fp->obj, clst);
  3224. if (clst <= 1) res = FR_INT_ERR;
  3225. if (clst == 0xFFFFFFFF) res = FR_DISK_ERR;
  3226. }
  3227. fp->clust = clst;
  3228. if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */
  3229. sc = clst2sect(fs, clst);
  3230. if (sc == 0) {
  3231. res = FR_INT_ERR;
  3232. } else {
  3233. fp->sect = sc + (DWORD)(ofs / SS(fs));
  3234. #if !FF_FS_TINY
  3235. if (disk_read(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) res = FR_DISK_ERR;
  3236. #endif
  3237. }
  3238. }
  3239. #if FF_FS_LOCK != 0
  3240. if (res != FR_OK) dec_lock(fp->obj.lockid); /* Decrement file open counter if seek failed */
  3241. #endif
  3242. }
  3243. #endif
  3244. }
  3245. FREE_NAMBUF();
  3246. }
  3247. if (res != FR_OK) fp->obj.fs = 0; /* Invalidate file object on error */
  3248. LEAVE_FF(fs, res);
  3249. }
  3250. /*-----------------------------------------------------------------------*/
  3251. /* Read File */
  3252. /*-----------------------------------------------------------------------*/
  3253. FRESULT f_read (
  3254. FIL* fp, /* Open file to be read */
  3255. void* buff, /* Data buffer to store the read data */
  3256. UINT btr, /* Number of bytes to read */
  3257. UINT* br /* Number of bytes read */
  3258. )
  3259. {
  3260. FRESULT res;
  3261. FATFS *fs;
  3262. DWORD clst;
  3263. LBA_t sect;
  3264. FSIZE_t remain;
  3265. UINT rcnt, cc, csect;
  3266. BYTE *rbuff = (BYTE*)buff;
  3267. *br = 0; /* Clear read byte counter */
  3268. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3269. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3270. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3271. remain = fp->obj.objsize - fp->fptr;
  3272. if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */
  3273. for ( ; btr > 0; btr -= rcnt, *br += rcnt, rbuff += rcnt, fp->fptr += rcnt) { /* Repeat until btr bytes read */
  3274. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  3275. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  3276. if (csect == 0) { /* On the cluster boundary? */
  3277. if (fp->fptr == 0) { /* On the top of the file? */
  3278. clst = fp->obj.sclust; /* Follow cluster chain from the origin */
  3279. } else { /* Middle or end of the file */
  3280. #if FF_USE_FASTSEEK
  3281. if (fp->cltbl) {
  3282. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  3283. } else
  3284. #endif
  3285. {
  3286. clst = get_fat(&fp->obj, fp->clust); /* Follow cluster chain on the FAT */
  3287. }
  3288. }
  3289. if (clst < 2) ABORT(fs, FR_INT_ERR);
  3290. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3291. fp->clust = clst; /* Update current cluster */
  3292. }
  3293. sect = clst2sect(fs, fp->clust); /* Get current sector */
  3294. if (sect == 0) ABORT(fs, FR_INT_ERR);
  3295. sect += csect;
  3296. cc = btr / SS(fs); /* When remaining bytes >= sector size, */
  3297. if (cc > 0) { /* Read maximum contiguous sectors directly */
  3298. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3299. cc = fs->csize - csect;
  3300. }
  3301. if (disk_read(fs->pdrv, rbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3302. #if !FF_FS_READONLY && FF_FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */
  3303. #if FF_FS_TINY
  3304. if (fs->wflag && fs->winsect - sect < cc) {
  3305. memcpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));
  3306. }
  3307. #else
  3308. if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {
  3309. memcpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));
  3310. }
  3311. #endif
  3312. #endif
  3313. rcnt = SS(fs) * cc; /* Number of bytes transferred */
  3314. continue;
  3315. }
  3316. #if !FF_FS_TINY
  3317. if (fp->sect != sect) { /* Load data sector if not in cache */
  3318. #if !FF_FS_READONLY
  3319. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3320. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3321. fp->flag &= (BYTE)~FA_DIRTY;
  3322. }
  3323. #endif
  3324. if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3325. }
  3326. #endif
  3327. fp->sect = sect;
  3328. }
  3329. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
  3330. if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */
  3331. #if FF_FS_TINY
  3332. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3333. memcpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  3334. #else
  3335. memcpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */
  3336. #endif
  3337. }
  3338. LEAVE_FF(fs, FR_OK);
  3339. }
  3340. #if !FF_FS_READONLY
  3341. /*-----------------------------------------------------------------------*/
  3342. /* Write File */
  3343. /*-----------------------------------------------------------------------*/
  3344. FRESULT f_write (
  3345. FIL* fp, /* Open file to be written */
  3346. const void* buff, /* Data to be written */
  3347. UINT btw, /* Number of bytes to write */
  3348. UINT* bw /* Number of bytes written */
  3349. )
  3350. {
  3351. FRESULT res;
  3352. FATFS *fs;
  3353. DWORD clst;
  3354. LBA_t sect;
  3355. UINT wcnt, cc, csect;
  3356. const BYTE *wbuff = (const BYTE*)buff;
  3357. *bw = 0; /* Clear write byte counter */
  3358. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3359. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res); /* Check validity */
  3360. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  3361. /* Check fptr wrap-around (file size cannot reach 4 GiB at FAT volume) */
  3362. if ((!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) && (DWORD)(fp->fptr + btw) < (DWORD)fp->fptr) {
  3363. btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);
  3364. }
  3365. for ( ; btw > 0; btw -= wcnt, *bw += wcnt, wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize) { /* Repeat until all data written */
  3366. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  3367. csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */
  3368. if (csect == 0) { /* On the cluster boundary? */
  3369. if (fp->fptr == 0) { /* On the top of the file? */
  3370. clst = fp->obj.sclust; /* Follow from the origin */
  3371. if (clst == 0) { /* If no cluster is allocated, */
  3372. clst = create_chain(&fp->obj, 0); /* create a new cluster chain */
  3373. }
  3374. } else { /* On the middle or end of the file */
  3375. #if FF_USE_FASTSEEK
  3376. if (fp->cltbl) {
  3377. clst = clmt_clust(fp, fp->fptr); /* Get cluster# from the CLMT */
  3378. } else
  3379. #endif
  3380. {
  3381. clst = create_chain(&fp->obj, fp->clust); /* Follow or stretch cluster chain on the FAT */
  3382. }
  3383. }
  3384. if (clst == 0) break; /* Could not allocate a new cluster (disk full) */
  3385. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3386. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3387. fp->clust = clst; /* Update current cluster */
  3388. if (fp->obj.sclust == 0) fp->obj.sclust = clst; /* Set start cluster if the first write */
  3389. }
  3390. #if FF_FS_TINY
  3391. if (fs->winsect == fp->sect && sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Write-back sector cache */
  3392. #else
  3393. if (fp->flag & FA_DIRTY) { /* Write-back sector cache */
  3394. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3395. fp->flag &= (BYTE)~FA_DIRTY;
  3396. }
  3397. #endif
  3398. sect = clst2sect(fs, fp->clust); /* Get current sector */
  3399. if (sect == 0) ABORT(fs, FR_INT_ERR);
  3400. sect += csect;
  3401. cc = btw / SS(fs); /* When remaining bytes >= sector size, */
  3402. if (cc > 0) { /* Write maximum contiguous sectors directly */
  3403. if (csect + cc > fs->csize) { /* Clip at cluster boundary */
  3404. cc = fs->csize - csect;
  3405. }
  3406. if (disk_write(fs->pdrv, wbuff, sect, cc) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3407. #if FF_FS_MINIMIZE <= 2
  3408. #if FF_FS_TINY
  3409. if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3410. memcpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));
  3411. fs->wflag = 0;
  3412. }
  3413. #else
  3414. if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
  3415. memcpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));
  3416. fp->flag &= (BYTE)~FA_DIRTY;
  3417. }
  3418. #endif
  3419. #endif
  3420. wcnt = SS(fs) * cc; /* Number of bytes transferred */
  3421. continue;
  3422. }
  3423. #if FF_FS_TINY
  3424. if (fp->fptr >= fp->obj.objsize) { /* Avoid silly cache filling on the growing edge */
  3425. if (sync_window(fs) != FR_OK) ABORT(fs, FR_DISK_ERR);
  3426. fs->winsect = sect;
  3427. }
  3428. #else
  3429. if (fp->sect != sect && /* Fill sector cache with file data */
  3430. fp->fptr < fp->obj.objsize &&
  3431. disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) {
  3432. ABORT(fs, FR_DISK_ERR);
  3433. }
  3434. #endif
  3435. fp->sect = sect;
  3436. }
  3437. wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
  3438. if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */
  3439. #if FF_FS_TINY
  3440. if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */
  3441. memcpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3442. fs->wflag = 1;
  3443. #else
  3444. memcpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */
  3445. fp->flag |= FA_DIRTY;
  3446. #endif
  3447. }
  3448. fp->flag |= FA_MODIFIED; /* Set file change flag */
  3449. LEAVE_FF(fs, FR_OK);
  3450. }
  3451. /*-----------------------------------------------------------------------*/
  3452. /* Synchronize the File */
  3453. /*-----------------------------------------------------------------------*/
  3454. FRESULT f_sync (
  3455. FIL* fp /* Open file to be synced */
  3456. )
  3457. {
  3458. FRESULT res;
  3459. FATFS *fs;
  3460. DWORD tm;
  3461. BYTE *dir;
  3462. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3463. if (res == FR_OK) {
  3464. if (fp->flag & FA_MODIFIED) { /* Is there any change to the file? */
  3465. #if !FF_FS_TINY
  3466. if (fp->flag & FA_DIRTY) { /* Write-back cached data if needed */
  3467. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) LEAVE_FF(fs, FR_DISK_ERR);
  3468. fp->flag &= (BYTE)~FA_DIRTY;
  3469. }
  3470. #endif
  3471. /* Update the directory entry */
  3472. tm = GET_FATTIME(); /* Modified time */
  3473. #if FF_FS_EXFAT
  3474. if (fs->fs_type == FS_EXFAT) {
  3475. res = fill_first_frag(&fp->obj); /* Fill first fragment on the FAT if needed */
  3476. if (res == FR_OK) {
  3477. res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  3478. }
  3479. if (res == FR_OK) {
  3480. DIR dj;
  3481. DEF_NAMBUF
  3482. INIT_NAMBUF(fs);
  3483. res = load_obj_xdir(&dj, &fp->obj); /* Load directory entry block */
  3484. if (res == FR_OK) {
  3485. fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */
  3486. fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation information */
  3487. st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust); /* Update start cluster */
  3488. st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize); /* Update file size */
  3489. st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize); /* (FatFs does not support Valid File Size feature) */
  3490. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */
  3491. fs->dirbuf[XDIR_ModTime10] = 0;
  3492. st_dword(fs->dirbuf + XDIR_AccTime, 0);
  3493. res = store_xdir(&dj); /* Restore it to the directory */
  3494. if (res == FR_OK) {
  3495. res = sync_fs(fs);
  3496. fp->flag &= (BYTE)~FA_MODIFIED;
  3497. }
  3498. }
  3499. FREE_NAMBUF();
  3500. }
  3501. } else
  3502. #endif
  3503. {
  3504. res = move_window(fs, fp->dir_sect);
  3505. if (res == FR_OK) {
  3506. dir = fp->dir_ptr;
  3507. dir[DIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */
  3508. st_clust(fp->obj.fs, dir, fp->obj.sclust); /* Update file allocation information */
  3509. st_dword(dir + DIR_FileSize, (DWORD)fp->obj.objsize); /* Update file size */
  3510. st_dword(dir + DIR_ModTime, tm); /* Update modified time */
  3511. st_word(dir + DIR_LstAccDate, 0);
  3512. fs->wflag = 1;
  3513. res = sync_fs(fs); /* Restore it to the directory */
  3514. fp->flag &= (BYTE)~FA_MODIFIED;
  3515. }
  3516. }
  3517. }
  3518. }
  3519. LEAVE_FF(fs, res);
  3520. }
  3521. #endif /* !FF_FS_READONLY */
  3522. /*-----------------------------------------------------------------------*/
  3523. /* Close File */
  3524. /*-----------------------------------------------------------------------*/
  3525. FRESULT f_close (
  3526. FIL* fp /* Open file to be closed */
  3527. )
  3528. {
  3529. FRESULT res;
  3530. FATFS *fs;
  3531. #if !FF_FS_READONLY
  3532. res = f_sync(fp); /* Flush cached data */
  3533. if (res == FR_OK)
  3534. #endif
  3535. {
  3536. res = validate(&fp->obj, &fs); /* Lock volume */
  3537. if (res == FR_OK) {
  3538. #if FF_FS_LOCK != 0
  3539. res = dec_lock(fp->obj.lockid); /* Decrement file open counter */
  3540. if (res == FR_OK) fp->obj.fs = 0; /* Invalidate file object */
  3541. #else
  3542. fp->obj.fs = 0; /* Invalidate file object */
  3543. #endif
  3544. #if FF_FS_REENTRANT
  3545. unlock_fs(fs, FR_OK); /* Unlock volume */
  3546. #endif
  3547. }
  3548. }
  3549. return res;
  3550. }
  3551. #if FF_FS_RPATH >= 1
  3552. /*-----------------------------------------------------------------------*/
  3553. /* Change Current Directory or Current Drive, Get Current Directory */
  3554. /*-----------------------------------------------------------------------*/
  3555. FRESULT f_chdrive (
  3556. const FATFS_TCHAR* path /* Drive number to set */
  3557. )
  3558. {
  3559. int vol;
  3560. /* Get logical drive number */
  3561. vol = get_ldnumber(&path);
  3562. if (vol < 0) return FR_INVALID_DRIVE;
  3563. CurrVol = (BYTE)vol; /* Set it as current volume */
  3564. return FR_OK;
  3565. }
  3566. FRESULT f_chdir (
  3567. const FATFS_TCHAR* path /* Pointer to the directory path */
  3568. )
  3569. {
  3570. #if FF_STR_VOLUME_ID == 2
  3571. UINT i;
  3572. #endif
  3573. FRESULT res;
  3574. DIR dj;
  3575. FATFS *fs;
  3576. DEF_NAMBUF
  3577. /* Get logical drive */
  3578. res = mount_volume(&path, &fs, 0);
  3579. if (res == FR_OK) {
  3580. dj.obj.fs = fs;
  3581. INIT_NAMBUF(fs);
  3582. res = follow_path(&dj, path); /* Follow the path */
  3583. if (res == FR_OK) { /* Follow completed */
  3584. if (dj.fn[NSFLAG] & NS_NONAME) { /* Is it the start directory itself? */
  3585. fs->cdir = dj.obj.sclust;
  3586. #if FF_FS_EXFAT
  3587. if (fs->fs_type == FS_EXFAT) {
  3588. fs->cdc_scl = dj.obj.c_scl;
  3589. fs->cdc_size = dj.obj.c_size;
  3590. fs->cdc_ofs = dj.obj.c_ofs;
  3591. }
  3592. #endif
  3593. } else {
  3594. if (dj.obj.attr & AM_DIR) { /* It is a sub-directory */
  3595. #if FF_FS_EXFAT
  3596. if (fs->fs_type == FS_EXFAT) {
  3597. fs->cdir = ld_dword(fs->dirbuf + XDIR_FstClus); /* Sub-directory cluster */
  3598. fs->cdc_scl = dj.obj.sclust; /* Save containing directory information */
  3599. fs->cdc_size = ((DWORD)dj.obj.objsize & 0xFFFFFF00) | dj.obj.stat;
  3600. fs->cdc_ofs = dj.blk_ofs;
  3601. } else
  3602. #endif
  3603. {
  3604. fs->cdir = ld_clust(fs, dj.dir); /* Sub-directory cluster */
  3605. }
  3606. } else {
  3607. res = FR_NO_PATH; /* Reached but a file */
  3608. }
  3609. }
  3610. }
  3611. FREE_NAMBUF();
  3612. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3613. #if FF_STR_VOLUME_ID == 2 /* Also current drive is changed if in Unix style volume ID */
  3614. if (res == FR_OK) {
  3615. for (i = FF_VOLUMES - 1; i && fs != FatFs[i]; i--) ; /* Set current drive */
  3616. CurrVol = (BYTE)i;
  3617. }
  3618. #endif
  3619. }
  3620. LEAVE_FF(fs, res);
  3621. }
  3622. #if FF_FS_RPATH >= 2
  3623. FRESULT f_getcwd (
  3624. FATFS_TCHAR* buff, /* Pointer to the directory path */
  3625. UINT len /* Size of buff in unit of FATFS_TCHAR */
  3626. )
  3627. {
  3628. FRESULT res;
  3629. DIR dj;
  3630. FATFS *fs;
  3631. UINT i, n;
  3632. DWORD ccl;
  3633. FATFS_TCHAR *tp = buff;
  3634. #if FF_VOLUMES >= 2
  3635. UINT vl;
  3636. #if FF_STR_VOLUME_ID
  3637. const char *vp;
  3638. #endif
  3639. #endif
  3640. FILINFO fno;
  3641. DEF_NAMBUF
  3642. /* Get logical drive */
  3643. buff[0] = 0; /* Set null string to get current volume */
  3644. res = mount_volume((const FATFS_TCHAR**)&buff, &fs, 0); /* Get current volume */
  3645. if (res == FR_OK) {
  3646. dj.obj.fs = fs;
  3647. INIT_NAMBUF(fs);
  3648. /* Follow parent directories and create the path */
  3649. i = len; /* Bottom of buffer (directory stack base) */
  3650. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* (Cannot do getcwd on exFAT and returns root path) */
  3651. dj.obj.sclust = fs->cdir; /* Start to follow upper directory from current directory */
  3652. while ((ccl = dj.obj.sclust) != 0) { /* Repeat while current directory is a sub-directory */
  3653. res = dir_sdi(&dj, 1 * SZDIRE); /* Get parent directory */
  3654. if (res != FR_OK) break;
  3655. res = move_window(fs, dj.sect);
  3656. if (res != FR_OK) break;
  3657. dj.obj.sclust = ld_clust(fs, dj.dir); /* Goto parent directory */
  3658. res = dir_sdi(&dj, 0);
  3659. if (res != FR_OK) break;
  3660. do { /* Find the entry links to the child directory */
  3661. res = DIR_READ_FILE(&dj);
  3662. if (res != FR_OK) break;
  3663. if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */
  3664. res = dir_next(&dj, 0);
  3665. } while (res == FR_OK);
  3666. if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
  3667. if (res != FR_OK) break;
  3668. get_fileinfo(&dj, &fno); /* Get the directory name and push it to the buffer */
  3669. for (n = 0; fno.fname[n]; n++) ; /* Name length */
  3670. if (i < n + 1) { /* Insufficient space to store the path name? */
  3671. res = FR_NOT_ENOUGH_CORE; break;
  3672. }
  3673. while (n) buff[--i] = fno.fname[--n]; /* Stack the name */
  3674. buff[--i] = '/';
  3675. }
  3676. }
  3677. if (res == FR_OK) {
  3678. if (i == len) buff[--i] = '/'; /* Is it the root-directory? */
  3679. #if FF_VOLUMES >= 2 /* Put drive prefix */
  3680. vl = 0;
  3681. #if FF_STR_VOLUME_ID >= 1 /* String volume ID */
  3682. for (n = 0, vp = (const char*)VolumeStr[CurrVol]; vp[n]; n++) ;
  3683. if (i >= n + 2) {
  3684. if (FF_STR_VOLUME_ID == 2) *tp++ = (FATFS_TCHAR)'/';
  3685. for (vl = 0; vl < n; *tp++ = (FATFS_TCHAR)vp[vl], vl++) ;
  3686. if (FF_STR_VOLUME_ID == 1) *tp++ = (FATFS_TCHAR)':';
  3687. vl++;
  3688. }
  3689. #else /* Numeric volume ID */
  3690. if (i >= 3) {
  3691. *tp++ = (FATFS_TCHAR)'0' + CurrVol;
  3692. *tp++ = (FATFS_TCHAR)':';
  3693. vl = 2;
  3694. }
  3695. #endif
  3696. if (vl == 0) res = FR_NOT_ENOUGH_CORE;
  3697. #endif
  3698. /* Add current directory path */
  3699. if (res == FR_OK) {
  3700. do *tp++ = buff[i++]; while (i < len); /* Copy stacked path string */
  3701. }
  3702. }
  3703. FREE_NAMBUF();
  3704. }
  3705. *tp = 0;
  3706. LEAVE_FF(fs, res);
  3707. }
  3708. #endif /* FF_FS_RPATH >= 2 */
  3709. #endif /* FF_FS_RPATH >= 1 */
  3710. #if FF_FS_MINIMIZE <= 2
  3711. /*-----------------------------------------------------------------------*/
  3712. /* Seek File Read/Write Pointer */
  3713. /*-----------------------------------------------------------------------*/
  3714. FRESULT f_lseek (
  3715. FIL* fp, /* Pointer to the file object */
  3716. FSIZE_t ofs /* File pointer from top of file */
  3717. )
  3718. {
  3719. FRESULT res;
  3720. FATFS *fs;
  3721. DWORD clst, bcs;
  3722. LBA_t nsect;
  3723. FSIZE_t ifptr;
  3724. #if FF_USE_FASTSEEK
  3725. DWORD cl, pcl, ncl, tcl, tlen, ulen;
  3726. DWORD *tbl;
  3727. LBA_t dsc;
  3728. #endif
  3729. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  3730. if (res == FR_OK) res = (FRESULT)fp->err;
  3731. #if FF_FS_EXFAT && !FF_FS_READONLY
  3732. if (res == FR_OK && fs->fs_type == FS_EXFAT) {
  3733. res = fill_last_frag(&fp->obj, fp->clust, 0xFFFFFFFF); /* Fill last fragment on the FAT if needed */
  3734. }
  3735. #endif
  3736. if (res != FR_OK) LEAVE_FF(fs, res);
  3737. #if FF_USE_FASTSEEK
  3738. if (fp->cltbl) { /* Fast seek */
  3739. if (ofs == CREATE_LINKMAP) { /* Create CLMT */
  3740. tbl = fp->cltbl;
  3741. tlen = *tbl++; ulen = 2; /* Given table size and required table size */
  3742. cl = fp->obj.sclust; /* Origin of the chain */
  3743. if (cl != 0) {
  3744. do {
  3745. /* Get a fragment */
  3746. tcl = cl; ncl = 0; ulen += 2; /* Top, length and used items */
  3747. do {
  3748. pcl = cl; ncl++;
  3749. cl = get_fat(&fp->obj, cl);
  3750. if (cl <= 1) ABORT(fs, FR_INT_ERR);
  3751. if (cl == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3752. } while (cl == pcl + 1);
  3753. if (ulen <= tlen) { /* Store the length and top of the fragment */
  3754. *tbl++ = ncl; *tbl++ = tcl;
  3755. }
  3756. } while (cl < fs->n_fatent); /* Repeat until end of chain */
  3757. }
  3758. *fp->cltbl = ulen; /* Number of items used */
  3759. if (ulen <= tlen) {
  3760. *tbl = 0; /* Terminate table */
  3761. } else {
  3762. res = FR_NOT_ENOUGH_CORE; /* Given table size is smaller than required */
  3763. }
  3764. } else { /* Fast seek */
  3765. if (ofs > fp->obj.objsize) ofs = fp->obj.objsize; /* Clip offset at the file size */
  3766. fp->fptr = ofs; /* Set file pointer */
  3767. if (ofs > 0) {
  3768. fp->clust = clmt_clust(fp, ofs - 1);
  3769. dsc = clst2sect(fs, fp->clust);
  3770. if (dsc == 0) ABORT(fs, FR_INT_ERR);
  3771. dsc += (DWORD)((ofs - 1) / SS(fs)) & (fs->csize - 1);
  3772. if (fp->fptr % SS(fs) && dsc != fp->sect) { /* Refill sector cache if needed */
  3773. #if !FF_FS_TINY
  3774. #if !FF_FS_READONLY
  3775. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3776. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3777. fp->flag &= (BYTE)~FA_DIRTY;
  3778. }
  3779. #endif
  3780. if (disk_read(fs->pdrv, fp->buf, dsc, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Load current sector */
  3781. #endif
  3782. fp->sect = dsc;
  3783. }
  3784. }
  3785. }
  3786. } else
  3787. #endif
  3788. /* Normal Seek */
  3789. {
  3790. #if FF_FS_EXFAT
  3791. if (fs->fs_type != FS_EXFAT && ofs >= 0x100000000) ofs = 0xFFFFFFFF; /* Clip at 4 GiB - 1 if at FATxx */
  3792. #endif
  3793. if (ofs > fp->obj.objsize && (FF_FS_READONLY || !(fp->flag & FA_WRITE))) { /* In read-only mode, clip offset with the file size */
  3794. ofs = fp->obj.objsize;
  3795. }
  3796. ifptr = fp->fptr;
  3797. fp->fptr = nsect = 0;
  3798. if (ofs > 0) {
  3799. bcs = (DWORD)fs->csize * SS(fs); /* Cluster size (byte) */
  3800. if (ifptr > 0 &&
  3801. (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */
  3802. fp->fptr = (ifptr - 1) & ~(FSIZE_t)(bcs - 1); /* start from the current cluster */
  3803. ofs -= fp->fptr;
  3804. clst = fp->clust;
  3805. } else { /* When seek to back cluster, */
  3806. clst = fp->obj.sclust; /* start from the first cluster */
  3807. #if !FF_FS_READONLY
  3808. if (clst == 0) { /* If no cluster chain, create a new chain */
  3809. clst = create_chain(&fp->obj, 0);
  3810. if (clst == 1) ABORT(fs, FR_INT_ERR);
  3811. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3812. fp->obj.sclust = clst;
  3813. }
  3814. #endif
  3815. fp->clust = clst;
  3816. }
  3817. if (clst != 0) {
  3818. while (ofs > bcs) { /* Cluster following loop */
  3819. ofs -= bcs; fp->fptr += bcs;
  3820. #if !FF_FS_READONLY
  3821. if (fp->flag & FA_WRITE) { /* Check if in write mode or not */
  3822. if (FF_FS_EXFAT && fp->fptr > fp->obj.objsize) { /* No FAT chain object needs correct objsize to generate FAT value */
  3823. fp->obj.objsize = fp->fptr;
  3824. fp->flag |= FA_MODIFIED;
  3825. }
  3826. clst = create_chain(&fp->obj, clst); /* Follow chain with forceed stretch */
  3827. if (clst == 0) { /* Clip file size in case of disk full */
  3828. ofs = 0; break;
  3829. }
  3830. } else
  3831. #endif
  3832. {
  3833. clst = get_fat(&fp->obj, clst); /* Follow cluster chain if not in write mode */
  3834. }
  3835. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  3836. if (clst <= 1 || clst >= fs->n_fatent) ABORT(fs, FR_INT_ERR);
  3837. fp->clust = clst;
  3838. }
  3839. fp->fptr += ofs;
  3840. if (ofs % SS(fs)) {
  3841. nsect = clst2sect(fs, clst); /* Current sector */
  3842. if (nsect == 0) ABORT(fs, FR_INT_ERR);
  3843. nsect += (DWORD)(ofs / SS(fs));
  3844. }
  3845. }
  3846. }
  3847. if (!FF_FS_READONLY && fp->fptr > fp->obj.objsize) { /* Set file change flag if the file size is extended */
  3848. fp->obj.objsize = fp->fptr;
  3849. fp->flag |= FA_MODIFIED;
  3850. }
  3851. if (fp->fptr % SS(fs) && nsect != fp->sect) { /* Fill sector cache if needed */
  3852. #if !FF_FS_TINY
  3853. #if !FF_FS_READONLY
  3854. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  3855. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  3856. fp->flag &= (BYTE)~FA_DIRTY;
  3857. }
  3858. #endif
  3859. if (disk_read(fs->pdrv, fp->buf, nsect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */
  3860. #endif
  3861. fp->sect = nsect;
  3862. }
  3863. }
  3864. LEAVE_FF(fs, res);
  3865. }
  3866. #if FF_FS_MINIMIZE <= 1
  3867. /*-----------------------------------------------------------------------*/
  3868. /* Create a Directory Object */
  3869. /*-----------------------------------------------------------------------*/
  3870. FRESULT f_opendir (
  3871. DIR* dp, /* Pointer to directory object to create */
  3872. const FATFS_TCHAR* path /* Pointer to the directory path */
  3873. )
  3874. {
  3875. FRESULT res;
  3876. FATFS *fs;
  3877. DEF_NAMBUF
  3878. if (!dp) return FR_INVALID_OBJECT;
  3879. /* Get logical drive */
  3880. res = mount_volume(&path, &fs, 0);
  3881. if (res == FR_OK) {
  3882. dp->obj.fs = fs;
  3883. INIT_NAMBUF(fs);
  3884. res = follow_path(dp, path); /* Follow the path to the directory */
  3885. if (res == FR_OK) { /* Follow completed */
  3886. if (!(dp->fn[NSFLAG] & NS_NONAME)) { /* It is not the origin directory itself */
  3887. if (dp->obj.attr & AM_DIR) { /* This object is a sub-directory */
  3888. #if FF_FS_EXFAT
  3889. if (fs->fs_type == FS_EXFAT) {
  3890. dp->obj.c_scl = dp->obj.sclust; /* Get containing directory inforamation */
  3891. dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat;
  3892. dp->obj.c_ofs = dp->blk_ofs;
  3893. init_alloc_info(fs, &dp->obj); /* Get object allocation info */
  3894. } else
  3895. #endif
  3896. {
  3897. dp->obj.sclust = ld_clust(fs, dp->dir); /* Get object allocation info */
  3898. }
  3899. } else { /* This object is a file */
  3900. res = FR_NO_PATH;
  3901. }
  3902. }
  3903. if (res == FR_OK) {
  3904. dp->obj.id = fs->id;
  3905. res = dir_sdi(dp, 0); /* Rewind directory */
  3906. #if FF_FS_LOCK != 0
  3907. if (res == FR_OK) {
  3908. if (dp->obj.sclust != 0) {
  3909. dp->obj.lockid = inc_lock(dp, 0); /* Lock the sub directory */
  3910. if (!dp->obj.lockid) res = FR_TOO_MANY_OPEN_FILES;
  3911. } else {
  3912. dp->obj.lockid = 0; /* Root directory need not to be locked */
  3913. }
  3914. }
  3915. #endif
  3916. }
  3917. }
  3918. FREE_NAMBUF();
  3919. if (res == FR_NO_FILE) res = FR_NO_PATH;
  3920. }
  3921. if (res != FR_OK) dp->obj.fs = 0; /* Invalidate the directory object if function faild */
  3922. LEAVE_FF(fs, res);
  3923. }
  3924. /*-----------------------------------------------------------------------*/
  3925. /* Close Directory */
  3926. /*-----------------------------------------------------------------------*/
  3927. FRESULT f_closedir (
  3928. DIR *dp /* Pointer to the directory object to be closed */
  3929. )
  3930. {
  3931. FRESULT res;
  3932. FATFS *fs;
  3933. res = validate(&dp->obj, &fs); /* Check validity of the file object */
  3934. if (res == FR_OK) {
  3935. #if FF_FS_LOCK != 0
  3936. if (dp->obj.lockid) res = dec_lock(dp->obj.lockid); /* Decrement sub-directory open counter */
  3937. if (res == FR_OK) dp->obj.fs = 0; /* Invalidate directory object */
  3938. #else
  3939. dp->obj.fs = 0; /* Invalidate directory object */
  3940. #endif
  3941. #if FF_FS_REENTRANT
  3942. unlock_fs(fs, FR_OK); /* Unlock volume */
  3943. #endif
  3944. }
  3945. return res;
  3946. }
  3947. /*-----------------------------------------------------------------------*/
  3948. /* Read Directory Entries in Sequence */
  3949. /*-----------------------------------------------------------------------*/
  3950. FRESULT f_readdir (
  3951. DIR* dp, /* Pointer to the open directory object */
  3952. FILINFO* fno /* Pointer to file information to return */
  3953. )
  3954. {
  3955. FRESULT res;
  3956. FATFS *fs;
  3957. DEF_NAMBUF
  3958. res = validate(&dp->obj, &fs); /* Check validity of the directory object */
  3959. if (res == FR_OK) {
  3960. if (!fno) {
  3961. res = dir_sdi(dp, 0); /* Rewind the directory object */
  3962. } else {
  3963. INIT_NAMBUF(fs);
  3964. res = DIR_READ_FILE(dp); /* Read an item */
  3965. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */
  3966. if (res == FR_OK) { /* A valid entry is found */
  3967. get_fileinfo(dp, fno); /* Get the object information */
  3968. res = dir_next(dp, 0); /* Increment index for next */
  3969. if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory now */
  3970. }
  3971. FREE_NAMBUF();
  3972. }
  3973. }
  3974. LEAVE_FF(fs, res);
  3975. }
  3976. #if FF_USE_FIND
  3977. /*-----------------------------------------------------------------------*/
  3978. /* Find Next File */
  3979. /*-----------------------------------------------------------------------*/
  3980. FRESULT f_findnext (
  3981. DIR* dp, /* Pointer to the open directory object */
  3982. FILINFO* fno /* Pointer to the file information structure */
  3983. )
  3984. {
  3985. FRESULT res;
  3986. for (;;) {
  3987. res = f_readdir(dp, fno); /* Get a directory item */
  3988. if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */
  3989. if (pattern_match(dp->pat, fno->fname, 0, FIND_RECURS)) break; /* Test for the file name */
  3990. #if FF_USE_LFN && FF_USE_FIND == 2
  3991. if (pattern_match(dp->pat, fno->altname, 0, FIND_RECURS)) break; /* Test for alternative name if exist */
  3992. #endif
  3993. }
  3994. return res;
  3995. }
  3996. /*-----------------------------------------------------------------------*/
  3997. /* Find First File */
  3998. /*-----------------------------------------------------------------------*/
  3999. FRESULT f_findfirst (
  4000. DIR* dp, /* Pointer to the blank directory object */
  4001. FILINFO* fno, /* Pointer to the file information structure */
  4002. const FATFS_TCHAR* path, /* Pointer to the directory to open */
  4003. const FATFS_TCHAR* pattern /* Pointer to the matching pattern */
  4004. )
  4005. {
  4006. FRESULT res;
  4007. dp->pat = pattern; /* Save pointer to pattern string */
  4008. res = f_opendir(dp, path); /* Open the target directory */
  4009. if (res == FR_OK) {
  4010. res = f_findnext(dp, fno); /* Find the first item */
  4011. }
  4012. return res;
  4013. }
  4014. #endif /* FF_USE_FIND */
  4015. #if FF_FS_MINIMIZE == 0
  4016. /*-----------------------------------------------------------------------*/
  4017. /* Get File Status */
  4018. /*-----------------------------------------------------------------------*/
  4019. FRESULT f_stat (
  4020. const FATFS_TCHAR* path, /* Pointer to the file path */
  4021. FILINFO* fno /* Pointer to file information to return */
  4022. )
  4023. {
  4024. FRESULT res;
  4025. DIR dj;
  4026. DEF_NAMBUF
  4027. /* Get logical drive */
  4028. res = mount_volume(&path, &dj.obj.fs, 0);
  4029. if (res == FR_OK) {
  4030. INIT_NAMBUF(dj.obj.fs);
  4031. res = follow_path(&dj, path); /* Follow the file path */
  4032. if (res == FR_OK) { /* Follow completed */
  4033. if (dj.fn[NSFLAG] & NS_NONAME) { /* It is origin directory */
  4034. res = FR_INVALID_NAME;
  4035. } else { /* Found an object */
  4036. if (fno) get_fileinfo(&dj, fno);
  4037. }
  4038. }
  4039. FREE_NAMBUF();
  4040. }
  4041. LEAVE_FF(dj.obj.fs, res);
  4042. }
  4043. #if !FF_FS_READONLY
  4044. /*-----------------------------------------------------------------------*/
  4045. /* Get Number of Free Clusters */
  4046. /*-----------------------------------------------------------------------*/
  4047. FRESULT f_getfree (
  4048. const FATFS_TCHAR* path, /* Logical drive number */
  4049. DWORD* nclst, /* Pointer to a variable to return number of free clusters */
  4050. FATFS** fatfs /* Pointer to return pointer to corresponding filesystem object */
  4051. )
  4052. {
  4053. FRESULT res;
  4054. FATFS *fs;
  4055. DWORD nfree, clst, stat;
  4056. LBA_t sect;
  4057. UINT i;
  4058. FFOBJID obj;
  4059. /* Get logical drive */
  4060. res = mount_volume(&path, &fs, 0);
  4061. if (res == FR_OK) {
  4062. *fatfs = fs; /* Return ptr to the fs object */
  4063. /* If free_clst is valid, return it without full FAT scan */
  4064. if (fs->free_clst <= fs->n_fatent - 2) {
  4065. *nclst = fs->free_clst;
  4066. } else {
  4067. /* Scan FAT to obtain number of free clusters */
  4068. nfree = 0;
  4069. if (fs->fs_type == FS_FAT12) { /* FAT12: Scan bit field FAT entries */
  4070. clst = 2; obj.fs = fs;
  4071. do {
  4072. stat = get_fat(&obj, clst);
  4073. if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  4074. if (stat == 1) { res = FR_INT_ERR; break; }
  4075. if (stat == 0) nfree++;
  4076. } while (++clst < fs->n_fatent);
  4077. } else {
  4078. #if FF_FS_EXFAT
  4079. if (fs->fs_type == FS_EXFAT) { /* exFAT: Scan allocation bitmap */
  4080. BYTE bm;
  4081. UINT b;
  4082. clst = fs->n_fatent - 2; /* Number of clusters */
  4083. sect = fs->bitbase; /* Bitmap sector */
  4084. i = 0; /* Offset in the sector */
  4085. do { /* Counts numbuer of bits with zero in the bitmap */
  4086. if (i == 0) {
  4087. res = move_window(fs, sect++);
  4088. if (res != FR_OK) break;
  4089. }
  4090. for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {
  4091. if (!(bm & 1)) nfree++;
  4092. bm >>= 1;
  4093. }
  4094. i = (i + 1) % SS(fs);
  4095. } while (clst);
  4096. } else
  4097. #endif
  4098. { /* FAT16/32: Scan WORD/DWORD FAT entries */
  4099. clst = fs->n_fatent; /* Number of entries */
  4100. sect = fs->fatbase; /* Top of the FAT */
  4101. i = 0; /* Offset in the sector */
  4102. do { /* Counts numbuer of entries with zero in the FAT */
  4103. if (i == 0) {
  4104. res = move_window(fs, sect++);
  4105. if (res != FR_OK) break;
  4106. }
  4107. if (fs->fs_type == FS_FAT16) {
  4108. if (ld_word(fs->win + i) == 0) nfree++;
  4109. i += 2;
  4110. } else {
  4111. if ((ld_dword(fs->win + i) & 0x0FFFFFFF) == 0) nfree++;
  4112. i += 4;
  4113. }
  4114. i %= SS(fs);
  4115. } while (--clst);
  4116. }
  4117. }
  4118. if (res == FR_OK) { /* Update parameters if succeeded */
  4119. *nclst = nfree; /* Return the free clusters */
  4120. fs->free_clst = nfree; /* Now free_clst is valid */
  4121. fs->fsi_flag |= 1; /* FAT32: FSInfo is to be updated */
  4122. }
  4123. }
  4124. }
  4125. LEAVE_FF(fs, res);
  4126. }
  4127. /*-----------------------------------------------------------------------*/
  4128. /* Truncate File */
  4129. /*-----------------------------------------------------------------------*/
  4130. FRESULT f_truncate (
  4131. FIL* fp /* Pointer to the file object */
  4132. )
  4133. {
  4134. FRESULT res;
  4135. FATFS *fs;
  4136. DWORD ncl;
  4137. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4138. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4139. if (!(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  4140. if (fp->fptr < fp->obj.objsize) { /* Process when fptr is not on the eof */
  4141. if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */
  4142. res = remove_chain(&fp->obj, fp->obj.sclust, 0);
  4143. fp->obj.sclust = 0;
  4144. } else { /* When truncate a part of the file, remove remaining clusters */
  4145. ncl = get_fat(&fp->obj, fp->clust);
  4146. res = FR_OK;
  4147. if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4148. if (ncl == 1) res = FR_INT_ERR;
  4149. if (res == FR_OK && ncl < fs->n_fatent) {
  4150. res = remove_chain(&fp->obj, ncl, fp->clust);
  4151. }
  4152. }
  4153. fp->obj.objsize = fp->fptr; /* Set file size to current read/write point */
  4154. fp->flag |= FA_MODIFIED;
  4155. #if !FF_FS_TINY
  4156. if (res == FR_OK && (fp->flag & FA_DIRTY)) {
  4157. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) {
  4158. res = FR_DISK_ERR;
  4159. } else {
  4160. fp->flag &= (BYTE)~FA_DIRTY;
  4161. }
  4162. }
  4163. #endif
  4164. if (res != FR_OK) ABORT(fs, res);
  4165. }
  4166. LEAVE_FF(fs, res);
  4167. }
  4168. /*-----------------------------------------------------------------------*/
  4169. /* Delete a File/Directory */
  4170. /*-----------------------------------------------------------------------*/
  4171. FRESULT f_unlink (
  4172. const FATFS_TCHAR* path /* Pointer to the file or directory path */
  4173. )
  4174. {
  4175. FRESULT res;
  4176. DIR dj, sdj;
  4177. DWORD dclst = 0;
  4178. FATFS *fs;
  4179. #if FF_FS_EXFAT
  4180. FFOBJID obj;
  4181. #endif
  4182. DEF_NAMBUF
  4183. /* Get logical drive */
  4184. res = mount_volume(&path, &fs, FA_WRITE);
  4185. if (res == FR_OK) {
  4186. dj.obj.fs = fs;
  4187. INIT_NAMBUF(fs);
  4188. res = follow_path(&dj, path); /* Follow the file path */
  4189. if (FF_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {
  4190. res = FR_INVALID_NAME; /* Cannot remove dot entry */
  4191. }
  4192. #if FF_FS_LOCK != 0
  4193. if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */
  4194. #endif
  4195. if (res == FR_OK) { /* The object is accessible */
  4196. if (dj.fn[NSFLAG] & NS_NONAME) {
  4197. res = FR_INVALID_NAME; /* Cannot remove the origin directory */
  4198. } else {
  4199. if (dj.obj.attr & AM_RDO) {
  4200. res = FR_DENIED; /* Cannot remove R/O object */
  4201. }
  4202. }
  4203. if (res == FR_OK) {
  4204. #if FF_FS_EXFAT
  4205. obj.fs = fs;
  4206. if (fs->fs_type == FS_EXFAT) {
  4207. init_alloc_info(fs, &obj);
  4208. dclst = obj.sclust;
  4209. } else
  4210. #endif
  4211. {
  4212. dclst = ld_clust(fs, dj.dir);
  4213. }
  4214. if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory? */
  4215. #if FF_FS_RPATH != 0
  4216. if (dclst == fs->cdir) { /* Is it the current directory? */
  4217. res = FR_DENIED;
  4218. } else
  4219. #endif
  4220. {
  4221. sdj.obj.fs = fs; /* Open the sub-directory */
  4222. sdj.obj.sclust = dclst;
  4223. #if FF_FS_EXFAT
  4224. if (fs->fs_type == FS_EXFAT) {
  4225. sdj.obj.objsize = obj.objsize;
  4226. sdj.obj.stat = obj.stat;
  4227. }
  4228. #endif
  4229. res = dir_sdi(&sdj, 0);
  4230. if (res == FR_OK) {
  4231. res = DIR_READ_FILE(&sdj); /* Test if the directory is empty */
  4232. if (res == FR_OK) res = FR_DENIED; /* Not empty? */
  4233. if (res == FR_NO_FILE) res = FR_OK; /* Empty? */
  4234. }
  4235. }
  4236. }
  4237. }
  4238. if (res == FR_OK) {
  4239. res = dir_remove(&dj); /* Remove the directory entry */
  4240. if (res == FR_OK && dclst != 0) { /* Remove the cluster chain if exist */
  4241. #if FF_FS_EXFAT
  4242. res = remove_chain(&obj, dclst, 0);
  4243. #else
  4244. res = remove_chain(&dj.obj, dclst, 0);
  4245. #endif
  4246. }
  4247. if (res == FR_OK) res = sync_fs(fs);
  4248. }
  4249. }
  4250. FREE_NAMBUF();
  4251. }
  4252. LEAVE_FF(fs, res);
  4253. }
  4254. /*-----------------------------------------------------------------------*/
  4255. /* Create a Directory */
  4256. /*-----------------------------------------------------------------------*/
  4257. FRESULT f_mkdir (
  4258. const FATFS_TCHAR* path /* Pointer to the directory path */
  4259. )
  4260. {
  4261. FRESULT res;
  4262. DIR dj;
  4263. FFOBJID sobj;
  4264. FATFS *fs;
  4265. DWORD dcl, pcl, tm;
  4266. DEF_NAMBUF
  4267. res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4268. if (res == FR_OK) {
  4269. dj.obj.fs = fs;
  4270. INIT_NAMBUF(fs);
  4271. res = follow_path(&dj, path); /* Follow the file path */
  4272. if (res == FR_OK) res = FR_EXIST; /* Name collision? */
  4273. if (FF_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) { /* Invalid name? */
  4274. res = FR_INVALID_NAME;
  4275. }
  4276. if (res == FR_NO_FILE) { /* It is clear to create a new directory */
  4277. sobj.fs = fs; /* New object id to create a new chain */
  4278. dcl = create_chain(&sobj, 0); /* Allocate a cluster for the new directory */
  4279. res = FR_OK;
  4280. if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster? */
  4281. if (dcl == 1) res = FR_INT_ERR; /* Any insanity? */
  4282. if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR; /* Disk error? */
  4283. tm = GET_FATTIME();
  4284. if (res == FR_OK) {
  4285. res = dir_clear(fs, dcl); /* Clean up the new table */
  4286. if (res == FR_OK) {
  4287. if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* Create dot entries (FAT only) */
  4288. memset(fs->win + DIR_Name, ' ', 11); /* Create "." entry */
  4289. fs->win[DIR_Name] = '.';
  4290. fs->win[DIR_Attr] = AM_DIR;
  4291. st_dword(fs->win + DIR_ModTime, tm);
  4292. st_clust(fs, fs->win, dcl);
  4293. memcpy(fs->win + SZDIRE, fs->win, SZDIRE); /* Create ".." entry */
  4294. fs->win[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;
  4295. st_clust(fs, fs->win + SZDIRE, pcl);
  4296. fs->wflag = 1;
  4297. }
  4298. res = dir_register(&dj); /* Register the object to the parent directoy */
  4299. }
  4300. }
  4301. if (res == FR_OK) {
  4302. #if FF_FS_EXFAT
  4303. if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */
  4304. st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */
  4305. st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */
  4306. st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)fs->csize * SS(fs)); /* Directory size needs to be valid */
  4307. st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)fs->csize * SS(fs));
  4308. fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag */
  4309. fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */
  4310. res = store_xdir(&dj);
  4311. } else
  4312. #endif
  4313. {
  4314. st_dword(dj.dir + DIR_ModTime, tm); /* Created time */
  4315. st_clust(fs, dj.dir, dcl); /* Table start cluster */
  4316. dj.dir[DIR_Attr] = AM_DIR; /* Attribute */
  4317. fs->wflag = 1;
  4318. }
  4319. if (res == FR_OK) {
  4320. res = sync_fs(fs);
  4321. }
  4322. } else {
  4323. remove_chain(&sobj, dcl, 0); /* Could not register, remove the allocated cluster */
  4324. }
  4325. }
  4326. FREE_NAMBUF();
  4327. }
  4328. LEAVE_FF(fs, res);
  4329. }
  4330. /*-----------------------------------------------------------------------*/
  4331. /* Rename a File/Directory */
  4332. /*-----------------------------------------------------------------------*/
  4333. FRESULT f_rename (
  4334. const FATFS_TCHAR* path_old, /* Pointer to the object name to be renamed */
  4335. const FATFS_TCHAR* path_new /* Pointer to the new name */
  4336. )
  4337. {
  4338. FRESULT res;
  4339. DIR djo, djn;
  4340. FATFS *fs;
  4341. BYTE buf[FF_FS_EXFAT ? SZDIRE * 2 : SZDIRE], *dir;
  4342. LBA_t sect;
  4343. DEF_NAMBUF
  4344. get_ldnumber(&path_new); /* Snip the drive number of new name off */
  4345. res = mount_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */
  4346. if (res == FR_OK) {
  4347. djo.obj.fs = fs;
  4348. INIT_NAMBUF(fs);
  4349. res = follow_path(&djo, path_old); /* Check old object */
  4350. if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */
  4351. #if FF_FS_LOCK != 0
  4352. if (res == FR_OK) {
  4353. res = chk_lock(&djo, 2);
  4354. }
  4355. #endif
  4356. if (res == FR_OK) { /* Object to be renamed is found */
  4357. #if FF_FS_EXFAT
  4358. if (fs->fs_type == FS_EXFAT) { /* At exFAT volume */
  4359. BYTE nf, nn;
  4360. WORD nh;
  4361. memcpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */
  4362. memcpy(&djn, &djo, sizeof djo);
  4363. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4364. if (res == FR_OK) { /* Is new name already in use by any other object? */
  4365. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4366. }
  4367. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4368. res = dir_register(&djn); /* Register the new entry */
  4369. if (res == FR_OK) {
  4370. nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];
  4371. nh = ld_word(fs->dirbuf + XDIR_NameHash);
  4372. memcpy(fs->dirbuf, buf, SZDIRE * 2); /* Restore 85+C0 entry */
  4373. fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;
  4374. st_word(fs->dirbuf + XDIR_NameHash, nh);
  4375. if (!(fs->dirbuf[XDIR_Attr] & AM_DIR)) fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */
  4376. /* Start of critical section where an interruption can cause a cross-link */
  4377. res = store_xdir(&djn);
  4378. }
  4379. }
  4380. } else
  4381. #endif
  4382. { /* At FAT/FAT32 volume */
  4383. memcpy(buf, djo.dir, SZDIRE); /* Save directory entry of the object */
  4384. memcpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */
  4385. res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */
  4386. if (res == FR_OK) { /* Is new name already in use by any other object? */
  4387. res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;
  4388. }
  4389. if (res == FR_NO_FILE) { /* It is a valid path and no name collision */
  4390. res = dir_register(&djn); /* Register the new entry */
  4391. if (res == FR_OK) {
  4392. dir = djn.dir; /* Copy directory entry of the object except name */
  4393. memcpy(dir + 13, buf + 13, SZDIRE - 13);
  4394. dir[DIR_Attr] = buf[DIR_Attr];
  4395. if (!(dir[DIR_Attr] & AM_DIR)) dir[DIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */
  4396. fs->wflag = 1;
  4397. if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */
  4398. sect = clst2sect(fs, ld_clust(fs, dir));
  4399. if (sect == 0) {
  4400. res = FR_INT_ERR;
  4401. } else {
  4402. /* Start of critical section where an interruption can cause a cross-link */
  4403. res = move_window(fs, sect);
  4404. dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */
  4405. if (res == FR_OK && dir[1] == '.') {
  4406. st_clust(fs, dir, djn.obj.sclust);
  4407. fs->wflag = 1;
  4408. }
  4409. }
  4410. }
  4411. }
  4412. }
  4413. }
  4414. if (res == FR_OK) {
  4415. res = dir_remove(&djo); /* Remove old entry */
  4416. if (res == FR_OK) {
  4417. res = sync_fs(fs);
  4418. }
  4419. }
  4420. /* End of the critical section */
  4421. }
  4422. FREE_NAMBUF();
  4423. }
  4424. LEAVE_FF(fs, res);
  4425. }
  4426. #endif /* !FF_FS_READONLY */
  4427. #endif /* FF_FS_MINIMIZE == 0 */
  4428. #endif /* FF_FS_MINIMIZE <= 1 */
  4429. #endif /* FF_FS_MINIMIZE <= 2 */
  4430. #if FF_USE_CHMOD && !FF_FS_READONLY
  4431. /*-----------------------------------------------------------------------*/
  4432. /* Change Attribute */
  4433. /*-----------------------------------------------------------------------*/
  4434. FRESULT f_chmod (
  4435. const FATFS_TCHAR* path, /* Pointer to the file path */
  4436. BYTE attr, /* Attribute bits */
  4437. BYTE mask /* Attribute mask to change */
  4438. )
  4439. {
  4440. FRESULT res;
  4441. DIR dj;
  4442. FATFS *fs;
  4443. DEF_NAMBUF
  4444. res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4445. if (res == FR_OK) {
  4446. dj.obj.fs = fs;
  4447. INIT_NAMBUF(fs);
  4448. res = follow_path(&dj, path); /* Follow the file path */
  4449. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4450. if (res == FR_OK) {
  4451. mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */
  4452. #if FF_FS_EXFAT
  4453. if (fs->fs_type == FS_EXFAT) {
  4454. fs->dirbuf[XDIR_Attr] = (attr & mask) | (fs->dirbuf[XDIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4455. res = store_xdir(&dj);
  4456. } else
  4457. #endif
  4458. {
  4459. dj.dir[DIR_Attr] = (attr & mask) | (dj.dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */
  4460. fs->wflag = 1;
  4461. }
  4462. if (res == FR_OK) {
  4463. res = sync_fs(fs);
  4464. }
  4465. }
  4466. FREE_NAMBUF();
  4467. }
  4468. LEAVE_FF(fs, res);
  4469. }
  4470. /*-----------------------------------------------------------------------*/
  4471. /* Change Timestamp */
  4472. /*-----------------------------------------------------------------------*/
  4473. FRESULT f_utime (
  4474. const FATFS_TCHAR* path, /* Pointer to the file/directory name */
  4475. const FILINFO* fno /* Pointer to the timestamp to be set */
  4476. )
  4477. {
  4478. FRESULT res;
  4479. DIR dj;
  4480. FATFS *fs;
  4481. DEF_NAMBUF
  4482. res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */
  4483. if (res == FR_OK) {
  4484. dj.obj.fs = fs;
  4485. INIT_NAMBUF(fs);
  4486. res = follow_path(&dj, path); /* Follow the file path */
  4487. if (res == FR_OK && (dj.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check object validity */
  4488. if (res == FR_OK) {
  4489. #if FF_FS_EXFAT
  4490. if (fs->fs_type == FS_EXFAT) {
  4491. st_dword(fs->dirbuf + XDIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4492. res = store_xdir(&dj);
  4493. } else
  4494. #endif
  4495. {
  4496. st_dword(dj.dir + DIR_ModTime, (DWORD)fno->fdate << 16 | fno->ftime);
  4497. fs->wflag = 1;
  4498. }
  4499. if (res == FR_OK) {
  4500. res = sync_fs(fs);
  4501. }
  4502. }
  4503. FREE_NAMBUF();
  4504. }
  4505. LEAVE_FF(fs, res);
  4506. }
  4507. #endif /* FF_USE_CHMOD && !FF_FS_READONLY */
  4508. #if FF_USE_LABEL
  4509. /*-----------------------------------------------------------------------*/
  4510. /* Get Volume Label */
  4511. /*-----------------------------------------------------------------------*/
  4512. FRESULT f_getlabel (
  4513. const FATFS_TCHAR* path, /* Logical drive number */
  4514. FATFS_TCHAR* label, /* Buffer to store the volume label */
  4515. DWORD* vsn /* Variable to store the volume serial number */
  4516. )
  4517. {
  4518. FRESULT res;
  4519. DIR dj;
  4520. FATFS *fs;
  4521. UINT si, di;
  4522. WCHAR wc;
  4523. /* Get logical drive */
  4524. res = mount_volume(&path, &fs, 0);
  4525. /* Get volume label */
  4526. if (res == FR_OK && label) {
  4527. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4528. res = dir_sdi(&dj, 0);
  4529. if (res == FR_OK) {
  4530. res = DIR_READ_LABEL(&dj); /* Find a volume label entry */
  4531. if (res == FR_OK) {
  4532. #if FF_FS_EXFAT
  4533. if (fs->fs_type == FS_EXFAT) {
  4534. WCHAR hs;
  4535. UINT nw;
  4536. for (si = di = hs = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */
  4537. wc = ld_word(dj.dir + XDIR_Label + si * 2);
  4538. if (hs == 0 && IsSurrogate(wc)) { /* Is the code a surrogate? */
  4539. hs = wc; continue;
  4540. }
  4541. nw = put_utf((DWORD)hs << 16 | wc, &label[di], 4); /* Store it in API encoding */
  4542. if (nw == 0) { di = 0; break; } /* Encode error? */
  4543. di += nw;
  4544. hs = 0;
  4545. }
  4546. if (hs != 0) di = 0; /* Broken surrogate pair? */
  4547. label[di] = 0;
  4548. } else
  4549. #endif
  4550. {
  4551. si = di = 0; /* Extract volume label from AM_VOL entry */
  4552. while (si < 11) {
  4553. wc = dj.dir[si++];
  4554. #if FF_USE_LFN && FF_LFN_UNICODE >= 1 /* Unicode output */
  4555. if (dbc_1st((BYTE)wc) && si < 11) wc = wc << 8 | dj.dir[si++]; /* Is it a DBC? */
  4556. wc = ff_oem2uni(wc, CODEPAGE); /* Convert it into Unicode */
  4557. if (wc == 0) { di = 0; break; } /* Invalid char in current code page? */
  4558. di += put_utf(wc, &label[di], 4); /* Store it in Unicode */
  4559. #else /* ANSI/OEM output */
  4560. label[di++] = (FATFS_TCHAR)wc;
  4561. #endif
  4562. }
  4563. do { /* Truncate trailing spaces */
  4564. label[di] = 0;
  4565. if (di == 0) break;
  4566. } while (label[--di] == ' ');
  4567. }
  4568. }
  4569. }
  4570. if (res == FR_NO_FILE) { /* No label entry and return nul string */
  4571. label[0] = 0;
  4572. res = FR_OK;
  4573. }
  4574. }
  4575. /* Get volume serial number */
  4576. if (res == FR_OK && vsn) {
  4577. res = move_window(fs, fs->volbase);
  4578. if (res == FR_OK) {
  4579. switch (fs->fs_type) {
  4580. case FS_EXFAT:
  4581. di = BPB_VolIDEx;
  4582. break;
  4583. case FS_FAT32:
  4584. di = BS_VolID32;
  4585. break;
  4586. default:
  4587. di = BS_VolID;
  4588. }
  4589. *vsn = ld_dword(fs->win + di);
  4590. }
  4591. }
  4592. LEAVE_FF(fs, res);
  4593. }
  4594. #if !FF_FS_READONLY
  4595. /*-----------------------------------------------------------------------*/
  4596. /* Set Volume Label */
  4597. /*-----------------------------------------------------------------------*/
  4598. FRESULT f_setlabel (
  4599. const FATFS_TCHAR* label /* Volume label to set with heading logical drive number */
  4600. )
  4601. {
  4602. FRESULT res;
  4603. DIR dj;
  4604. FATFS *fs;
  4605. BYTE dirvn[22];
  4606. UINT di;
  4607. WCHAR wc;
  4608. static const char badchr[18] = "+.,;=[]" "/*:<>|\\\"\?\x7F"; /* [0..16] for FAT, [7..16] for exFAT */
  4609. #if FF_USE_LFN
  4610. DWORD dc;
  4611. #endif
  4612. /* Get logical drive */
  4613. res = mount_volume(&label, &fs, FA_WRITE);
  4614. if (res != FR_OK) LEAVE_FF(fs, res);
  4615. #if FF_FS_EXFAT
  4616. if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */
  4617. memset(dirvn, 0, 22);
  4618. di = 0;
  4619. while ((UINT)*label >= ' ') { /* Create volume label */
  4620. dc = tchar2uni(&label); /* Get a Unicode character */
  4621. if (dc >= 0x10000) {
  4622. if (dc == 0xFFFFFFFF || di >= 10) { /* Wrong surrogate or buffer overflow */
  4623. dc = 0;
  4624. } else {
  4625. st_word(dirvn + di * 2, (WCHAR)(dc >> 16)); di++;
  4626. }
  4627. }
  4628. if (dc == 0 || strchr(&badchr[7], (int)dc) || di >= 11) { /* Check validity of the volume label */
  4629. LEAVE_FF(fs, FR_INVALID_NAME);
  4630. }
  4631. st_word(dirvn + di * 2, (WCHAR)dc); di++;
  4632. }
  4633. } else
  4634. #endif
  4635. { /* On the FAT/FAT32 volume */
  4636. memset(dirvn, ' ', 11);
  4637. di = 0;
  4638. while ((UINT)*label >= ' ') { /* Create volume label */
  4639. #if FF_USE_LFN
  4640. dc = tchar2uni(&label);
  4641. wc = (dc < 0x10000) ? ff_uni2oem(ff_wtoupper(dc), CODEPAGE) : 0;
  4642. #else /* ANSI/OEM input */
  4643. wc = (BYTE)*label++;
  4644. if (dbc_1st((BYTE)wc)) wc = dbc_2nd((BYTE)*label) ? wc << 8 | (BYTE)*label++ : 0;
  4645. if (IsLower(wc)) wc -= 0x20; /* To upper ASCII characters */
  4646. #if FF_CODE_PAGE == 0
  4647. if (ExCvt && wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */
  4648. #elif FF_CODE_PAGE < 900
  4649. if (wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */
  4650. #endif
  4651. #endif
  4652. if (wc == 0 || strchr(&badchr[0], (int)wc) || di >= (UINT)((wc >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */
  4653. LEAVE_FF(fs, FR_INVALID_NAME);
  4654. }
  4655. if (wc >= 0x100) dirvn[di++] = (BYTE)(wc >> 8);
  4656. dirvn[di++] = (BYTE)wc;
  4657. }
  4658. if (dirvn[0] == DDEM) LEAVE_FF(fs, FR_INVALID_NAME); /* Reject illegal name (heading DDEM) */
  4659. while (di && dirvn[di - 1] == ' ') di--; /* Snip trailing spaces */
  4660. }
  4661. /* Set volume label */
  4662. dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */
  4663. res = dir_sdi(&dj, 0);
  4664. if (res == FR_OK) {
  4665. res = DIR_READ_LABEL(&dj); /* Get volume label entry */
  4666. if (res == FR_OK) {
  4667. if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4668. dj.dir[XDIR_NumLabel] = (BYTE)di; /* Change the volume label */
  4669. memcpy(dj.dir + XDIR_Label, dirvn, 22);
  4670. } else {
  4671. if (di != 0) {
  4672. memcpy(dj.dir, dirvn, 11); /* Change the volume label */
  4673. } else {
  4674. dj.dir[DIR_Name] = DDEM; /* Remove the volume label */
  4675. }
  4676. }
  4677. fs->wflag = 1;
  4678. res = sync_fs(fs);
  4679. } else { /* No volume label entry or an error */
  4680. if (res == FR_NO_FILE) {
  4681. res = FR_OK;
  4682. if (di != 0) { /* Create a volume label entry */
  4683. res = dir_alloc(&dj, 1); /* Allocate an entry */
  4684. if (res == FR_OK) {
  4685. memset(dj.dir, 0, SZDIRE); /* Clean the entry */
  4686. if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {
  4687. dj.dir[XDIR_Type] = ET_VLABEL; /* Create volume label entry */
  4688. dj.dir[XDIR_NumLabel] = (BYTE)di;
  4689. memcpy(dj.dir + XDIR_Label, dirvn, 22);
  4690. } else {
  4691. dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */
  4692. memcpy(dj.dir, dirvn, 11);
  4693. }
  4694. fs->wflag = 1;
  4695. res = sync_fs(fs);
  4696. }
  4697. }
  4698. }
  4699. }
  4700. }
  4701. LEAVE_FF(fs, res);
  4702. }
  4703. #endif /* !FF_FS_READONLY */
  4704. #endif /* FF_USE_LABEL */
  4705. #if FF_USE_EXPAND && !FF_FS_READONLY
  4706. /*-----------------------------------------------------------------------*/
  4707. /* Allocate a Contiguous Blocks to the File */
  4708. /*-----------------------------------------------------------------------*/
  4709. FRESULT f_expand (
  4710. FIL* fp, /* Pointer to the file object */
  4711. FSIZE_t fsz, /* File size to be expanded to */
  4712. BYTE opt /* Operation mode 0:Find and prepare or 1:Find and allocate */
  4713. )
  4714. {
  4715. FRESULT res;
  4716. FATFS *fs;
  4717. DWORD n, clst, stcl, scl, ncl, tcl, lclst;
  4718. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4719. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4720. if (fsz == 0 || fp->obj.objsize != 0 || !(fp->flag & FA_WRITE)) LEAVE_FF(fs, FR_DENIED);
  4721. #if FF_FS_EXFAT
  4722. if (fs->fs_type != FS_EXFAT && fsz >= 0x100000000) LEAVE_FF(fs, FR_DENIED); /* Check if in size limit */
  4723. #endif
  4724. n = (DWORD)fs->csize * SS(fs); /* Cluster size */
  4725. tcl = (DWORD)(fsz / n) + ((fsz & (n - 1)) ? 1 : 0); /* Number of clusters required */
  4726. stcl = fs->last_clst; lclst = 0;
  4727. if (stcl < 2 || stcl >= fs->n_fatent) stcl = 2;
  4728. #if FF_FS_EXFAT
  4729. if (fs->fs_type == FS_EXFAT) {
  4730. scl = find_bitmap(fs, stcl, tcl); /* Find a contiguous cluster block */
  4731. if (scl == 0) res = FR_DENIED; /* No contiguous cluster block was found */
  4732. if (scl == 0xFFFFFFFF) res = FR_DISK_ERR;
  4733. if (res == FR_OK) { /* A contiguous free area is found */
  4734. if (opt) { /* Allocate it now */
  4735. res = change_bitmap(fs, scl, tcl, 1); /* Mark the cluster block 'in use' */
  4736. lclst = scl + tcl - 1;
  4737. } else { /* Set it as suggested point for next allocation */
  4738. lclst = scl - 1;
  4739. }
  4740. }
  4741. } else
  4742. #endif
  4743. {
  4744. scl = clst = stcl; ncl = 0;
  4745. for (;;) { /* Find a contiguous cluster block */
  4746. n = get_fat(&fp->obj, clst);
  4747. if (++clst >= fs->n_fatent) clst = 2;
  4748. if (n == 1) { res = FR_INT_ERR; break; }
  4749. if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
  4750. if (n == 0) { /* Is it a free cluster? */
  4751. if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */
  4752. } else {
  4753. scl = clst; ncl = 0; /* Not a free cluster */
  4754. }
  4755. if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */
  4756. }
  4757. if (res == FR_OK) { /* A contiguous free area is found */
  4758. if (opt) { /* Allocate it now */
  4759. for (clst = scl, n = tcl; n; clst++, n--) { /* Create a cluster chain on the FAT */
  4760. res = put_fat(fs, clst, (n == 1) ? 0xFFFFFFFF : clst + 1);
  4761. if (res != FR_OK) break;
  4762. lclst = clst;
  4763. }
  4764. } else { /* Set it as suggested point for next allocation */
  4765. lclst = scl - 1;
  4766. }
  4767. }
  4768. }
  4769. if (res == FR_OK) {
  4770. fs->last_clst = lclst; /* Set suggested start cluster to start next */
  4771. if (opt) { /* Is it allocated now? */
  4772. fp->obj.sclust = scl; /* Update object allocation information */
  4773. fp->obj.objsize = fsz;
  4774. if (FF_FS_EXFAT) fp->obj.stat = 2; /* Set status 'contiguous chain' */
  4775. fp->flag |= FA_MODIFIED;
  4776. if (fs->free_clst <= fs->n_fatent - 2) { /* Update FSINFO */
  4777. fs->free_clst -= tcl;
  4778. fs->fsi_flag |= 1;
  4779. }
  4780. }
  4781. }
  4782. LEAVE_FF(fs, res);
  4783. }
  4784. #endif /* FF_USE_EXPAND && !FF_FS_READONLY */
  4785. #if FF_USE_FORWARD
  4786. /*-----------------------------------------------------------------------*/
  4787. /* Forward Data to the Stream Directly */
  4788. /*-----------------------------------------------------------------------*/
  4789. FRESULT f_forward (
  4790. FIL* fp, /* Pointer to the file object */
  4791. UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */
  4792. UINT btf, /* Number of bytes to forward */
  4793. UINT* bf /* Pointer to number of bytes forwarded */
  4794. )
  4795. {
  4796. FRESULT res;
  4797. FATFS *fs;
  4798. DWORD clst;
  4799. LBA_t sect;
  4800. FSIZE_t remain;
  4801. UINT rcnt, csect;
  4802. BYTE *dbuf;
  4803. *bf = 0; /* Clear transfer byte counter */
  4804. res = validate(&fp->obj, &fs); /* Check validity of the file object */
  4805. if (res != FR_OK || (res = (FRESULT)fp->err) != FR_OK) LEAVE_FF(fs, res);
  4806. if (!(fp->flag & FA_READ)) LEAVE_FF(fs, FR_DENIED); /* Check access mode */
  4807. remain = fp->obj.objsize - fp->fptr;
  4808. if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */
  4809. for ( ; btf > 0 && (*func)(0, 0); fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) { /* Repeat until all data transferred or stream goes busy */
  4810. csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */
  4811. if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */
  4812. if (csect == 0) { /* On the cluster boundary? */
  4813. clst = (fp->fptr == 0) ? /* On the top of the file? */
  4814. fp->obj.sclust : get_fat(&fp->obj, fp->clust);
  4815. if (clst <= 1) ABORT(fs, FR_INT_ERR);
  4816. if (clst == 0xFFFFFFFF) ABORT(fs, FR_DISK_ERR);
  4817. fp->clust = clst; /* Update current cluster */
  4818. }
  4819. }
  4820. sect = clst2sect(fs, fp->clust); /* Get current data sector */
  4821. if (sect == 0) ABORT(fs, FR_INT_ERR);
  4822. sect += csect;
  4823. #if FF_FS_TINY
  4824. if (move_window(fs, sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window to the file data */
  4825. dbuf = fs->win;
  4826. #else
  4827. if (fp->sect != sect) { /* Fill sector cache with file data */
  4828. #if !FF_FS_READONLY
  4829. if (fp->flag & FA_DIRTY) { /* Write-back dirty sector cache */
  4830. if (disk_write(fs->pdrv, fp->buf, fp->sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4831. fp->flag &= (BYTE)~FA_DIRTY;
  4832. }
  4833. #endif
  4834. if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR);
  4835. }
  4836. dbuf = fp->buf;
  4837. #endif
  4838. fp->sect = sect;
  4839. rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */
  4840. if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */
  4841. rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */
  4842. if (rcnt == 0) ABORT(fs, FR_INT_ERR);
  4843. }
  4844. LEAVE_FF(fs, FR_OK);
  4845. }
  4846. #endif /* FF_USE_FORWARD */
  4847. #if !FF_FS_READONLY && FF_USE_MKFS
  4848. /*-----------------------------------------------------------------------*/
  4849. /* Create FAT/exFAT volume (with sub-functions) */
  4850. /*-----------------------------------------------------------------------*/
  4851. #define N_SEC_TRACK 63 /* Sectors per track for determination of drive CHS */
  4852. #define GPT_ALIGN 0x100000 /* Alignment of partitions in GPT [byte] (>=128KB) */
  4853. #define GPT_ITEMS 128 /* Number of GPT table size (>=128, sector aligned) */
  4854. /* Create partitions on the physical drive in format of MBR or GPT */
  4855. static FRESULT create_partition (
  4856. BYTE drv, /* Physical drive number */
  4857. const LBA_t plst[], /* Partition list */
  4858. BYTE sys, /* System ID (for only MBR, temp setting) */
  4859. BYTE* buf /* Working buffer for a sector */
  4860. )
  4861. {
  4862. UINT i, cy;
  4863. LBA_t sz_drv;
  4864. DWORD sz_drv32, nxt_alloc32, sz_part32;
  4865. BYTE *pte;
  4866. BYTE hd, n_hd, sc, n_sc;
  4867. /* Get physical drive size */
  4868. if (disk_ioctl(drv, GET_SECTOR_COUNT, &sz_drv) != RES_OK) return FR_DISK_ERR;
  4869. #if FF_LBA64
  4870. if (sz_drv >= FF_MIN_GPT) { /* Create partitions in GPT format */
  4871. WORD ss;
  4872. UINT sz_ptbl, pi, si, ofs;
  4873. DWORD bcc, rnd, align;
  4874. QWORD nxt_alloc, sz_part, sz_pool, top_bpt;
  4875. static const BYTE gpt_mbr[16] = {0x00, 0x00, 0x02, 0x00, 0xEE, 0xFE, 0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};
  4876. #if FF_MAX_SS != FF_MIN_SS
  4877. if (disk_ioctl(drv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR; /* Get sector size */
  4878. if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  4879. #else
  4880. ss = FF_MAX_SS;
  4881. #endif
  4882. rnd = (DWORD)sz_drv + GET_FATTIME(); /* Random seed */
  4883. align = GPT_ALIGN / ss; /* Partition alignment for GPT [sector] */
  4884. sz_ptbl = GPT_ITEMS * SZ_GPTE / ss; /* Size of partition table [sector] */
  4885. top_bpt = sz_drv - sz_ptbl - 1; /* Backup partiiton table start sector */
  4886. nxt_alloc = 2 + sz_ptbl; /* First allocatable sector */
  4887. sz_pool = top_bpt - nxt_alloc; /* Size of allocatable area */
  4888. bcc = 0xFFFFFFFF; sz_part = 1;
  4889. pi = si = 0; /* partition table index, size table index */
  4890. do {
  4891. if (pi * SZ_GPTE % ss == 0) memset(buf, 0, ss); /* Clean the buffer if needed */
  4892. if (sz_part != 0) { /* Is the size table not termintated? */
  4893. nxt_alloc = (nxt_alloc + align - 1) & ((QWORD)0 - align); /* Align partition start */
  4894. sz_part = plst[si++]; /* Get a partition size */
  4895. if (sz_part <= 100) { /* Is the size in percentage? */
  4896. sz_part = sz_pool * sz_part / 100;
  4897. sz_part = (sz_part + align - 1) & ((QWORD)0 - align); /* Align partition end (only if in percentage) */
  4898. }
  4899. if (nxt_alloc + sz_part > top_bpt) { /* Clip the size at end of the pool */
  4900. sz_part = (nxt_alloc < top_bpt) ? top_bpt - nxt_alloc : 0;
  4901. }
  4902. }
  4903. if (sz_part != 0) { /* Add a partition? */
  4904. ofs = pi * SZ_GPTE % ss;
  4905. memcpy(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16); /* Set partition GUID (Microsoft Basic Data) */
  4906. rnd = make_rand(rnd, buf + ofs + GPTE_UpGuid, 16); /* Set unique partition GUID */
  4907. st_qword(buf + ofs + GPTE_FstLba, nxt_alloc); /* Set partition start sector */
  4908. st_qword(buf + ofs + GPTE_LstLba, nxt_alloc + sz_part - 1); /* Set partition end sector */
  4909. nxt_alloc += sz_part; /* Next allocatable sector */
  4910. }
  4911. if ((pi + 1) * SZ_GPTE % ss == 0) { /* Write the buffer if it is filled up */
  4912. for (i = 0; i < ss; bcc = crc32(bcc, buf[i++])) ; /* Calculate table check sum */
  4913. if (disk_write(drv, buf, 2 + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to primary table */
  4914. if (disk_write(drv, buf, top_bpt + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to secondary table */
  4915. }
  4916. } while (++pi < GPT_ITEMS);
  4917. /* Create primary GPT header */
  4918. memset(buf, 0, ss);
  4919. memcpy(buf + GPTH_Sign, "EFI PART" "\0\0\1\0" "\x5C\0\0", 16); /* Signature, version (1.0) and size (92) */
  4920. st_dword(buf + GPTH_PtBcc, ~bcc); /* Table check sum */
  4921. st_qword(buf + GPTH_CurLba, 1); /* LBA of this header */
  4922. st_qword(buf + GPTH_BakLba, sz_drv - 1); /* LBA of secondary header */
  4923. st_qword(buf + GPTH_FstLba, 2 + sz_ptbl); /* LBA of first allocatable sector */
  4924. st_qword(buf + GPTH_LstLba, top_bpt - 1); /* LBA of last allocatable sector */
  4925. st_dword(buf + GPTH_PteSize, SZ_GPTE); /* Size of a table entry */
  4926. st_dword(buf + GPTH_PtNum, GPT_ITEMS); /* Number of table entries */
  4927. st_dword(buf + GPTH_PtOfs, 2); /* LBA of this table */
  4928. rnd = make_rand(rnd, buf + GPTH_DskGuid, 16); /* Disk GUID */
  4929. for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */
  4930. st_dword(buf + GPTH_Bcc, ~bcc); /* Header check sum */
  4931. if (disk_write(drv, buf, 1, 1) != RES_OK) return FR_DISK_ERR;
  4932. /* Create secondary GPT header */
  4933. st_qword(buf + GPTH_CurLba, sz_drv - 1); /* LBA of this header */
  4934. st_qword(buf + GPTH_BakLba, 1); /* LBA of primary header */
  4935. st_qword(buf + GPTH_PtOfs, top_bpt); /* LBA of this table */
  4936. st_dword(buf + GPTH_Bcc, 0);
  4937. for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */
  4938. st_dword(buf + GPTH_Bcc, ~bcc); /* Header check sum */
  4939. if (disk_write(drv, buf, sz_drv - 1, 1) != RES_OK) return FR_DISK_ERR;
  4940. /* Create protective MBR */
  4941. memset(buf, 0, ss);
  4942. memcpy(buf + MBR_Table, gpt_mbr, 16); /* Create a GPT partition */
  4943. st_word(buf + BS_55AA, 0xAA55);
  4944. if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR;
  4945. } else
  4946. #endif
  4947. { /* Create partitions in MBR format */
  4948. sz_drv32 = (DWORD)sz_drv;
  4949. n_sc = N_SEC_TRACK; /* Determine drive CHS without any consideration of the drive geometry */
  4950. for (n_hd = 8; n_hd != 0 && sz_drv32 / n_hd / n_sc > 1024; n_hd *= 2) ;
  4951. if (n_hd == 0) n_hd = 255; /* Number of heads needs to be <256 */
  4952. memset(buf, 0, FF_MAX_SS); /* Clear MBR */
  4953. pte = buf + MBR_Table; /* Partition table in the MBR */
  4954. for (i = 0, nxt_alloc32 = n_sc; i < 4 && nxt_alloc32 != 0 && nxt_alloc32 < sz_drv32; i++, nxt_alloc32 += sz_part32) {
  4955. sz_part32 = (DWORD)plst[i]; /* Get partition size */
  4956. if (sz_part32 <= 100) sz_part32 = (sz_part32 == 100) ? sz_drv32 : sz_drv32 / 100 * sz_part32; /* Size in percentage? */
  4957. if (nxt_alloc32 + sz_part32 > sz_drv32 || nxt_alloc32 + sz_part32 < nxt_alloc32) sz_part32 = sz_drv32 - nxt_alloc32; /* Clip at drive size */
  4958. if (sz_part32 == 0) break; /* End of table or no sector to allocate? */
  4959. st_dword(pte + PTE_StLba, nxt_alloc32); /* Start LBA */
  4960. st_dword(pte + PTE_SizLba, sz_part32); /* Number of sectors */
  4961. pte[PTE_System] = sys; /* System type */
  4962. cy = (UINT)(nxt_alloc32 / n_sc / n_hd); /* Start cylinder */
  4963. hd = (BYTE)(nxt_alloc32 / n_sc % n_hd); /* Start head */
  4964. sc = (BYTE)(nxt_alloc32 % n_sc + 1); /* Start sector */
  4965. pte[PTE_StHead] = hd;
  4966. pte[PTE_StSec] = (BYTE)((cy >> 2 & 0xC0) | sc);
  4967. pte[PTE_StCyl] = (BYTE)cy;
  4968. cy = (UINT)((nxt_alloc32 + sz_part32 - 1) / n_sc / n_hd); /* End cylinder */
  4969. hd = (BYTE)((nxt_alloc32 + sz_part32 - 1) / n_sc % n_hd); /* End head */
  4970. sc = (BYTE)((nxt_alloc32 + sz_part32 - 1) % n_sc + 1); /* End sector */
  4971. pte[PTE_EdHead] = hd;
  4972. pte[PTE_EdSec] = (BYTE)((cy >> 2 & 0xC0) | sc);
  4973. pte[PTE_EdCyl] = (BYTE)cy;
  4974. pte += SZ_PTE; /* Next entry */
  4975. }
  4976. st_word(buf + BS_55AA, 0xAA55); /* MBR signature */
  4977. if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */
  4978. }
  4979. return FR_OK;
  4980. }
  4981. FRESULT f_mkfs (
  4982. const FATFS_TCHAR* path, /* Logical drive number */
  4983. const MKFS_PARM* opt, /* Format options */
  4984. void* work, /* Pointer to working buffer (null: use heap memory) */
  4985. UINT len /* Size of working buffer [byte] */
  4986. )
  4987. {
  4988. static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT volume (4Ks unit) */
  4989. static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */
  4990. static const MKFS_PARM defopt = {FM_ANY, 0, 0, 0, 0}; /* Default parameter */
  4991. BYTE fsopt, fsty, sys, *buf, *pte, pdrv, ipart;
  4992. WORD ss; /* Sector size */
  4993. DWORD sz_buf, sz_blk, n_clst, pau, nsect, n, vsn;
  4994. LBA_t sz_vol, b_vol, b_fat, b_data; /* Size of volume, Base LBA of volume, fat, data */
  4995. LBA_t sect, lba[2];
  4996. DWORD sz_rsv, sz_fat, sz_dir, sz_au; /* Size of reserved, fat, dir, data, cluster */
  4997. UINT n_fat, n_root, i; /* Index, Number of FATs and Number of roor dir entries */
  4998. int vol;
  4999. DSTATUS ds;
  5000. FRESULT fr;
  5001. /* Check mounted drive and clear work area */
  5002. vol = get_ldnumber(&path); /* Get target logical drive */
  5003. if (vol < 0) return FR_INVALID_DRIVE;
  5004. if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear the fs object if mounted */
  5005. pdrv = LD2PD(vol); /* Physical drive */
  5006. ipart = LD2PT(vol); /* Partition (0:create as new, 1..:get from partition table) */
  5007. if (!opt) opt = &defopt; /* Use default parameter if it is not given */
  5008. /* Get physical drive status (sz_drv, sz_blk, ss) */
  5009. ds = disk_initialize(pdrv);
  5010. if (ds & STA_NOINIT) return FR_NOT_READY;
  5011. if (ds & STA_PROTECT) return FR_WRITE_PROTECTED;
  5012. sz_blk = opt->align;
  5013. if (sz_blk == 0 && disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK) sz_blk = 1;
  5014. if (sz_blk == 0 || sz_blk > 0x8000 || (sz_blk & (sz_blk - 1))) sz_blk = 1;
  5015. #if FF_MAX_SS != FF_MIN_SS
  5016. if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;
  5017. if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;
  5018. #else
  5019. ss = FF_MAX_SS;
  5020. #endif
  5021. /* Options for FAT sub-type and FAT parameters */
  5022. fsopt = opt->fmt & (FM_ANY | FM_SFD);
  5023. n_fat = (opt->n_fat >= 1 && opt->n_fat <= 2) ? opt->n_fat : 1;
  5024. n_root = (opt->n_root >= 1 && opt->n_root <= 32768 && (opt->n_root % (ss / SZDIRE)) == 0) ? opt->n_root : 512;
  5025. sz_au = (opt->au_size <= 0x1000000 && (opt->au_size & (opt->au_size - 1)) == 0) ? opt->au_size : 0;
  5026. sz_au /= ss; /* Byte --> Sector */
  5027. /* Get working buffer */
  5028. sz_buf = len / ss; /* Size of working buffer [sector] */
  5029. if (sz_buf == 0) return FR_NOT_ENOUGH_CORE;
  5030. buf = (BYTE*)work; /* Working buffer */
  5031. #if FF_USE_LFN == 3
  5032. if (!buf) buf = ff_memalloc(sz_buf * ss); /* Use heap memory for working buffer */
  5033. #endif
  5034. if (!buf) return FR_NOT_ENOUGH_CORE;
  5035. /* Determine where the volume to be located (b_vol, sz_vol) */
  5036. b_vol = sz_vol = 0;
  5037. if (FF_MULTI_PARTITION && ipart != 0) { /* Is the volume associated with any specific partition? */
  5038. /* Get partition location from the existing partition table */
  5039. if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Load MBR */
  5040. if (ld_word(buf + BS_55AA) != 0xAA55) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if MBR is valid */
  5041. #if FF_LBA64
  5042. if (buf[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */
  5043. DWORD n_ent, ofs;
  5044. QWORD pt_lba;
  5045. /* Get the partition location from GPT */
  5046. if (disk_read(pdrv, buf, 1, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Load GPT header sector (next to MBR) */
  5047. if (!test_gpt_header(buf)) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if GPT header is valid */
  5048. n_ent = ld_dword(buf + GPTH_PtNum); /* Number of entries */
  5049. pt_lba = ld_qword(buf + GPTH_PtOfs); /* Table start sector */
  5050. ofs = i = 0;
  5051. while (n_ent) { /* Find MS Basic partition with order of ipart */
  5052. if (ofs == 0 && disk_read(pdrv, buf, pt_lba++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Get PT sector */
  5053. if (!memcmp(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16) && ++i == ipart) { /* MS basic data partition? */
  5054. b_vol = ld_qword(buf + ofs + GPTE_FstLba);
  5055. sz_vol = ld_qword(buf + ofs + GPTE_LstLba) - b_vol + 1;
  5056. break;
  5057. }
  5058. n_ent--; ofs = (ofs + SZ_GPTE) % ss; /* Next entry */
  5059. }
  5060. if (n_ent == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* Partition not found */
  5061. fsopt |= 0x80; /* Partitioning is in GPT */
  5062. } else
  5063. #endif
  5064. { /* Get the partition location from MBR partition table */
  5065. pte = buf + (MBR_Table + (ipart - 1) * SZ_PTE);
  5066. if (ipart > 4 || pte[PTE_System] == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* No partition? */
  5067. b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */
  5068. sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */
  5069. }
  5070. } else { /* The volume is associated with a physical drive */
  5071. if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5072. if (!(fsopt & FM_SFD)) { /* To be partitioned? */
  5073. /* Create a single-partition on the drive in this function */
  5074. #if FF_LBA64
  5075. if (sz_vol >= FF_MIN_GPT) { /* Which partition type to create, MBR or GPT? */
  5076. fsopt |= 0x80; /* Partitioning is in GPT */
  5077. b_vol = GPT_ALIGN / ss; sz_vol -= b_vol + GPT_ITEMS * SZ_GPTE / ss + 1; /* Estimated partition offset and size */
  5078. } else
  5079. #endif
  5080. { /* Partitioning is in MBR */
  5081. if (sz_vol > N_SEC_TRACK) {
  5082. b_vol = N_SEC_TRACK; sz_vol -= b_vol; /* Estimated partition offset and size */
  5083. }
  5084. }
  5085. }
  5086. }
  5087. if (sz_vol < 128) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if volume size is >=128s */
  5088. /* Now start to create an FAT volume at b_vol and sz_vol */
  5089. do { /* Pre-determine the FAT type */
  5090. if (FF_FS_EXFAT && (fsopt & FM_EXFAT)) { /* exFAT possible? */
  5091. if ((fsopt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || sz_au > 128) { /* exFAT only, vol >= 64MS or sz_au > 128S ? */
  5092. fsty = FS_EXFAT; break;
  5093. }
  5094. }
  5095. #if FF_LBA64
  5096. if (sz_vol >= 0x100000000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too large volume for FAT/FAT32 */
  5097. #endif
  5098. if (sz_au > 128) sz_au = 128; /* Invalid AU for FAT/FAT32? */
  5099. if (fsopt & FM_FAT32) { /* FAT32 possible? */
  5100. if (!(fsopt & FM_FAT)) { /* no-FAT? */
  5101. fsty = FS_FAT32; break;
  5102. }
  5103. }
  5104. if (!(fsopt & FM_FAT)) LEAVE_MKFS(FR_INVALID_PARAMETER); /* no-FAT? */
  5105. fsty = FS_FAT16;
  5106. } while (0);
  5107. vsn = (DWORD)sz_vol + GET_FATTIME(); /* VSN generated from current time and partitiion size */
  5108. #if FF_FS_EXFAT
  5109. if (fsty == FS_EXFAT) { /* Create an exFAT volume */
  5110. DWORD szb_bit, szb_case, sum, nbit, clu, clen[3];
  5111. WCHAR ch, si;
  5112. UINT j, st;
  5113. if (sz_vol < 0x1000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume for exFAT? */
  5114. #if FF_USE_TRIM
  5115. lba[0] = b_vol; lba[1] = b_vol + sz_vol - 1; /* Inform storage device that the volume area may be erased */
  5116. disk_ioctl(pdrv, CTRL_TRIM, lba);
  5117. #endif
  5118. /* Determine FAT location, data location and number of clusters */
  5119. if (sz_au == 0) { /* AU auto-selection */
  5120. sz_au = 8;
  5121. if (sz_vol >= 0x80000) sz_au = 64; /* >= 512Ks */
  5122. if (sz_vol >= 0x4000000) sz_au = 256; /* >= 64Ms */
  5123. }
  5124. b_fat = b_vol + 32; /* FAT start at offset 32 */
  5125. sz_fat = (DWORD)((sz_vol / sz_au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */
  5126. b_data = (b_fat + sz_fat + sz_blk - 1) & ~((LBA_t)sz_blk - 1); /* Align data area to the erase block boundary */
  5127. if (b_data - b_vol >= sz_vol / 2) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */
  5128. n_clst = (DWORD)(sz_vol - (b_data - b_vol)) / sz_au; /* Number of clusters */
  5129. if (n_clst <16) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too few clusters? */
  5130. if (n_clst > MAX_EXFAT) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters? */
  5131. szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */
  5132. clen[0] = (szb_bit + sz_au * ss - 1) / (sz_au * ss); /* Number of allocation bitmap clusters */
  5133. /* Create a compressed up-case table */
  5134. sect = b_data + sz_au * clen[0]; /* Table start sector */
  5135. sum = 0; /* Table checksum to be stored in the 82 entry */
  5136. st = 0; si = 0; i = 0; j = 0; szb_case = 0;
  5137. do {
  5138. switch (st) {
  5139. case 0:
  5140. ch = (WCHAR)ff_wtoupper(si); /* Get an up-case char */
  5141. if (ch != si) {
  5142. si++; break; /* Store the up-case char if exist */
  5143. }
  5144. for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */
  5145. if (j >= 128) {
  5146. ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 chars */
  5147. }
  5148. st = 1; /* Do not compress short run */
  5149. /* FALLTHROUGH */
  5150. case 1:
  5151. ch = si++; /* Fill the short run */
  5152. if (--j == 0) st = 0;
  5153. break;
  5154. default:
  5155. ch = (WCHAR)j; si += (WCHAR)j; /* Number of chars to skip */
  5156. st = 0;
  5157. }
  5158. sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */
  5159. sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);
  5160. i += 2; szb_case += 2;
  5161. if (si == 0 || i == sz_buf * ss) { /* Write buffered data when buffer full or end of process */
  5162. n = (i + ss - 1) / ss;
  5163. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5164. sect += n; i = 0;
  5165. }
  5166. } while (si);
  5167. clen[1] = (szb_case + sz_au * ss - 1) / (sz_au * ss); /* Number of up-case table clusters */
  5168. clen[2] = 1; /* Number of root dir clusters */
  5169. /* Initialize the allocation bitmap */
  5170. sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of bitmap sectors */
  5171. nbit = clen[0] + clen[1] + clen[2]; /* Number of clusters in-use by system (bitmap, up-case and root-dir) */
  5172. do {
  5173. memset(buf, 0, sz_buf * ss); /* Initialize bitmap buffer */
  5174. for (i = 0; nbit != 0 && i / 8 < sz_buf * ss; buf[i / 8] |= 1 << (i % 8), i++, nbit--) ; /* Mark used clusters */
  5175. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  5176. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5177. sect += n; nsect -= n;
  5178. } while (nsect);
  5179. /* Initialize the FAT */
  5180. sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */
  5181. j = nbit = clu = 0;
  5182. do {
  5183. memset(buf, 0, sz_buf * ss); i = 0; /* Clear work area and reset write offset */
  5184. if (clu == 0) { /* Initialize FAT [0] and FAT[1] */
  5185. st_dword(buf + i, 0xFFFFFFF8); i += 4; clu++;
  5186. st_dword(buf + i, 0xFFFFFFFF); i += 4; clu++;
  5187. }
  5188. do { /* Create chains of bitmap, up-case and root dir */
  5189. while (nbit != 0 && i < sz_buf * ss) { /* Create a chain */
  5190. st_dword(buf + i, (nbit > 1) ? clu + 1 : 0xFFFFFFFF);
  5191. i += 4; clu++; nbit--;
  5192. }
  5193. if (nbit == 0 && j < 3) nbit = clen[j++]; /* Get next chain length */
  5194. } while (nbit != 0 && i < sz_buf * ss);
  5195. n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */
  5196. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5197. sect += n; nsect -= n;
  5198. } while (nsect);
  5199. /* Initialize the root directory */
  5200. memset(buf, 0, sz_buf * ss);
  5201. buf[SZDIRE * 0 + 0] = ET_VLABEL; /* Volume label entry (no label) */
  5202. buf[SZDIRE * 1 + 0] = ET_BITMAP; /* Bitmap entry */
  5203. st_dword(buf + SZDIRE * 1 + 20, 2); /* cluster */
  5204. st_dword(buf + SZDIRE * 1 + 24, szb_bit); /* size */
  5205. buf[SZDIRE * 2 + 0] = ET_UPCASE; /* Up-case table entry */
  5206. st_dword(buf + SZDIRE * 2 + 4, sum); /* sum */
  5207. st_dword(buf + SZDIRE * 2 + 20, 2 + clen[0]); /* cluster */
  5208. st_dword(buf + SZDIRE * 2 + 24, szb_case); /* size */
  5209. sect = b_data + sz_au * (clen[0] + clen[1]); nsect = sz_au; /* Start of the root directory and number of sectors */
  5210. do { /* Fill root directory sectors */
  5211. n = (nsect > sz_buf) ? sz_buf : nsect;
  5212. if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5213. memset(buf, 0, ss); /* Rest of entries are filled with zero */
  5214. sect += n; nsect -= n;
  5215. } while (nsect);
  5216. /* Create two set of the exFAT VBR blocks */
  5217. sect = b_vol;
  5218. for (n = 0; n < 2; n++) {
  5219. /* Main record (+0) */
  5220. memset(buf, 0, ss);
  5221. memcpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */
  5222. st_qword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */
  5223. st_qword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */
  5224. st_dword(buf + BPB_FatOfsEx, (DWORD)(b_fat - b_vol)); /* FAT offset [sector] */
  5225. st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */
  5226. st_dword(buf + BPB_DataOfsEx, (DWORD)(b_data - b_vol)); /* Data offset [sector] */
  5227. st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */
  5228. st_dword(buf + BPB_RootClusEx, 2 + clen[0] + clen[1]); /* Root dir cluster # */
  5229. st_dword(buf + BPB_VolIDEx, vsn); /* VSN */
  5230. st_word(buf + BPB_FSVerEx, 0x100); /* Filesystem version (1.00) */
  5231. for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */
  5232. for (buf[BPB_SecPerClusEx] = 0, i = sz_au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */
  5233. buf[BPB_NumFATsEx] = 1; /* Number of FATs */
  5234. buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */
  5235. st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */
  5236. st_word(buf + BS_55AA, 0xAA55); /* Signature (placed here regardless of sector size) */
  5237. for (i = sum = 0; i < ss; i++) { /* VBR checksum */
  5238. if (i != BPB_VolFlagEx && i != BPB_VolFlagEx + 1 && i != BPB_PercInUseEx) sum = xsum32(buf[i], sum);
  5239. }
  5240. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5241. /* Extended bootstrap record (+1..+8) */
  5242. memset(buf, 0, ss);
  5243. st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */
  5244. for (j = 1; j < 9; j++) {
  5245. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  5246. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5247. }
  5248. /* OEM/Reserved record (+9..+10) */
  5249. memset(buf, 0, ss);
  5250. for ( ; j < 11; j++) {
  5251. for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */
  5252. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5253. }
  5254. /* Sum record (+11) */
  5255. for (i = 0; i < ss; i += 4) st_dword(buf + i, sum); /* Fill with checksum value */
  5256. if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5257. }
  5258. } else
  5259. #endif /* FF_FS_EXFAT */
  5260. { /* Create an FAT/FAT32 volume */
  5261. do {
  5262. pau = sz_au;
  5263. /* Pre-determine number of clusters and FAT sub-type */
  5264. if (fsty == FS_FAT32) { /* FAT32 volume */
  5265. if (pau == 0) { /* AU auto-selection */
  5266. n = (DWORD)sz_vol / 0x20000; /* Volume size in unit of 128KS */
  5267. for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */
  5268. }
  5269. n_clst = (DWORD)sz_vol / pau; /* Number of clusters */
  5270. sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */
  5271. sz_rsv = 32; /* Number of reserved sectors */
  5272. sz_dir = 0; /* No static directory */
  5273. if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) LEAVE_MKFS(FR_MKFS_ABORTED);
  5274. } else { /* FAT volume */
  5275. if (pau == 0) { /* au auto-selection */
  5276. n = (DWORD)sz_vol / 0x1000; /* Volume size in unit of 4KS */
  5277. for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */
  5278. }
  5279. n_clst = (DWORD)sz_vol / pau;
  5280. if (n_clst > MAX_FAT12) {
  5281. n = n_clst * 2 + 4; /* FAT size [byte] */
  5282. } else {
  5283. fsty = FS_FAT12;
  5284. n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */
  5285. }
  5286. sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */
  5287. sz_rsv = 1; /* Number of reserved sectors */
  5288. sz_dir = (DWORD)n_root * SZDIRE / ss; /* Root dir size [sector] */
  5289. }
  5290. b_fat = b_vol + sz_rsv; /* FAT base */
  5291. b_data = b_fat + sz_fat * n_fat + sz_dir; /* Data base */
  5292. /* Align data area to erase block boundary (for flash memory media) */
  5293. n = (DWORD)(((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data); /* Sectors to next nearest from current data base */
  5294. if (fsty == FS_FAT32) { /* FAT32: Move FAT */
  5295. sz_rsv += n; b_fat += n;
  5296. } else { /* FAT: Expand FAT */
  5297. if (n % n_fat) { /* Adjust fractional error if needed */
  5298. n--; sz_rsv++; b_fat++;
  5299. }
  5300. sz_fat += n / n_fat;
  5301. }
  5302. /* Determine number of clusters and final check of validity of the FAT sub-type */
  5303. if (sz_vol < b_data + pau * 16 - b_vol) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */
  5304. n_clst = ((DWORD)sz_vol - sz_rsv - sz_fat * n_fat - sz_dir) / pau;
  5305. if (fsty == FS_FAT32) {
  5306. if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32? */
  5307. if (sz_au == 0 && (sz_au = pau / 2) != 0) continue; /* Adjust cluster size and retry */
  5308. LEAVE_MKFS(FR_MKFS_ABORTED);
  5309. }
  5310. }
  5311. if (fsty == FS_FAT16) {
  5312. if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */
  5313. if (sz_au == 0 && (pau * 2) <= 64) {
  5314. sz_au = pau * 2; continue; /* Adjust cluster size and retry */
  5315. }
  5316. if ((fsopt & FM_FAT32)) {
  5317. fsty = FS_FAT32; continue; /* Switch type to FAT32 and retry */
  5318. }
  5319. if (sz_au == 0 && (sz_au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  5320. LEAVE_MKFS(FR_MKFS_ABORTED);
  5321. }
  5322. if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */
  5323. if (sz_au == 0 && (sz_au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */
  5324. LEAVE_MKFS(FR_MKFS_ABORTED);
  5325. }
  5326. }
  5327. if (fsty == FS_FAT12 && n_clst > MAX_FAT12) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters for FAT12 */
  5328. /* Ok, it is the valid cluster configuration */
  5329. break;
  5330. } while (1);
  5331. #if FF_USE_TRIM
  5332. lba[0] = b_vol; lba[1] = b_vol + sz_vol - 1; /* Inform storage device that the volume area may be erased */
  5333. disk_ioctl(pdrv, CTRL_TRIM, lba);
  5334. #endif
  5335. /* Create FAT VBR */
  5336. memset(buf, 0, ss);
  5337. memcpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11); /* Boot jump code (x86), OEM name */
  5338. st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */
  5339. buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */
  5340. st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */
  5341. buf[BPB_NumFATs] = (BYTE)n_fat; /* Number of FATs */
  5342. st_word(buf + BPB_RootEntCnt, (WORD)((fsty == FS_FAT32) ? 0 : n_root)); /* Number of root directory entries */
  5343. if (sz_vol < 0x10000) {
  5344. st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */
  5345. } else {
  5346. st_dword(buf + BPB_TotSec32, (DWORD)sz_vol); /* Volume size in 32-bit LBA */
  5347. }
  5348. buf[BPB_Media] = 0xF8; /* Media descriptor byte */
  5349. st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */
  5350. st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */
  5351. st_dword(buf + BPB_HiddSec, (DWORD)b_vol); /* Volume offset in the physical drive [sector] */
  5352. if (fsty == FS_FAT32) {
  5353. st_dword(buf + BS_VolID32, vsn); /* VSN */
  5354. st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */
  5355. st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */
  5356. st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */
  5357. st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */
  5358. buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */
  5359. buf[BS_BootSig32] = 0x29; /* Extended boot signature */
  5360. memcpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */
  5361. } else {
  5362. st_dword(buf + BS_VolID, vsn); /* VSN */
  5363. st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */
  5364. buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */
  5365. buf[BS_BootSig] = 0x29; /* Extended boot signature */
  5366. memcpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */
  5367. }
  5368. st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */
  5369. if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it to the VBR sector */
  5370. /* Create FSINFO record if needed */
  5371. if (fsty == FS_FAT32) {
  5372. disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */
  5373. memset(buf, 0, ss);
  5374. st_dword(buf + FSI_LeadSig, 0x41615252);
  5375. st_dword(buf + FSI_StrucSig, 0x61417272);
  5376. st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */
  5377. st_dword(buf + FSI_Nxt_Free, 2); /* Last allocated cluster# */
  5378. st_word(buf + BS_55AA, 0xAA55);
  5379. disk_write(pdrv, buf, b_vol + 7, 1); /* Write backup FSINFO (VBR + 7) */
  5380. disk_write(pdrv, buf, b_vol + 1, 1); /* Write original FSINFO (VBR + 1) */
  5381. }
  5382. /* Initialize FAT area */
  5383. memset(buf, 0, sz_buf * ss);
  5384. sect = b_fat; /* FAT start sector */
  5385. for (i = 0; i < n_fat; i++) { /* Initialize FATs each */
  5386. if (fsty == FS_FAT32) {
  5387. st_dword(buf + 0, 0xFFFFFFF8); /* FAT[0] */
  5388. st_dword(buf + 4, 0xFFFFFFFF); /* FAT[1] */
  5389. st_dword(buf + 8, 0x0FFFFFFF); /* FAT[2] (root directory) */
  5390. } else {
  5391. st_dword(buf + 0, (fsty == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* FAT[0] and FAT[1] */
  5392. }
  5393. nsect = sz_fat; /* Number of FAT sectors */
  5394. do { /* Fill FAT sectors */
  5395. n = (nsect > sz_buf) ? sz_buf : nsect;
  5396. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5397. memset(buf, 0, ss); /* Rest of FAT all are cleared */
  5398. sect += n; nsect -= n;
  5399. } while (nsect);
  5400. }
  5401. /* Initialize root directory (fill with zero) */
  5402. nsect = (fsty == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */
  5403. do {
  5404. n = (nsect > sz_buf) ? sz_buf : nsect;
  5405. if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5406. sect += n; nsect -= n;
  5407. } while (nsect);
  5408. }
  5409. /* A FAT volume has been created here */
  5410. /* Determine system ID in the MBR partition table */
  5411. if (FF_FS_EXFAT && fsty == FS_EXFAT) {
  5412. sys = 0x07; /* exFAT */
  5413. } else {
  5414. if (fsty == FS_FAT32) {
  5415. sys = 0x0C; /* FAT32X */
  5416. } else {
  5417. if (sz_vol >= 0x10000) {
  5418. sys = 0x06; /* FAT12/16 (large) */
  5419. } else {
  5420. sys = (fsty == FS_FAT16) ? 0x04 : 0x01; /* FAT16 : FAT12 */
  5421. }
  5422. }
  5423. }
  5424. /* Update partition information */
  5425. if (FF_MULTI_PARTITION && ipart != 0) { /* Volume is in the existing partition */
  5426. if (!FF_LBA64 || !(fsopt & 0x80)) {
  5427. /* Update system ID in the partition table */
  5428. if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Read the MBR */
  5429. buf[MBR_Table + (ipart - 1) * SZ_PTE + PTE_System] = sys; /* Set system ID */
  5430. if (disk_write(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it back to the MBR */
  5431. }
  5432. } else { /* Volume as a new single partition */
  5433. if (!(fsopt & FM_SFD)) { /* Create partition table if not in SFD */
  5434. lba[0] = sz_vol; lba[1] = 0;
  5435. fr = create_partition(pdrv, lba, sys, buf);
  5436. if (fr != FR_OK) LEAVE_MKFS(fr);
  5437. }
  5438. }
  5439. if (disk_ioctl(pdrv, CTRL_SYNC, 0) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);
  5440. LEAVE_MKFS(FR_OK);
  5441. }
  5442. #if FF_MULTI_PARTITION
  5443. /*-----------------------------------------------------------------------*/
  5444. /* Create Partition Table on the Physical Drive */
  5445. /*-----------------------------------------------------------------------*/
  5446. FRESULT f_fdisk (
  5447. BYTE pdrv, /* Physical drive number */
  5448. const LBA_t ptbl[], /* Pointer to the size table for each partitions */
  5449. void* work /* Pointer to the working buffer (null: use heap memory) */
  5450. )
  5451. {
  5452. BYTE *buf = (BYTE*)work;
  5453. DSTATUS stat;
  5454. stat = disk_initialize(pdrv);
  5455. if (stat & STA_NOINIT) return FR_NOT_READY;
  5456. if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
  5457. #if FF_USE_LFN == 3
  5458. if (!buf) buf = ff_memalloc(FF_MAX_SS); /* Use heap memory for working buffer */
  5459. #endif
  5460. if (!buf) return FR_NOT_ENOUGH_CORE;
  5461. LEAVE_MKFS(create_partition(pdrv, ptbl, 0x07, buf));
  5462. }
  5463. #endif /* FF_MULTI_PARTITION */
  5464. #endif /* !FF_FS_READONLY && FF_USE_MKFS */
  5465. #if FF_USE_STRFUNC
  5466. #if FF_USE_LFN && FF_LFN_UNICODE && (FF_STRF_ENCODE < 0 || FF_STRF_ENCODE > 3)
  5467. #error Wrong FF_STRF_ENCODE setting
  5468. #endif
  5469. /*-----------------------------------------------------------------------*/
  5470. /* Get a String from the File */
  5471. /*-----------------------------------------------------------------------*/
  5472. FATFS_TCHAR* f_gets (
  5473. FATFS_TCHAR* buff, /* Pointer to the buffer to store read string */
  5474. int len, /* Size of string buffer (items) */
  5475. FIL* fp /* Pointer to the file object */
  5476. )
  5477. {
  5478. int nc = 0;
  5479. FATFS_TCHAR *p = buff;
  5480. BYTE s[4];
  5481. UINT rc;
  5482. DWORD dc;
  5483. #if FF_USE_LFN && FF_LFN_UNICODE && FF_STRF_ENCODE <= 2
  5484. WCHAR wc;
  5485. #endif
  5486. #if FF_USE_LFN && FF_LFN_UNICODE && FF_STRF_ENCODE == 3
  5487. UINT ct;
  5488. #endif
  5489. #if FF_USE_LFN && FF_LFN_UNICODE /* With code conversion (Unicode API) */
  5490. /* Make a room for the character and terminator */
  5491. if (FF_LFN_UNICODE == 1) len -= (FF_STRF_ENCODE == 0) ? 1 : 2;
  5492. if (FF_LFN_UNICODE == 2) len -= (FF_STRF_ENCODE == 0) ? 3 : 4;
  5493. if (FF_LFN_UNICODE == 3) len -= 1;
  5494. while (nc < len) {
  5495. #if FF_STRF_ENCODE == 0 /* Read a character in ANSI/OEM */
  5496. f_read(fp, s, 1, &rc); /* Get a code unit */
  5497. if (rc != 1) break; /* EOF? */
  5498. wc = s[0];
  5499. if (dbc_1st((BYTE)wc)) { /* DBC 1st byte? */
  5500. f_read(fp, s, 1, &rc); /* Get 2nd byte */
  5501. if (rc != 1 || !dbc_2nd(s[0])) continue; /* Wrong code? */
  5502. wc = wc << 8 | s[0];
  5503. }
  5504. dc = ff_oem2uni(wc, CODEPAGE); /* Convert ANSI/OEM into Unicode */
  5505. if (dc == 0) continue; /* Conversion error? */
  5506. #elif FF_STRF_ENCODE == 1 || FF_STRF_ENCODE == 2 /* Read a character in UTF-16LE/BE */
  5507. f_read(fp, s, 2, &rc); /* Get a code unit */
  5508. if (rc != 2) break; /* EOF? */
  5509. dc = (FF_STRF_ENCODE == 1) ? ld_word(s) : s[0] << 8 | s[1];
  5510. if (IsSurrogateL(dc)) continue; /* Broken surrogate pair? */
  5511. if (IsSurrogateH(dc)) { /* High surrogate? */
  5512. f_read(fp, s, 2, &rc); /* Get low surrogate */
  5513. if (rc != 2) break; /* EOF? */
  5514. wc = (FF_STRF_ENCODE == 1) ? ld_word(s) : s[0] << 8 | s[1];
  5515. if (!IsSurrogateL(wc)) continue; /* Broken surrogate pair? */
  5516. dc = ((dc & 0x3FF) + 0x40) << 10 | (wc & 0x3FF); /* Merge surrogate pair */
  5517. }
  5518. #else /* Read a character in UTF-8 */
  5519. f_read(fp, s, 1, &rc); /* Get a code unit */
  5520. if (rc != 1) break; /* EOF? */
  5521. dc = s[0];
  5522. if (dc >= 0x80) { /* Multi-byte sequence? */
  5523. ct = 0;
  5524. if ((dc & 0xE0) == 0xC0) { dc &= 0x1F; ct = 1; } /* 2-byte sequence? */
  5525. if ((dc & 0xF0) == 0xE0) { dc &= 0x0F; ct = 2; } /* 3-byte sequence? */
  5526. if ((dc & 0xF8) == 0xF0) { dc &= 0x07; ct = 3; } /* 4-byte sequence? */
  5527. if (ct == 0) continue;
  5528. f_read(fp, s, ct, &rc); /* Get trailing bytes */
  5529. if (rc != ct) break;
  5530. rc = 0;
  5531. do { /* Merge the byte sequence */
  5532. if ((s[rc] & 0xC0) != 0x80) break;
  5533. dc = dc << 6 | (s[rc] & 0x3F);
  5534. } while (++rc < ct);
  5535. if (rc != ct || dc < 0x80 || IsSurrogate(dc) || dc >= 0x110000) continue; /* Wrong encoding? */
  5536. }
  5537. #endif
  5538. /* A code point is avaialble in dc to be output */
  5539. if (FF_USE_STRFUNC == 2 && dc == '\r') continue; /* Strip \r off if needed */
  5540. #if FF_LFN_UNICODE == 1 || FF_LFN_UNICODE == 3 /* Output it in UTF-16/32 encoding */
  5541. if (FF_LFN_UNICODE == 1 && dc >= 0x10000) { /* Out of BMP at UTF-16? */
  5542. *p++ = (FATFS_TCHAR)(0xD800 | ((dc >> 10) - 0x40)); nc++; /* Make and output high surrogate */
  5543. dc = 0xDC00 | (dc & 0x3FF); /* Make low surrogate */
  5544. }
  5545. *p++ = (FATFS_TCHAR)dc; nc++;
  5546. if (dc == '\n') break; /* End of line? */
  5547. #elif FF_LFN_UNICODE == 2 /* Output it in UTF-8 encoding */
  5548. if (dc < 0x80) { /* Single byte? */
  5549. *p++ = (FATFS_TCHAR)dc;
  5550. nc++;
  5551. if (dc == '\n') break; /* End of line? */
  5552. } else {
  5553. if (dc < 0x800) { /* 2-byte sequence? */
  5554. *p++ = (FATFS_TCHAR)(0xC0 | (dc >> 6 & 0x1F));
  5555. *p++ = (FATFS_TCHAR)(0x80 | (dc >> 0 & 0x3F));
  5556. nc += 2;
  5557. } else {
  5558. if (dc < 0x10000) { /* 3-byte sequence? */
  5559. *p++ = (FATFS_TCHAR)(0xE0 | (dc >> 12 & 0x0F));
  5560. *p++ = (FATFS_TCHAR)(0x80 | (dc >> 6 & 0x3F));
  5561. *p++ = (FATFS_TCHAR)(0x80 | (dc >> 0 & 0x3F));
  5562. nc += 3;
  5563. } else { /* 4-byte sequence? */
  5564. *p++ = (FATFS_TCHAR)(0xF0 | (dc >> 18 & 0x07));
  5565. *p++ = (FATFS_TCHAR)(0x80 | (dc >> 12 & 0x3F));
  5566. *p++ = (FATFS_TCHAR)(0x80 | (dc >> 6 & 0x3F));
  5567. *p++ = (FATFS_TCHAR)(0x80 | (dc >> 0 & 0x3F));
  5568. nc += 4;
  5569. }
  5570. }
  5571. }
  5572. #endif
  5573. }
  5574. #else /* Byte-by-byte read without any conversion (ANSI/OEM API) */
  5575. len -= 1; /* Make a room for the terminator */
  5576. while (nc < len) {
  5577. f_read(fp, s, 1, &rc); /* Get a byte */
  5578. if (rc != 1) break; /* EOF? */
  5579. dc = s[0];
  5580. if (FF_USE_STRFUNC == 2 && dc == '\r') continue;
  5581. *p++ = (FATFS_TCHAR)dc; nc++;
  5582. if (dc == '\n') break;
  5583. }
  5584. #endif
  5585. *p = 0; /* Terminate the string */
  5586. return nc ? buff : 0; /* When no data read due to EOF or error, return with error. */
  5587. }
  5588. #if !FF_FS_READONLY
  5589. #include <stdarg.h>
  5590. #define SZ_PUTC_BUF 64
  5591. #define SZ_NUM_BUF 32
  5592. /*-----------------------------------------------------------------------*/
  5593. /* Put a Character to the File (with sub-functions) */
  5594. /*-----------------------------------------------------------------------*/
  5595. /* Output buffer and work area */
  5596. typedef struct {
  5597. FIL *fp; /* Ptr to the writing file */
  5598. int idx, nchr; /* Write index of buf[] (-1:error), number of encoding units written */
  5599. #if FF_USE_LFN && FF_LFN_UNICODE == 1
  5600. WCHAR hs;
  5601. #elif FF_USE_LFN && FF_LFN_UNICODE == 2
  5602. BYTE bs[4];
  5603. UINT wi, ct;
  5604. #endif
  5605. BYTE buf[SZ_PUTC_BUF]; /* Write buffer */
  5606. } putbuff;
  5607. /* Buffered file write with code conversion */
  5608. static void putc_bfd (putbuff* pb, FATFS_TCHAR c)
  5609. {
  5610. UINT n;
  5611. int i, nc;
  5612. #if FF_USE_LFN && FF_LFN_UNICODE
  5613. WCHAR hs, wc;
  5614. #if FF_LFN_UNICODE == 2
  5615. DWORD dc;
  5616. const FATFS_TCHAR *tp;
  5617. #endif
  5618. #endif
  5619. if (FF_USE_STRFUNC == 2 && c == '\n') { /* LF -> CRLF conversion */
  5620. putc_bfd(pb, '\r');
  5621. }
  5622. i = pb->idx; /* Write index of pb->buf[] */
  5623. if (i < 0) return; /* In write error? */
  5624. nc = pb->nchr; /* Write unit counter */
  5625. #if FF_USE_LFN && FF_LFN_UNICODE
  5626. #if FF_LFN_UNICODE == 1 /* UTF-16 input */
  5627. if (IsSurrogateH(c)) { /* High surrogate? */
  5628. pb->hs = c; return; /* Save it for next */
  5629. }
  5630. hs = pb->hs; pb->hs = 0;
  5631. if (hs != 0) { /* There is a leading high surrogate */
  5632. if (!IsSurrogateL(c)) hs = 0; /* Discard high surrogate if not a surrogate pair */
  5633. } else {
  5634. if (IsSurrogateL(c)) return; /* Discard stray low surrogate */
  5635. }
  5636. wc = c;
  5637. #elif FF_LFN_UNICODE == 2 /* UTF-8 input */
  5638. for (;;) {
  5639. if (pb->ct == 0) { /* Out of multi-byte sequence? */
  5640. pb->bs[pb->wi = 0] = (BYTE)c; /* Save 1st byte */
  5641. if ((BYTE)c < 0x80) break; /* Single byte? */
  5642. if (((BYTE)c & 0xE0) == 0xC0) pb->ct = 1; /* 2-byte sequence? */
  5643. if (((BYTE)c & 0xF0) == 0xE0) pb->ct = 2; /* 3-byte sequence? */
  5644. if (((BYTE)c & 0xF8) == 0xF0) pb->ct = 3; /* 4-byte sequence? */
  5645. return;
  5646. } else { /* In the multi-byte sequence */
  5647. if (((BYTE)c & 0xC0) != 0x80) { /* Broken sequence? */
  5648. pb->ct = 0; continue;
  5649. }
  5650. pb->bs[++pb->wi] = (BYTE)c; /* Save the trailing byte */
  5651. if (--pb->ct == 0) break; /* End of multi-byte sequence? */
  5652. return;
  5653. }
  5654. }
  5655. tp = (const FATFS_TCHAR*)pb->bs;
  5656. dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */
  5657. if (dc == 0xFFFFFFFF) return; /* Wrong code? */
  5658. wc = (WCHAR)dc;
  5659. hs = (WCHAR)(dc >> 16);
  5660. #elif FF_LFN_UNICODE == 3 /* UTF-32 input */
  5661. if (IsSurrogate(c) || c >= 0x110000) return; /* Discard invalid code */
  5662. if (c >= 0x10000) { /* Out of BMP? */
  5663. hs = (WCHAR)(0xD800 | ((c >> 10) - 0x40)); /* Make high surrogate */
  5664. wc = 0xDC00 | (c & 0x3FF); /* Make low surrogate */
  5665. } else {
  5666. hs = 0;
  5667. wc = (WCHAR)c;
  5668. }
  5669. #endif
  5670. /* A code point in UTF-16 is available in hs and wc */
  5671. #if FF_STRF_ENCODE == 1 /* Write a code point in UTF-16LE */
  5672. if (hs != 0) { /* Surrogate pair? */
  5673. st_word(&pb->buf[i], hs);
  5674. i += 2;
  5675. nc++;
  5676. }
  5677. st_word(&pb->buf[i], wc);
  5678. i += 2;
  5679. #elif FF_STRF_ENCODE == 2 /* Write a code point in UTF-16BE */
  5680. if (hs != 0) { /* Surrogate pair? */
  5681. pb->buf[i++] = (BYTE)(hs >> 8);
  5682. pb->buf[i++] = (BYTE)hs;
  5683. nc++;
  5684. }
  5685. pb->buf[i++] = (BYTE)(wc >> 8);
  5686. pb->buf[i++] = (BYTE)wc;
  5687. #elif FF_STRF_ENCODE == 3 /* Write a code point in UTF-8 */
  5688. if (hs != 0) { /* 4-byte sequence? */
  5689. nc += 3;
  5690. hs = (hs & 0x3FF) + 0x40;
  5691. pb->buf[i++] = (BYTE)(0xF0 | hs >> 8);
  5692. pb->buf[i++] = (BYTE)(0x80 | (hs >> 2 & 0x3F));
  5693. pb->buf[i++] = (BYTE)(0x80 | (hs & 3) << 4 | (wc >> 6 & 0x0F));
  5694. pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));
  5695. } else {
  5696. if (wc < 0x80) { /* Single byte? */
  5697. pb->buf[i++] = (BYTE)wc;
  5698. } else {
  5699. if (wc < 0x800) { /* 2-byte sequence? */
  5700. nc += 1;
  5701. pb->buf[i++] = (BYTE)(0xC0 | wc >> 6);
  5702. } else { /* 3-byte sequence */
  5703. nc += 2;
  5704. pb->buf[i++] = (BYTE)(0xE0 | wc >> 12);
  5705. pb->buf[i++] = (BYTE)(0x80 | (wc >> 6 & 0x3F));
  5706. }
  5707. pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));
  5708. }
  5709. }
  5710. #else /* Write a code point in ANSI/OEM */
  5711. if (hs != 0) return;
  5712. wc = ff_uni2oem(wc, CODEPAGE); /* UTF-16 ==> ANSI/OEM */
  5713. if (wc == 0) return;
  5714. if (wc >= 0x100) {
  5715. pb->buf[i++] = (BYTE)(wc >> 8); nc++;
  5716. }
  5717. pb->buf[i++] = (BYTE)wc;
  5718. #endif
  5719. #else /* ANSI/OEM input (without re-encoding) */
  5720. pb->buf[i++] = (BYTE)c;
  5721. #endif
  5722. if (i >= (int)(sizeof pb->buf) - 4) { /* Write buffered characters to the file */
  5723. f_write(pb->fp, pb->buf, (UINT)i, &n);
  5724. i = (n == (UINT)i) ? 0 : -1;
  5725. }
  5726. pb->idx = i;
  5727. pb->nchr = nc + 1;
  5728. }
  5729. /* Flush remaining characters in the buffer */
  5730. static int putc_flush (putbuff* pb)
  5731. {
  5732. UINT nw;
  5733. if ( pb->idx >= 0 /* Flush buffered characters to the file */
  5734. && f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK
  5735. && (UINT)pb->idx == nw) return pb->nchr;
  5736. return -1;
  5737. }
  5738. /* Initialize write buffer */
  5739. static void putc_init (putbuff* pb, FIL* fp)
  5740. {
  5741. memset(pb, 0, sizeof (putbuff));
  5742. pb->fp = fp;
  5743. }
  5744. int f_putc (
  5745. FATFS_TCHAR c, /* A character to be output */
  5746. FIL* fp /* Pointer to the file object */
  5747. )
  5748. {
  5749. putbuff pb;
  5750. putc_init(&pb, fp);
  5751. putc_bfd(&pb, c); /* Put the character */
  5752. return putc_flush(&pb);
  5753. }
  5754. /*-----------------------------------------------------------------------*/
  5755. /* Put a String to the File */
  5756. /*-----------------------------------------------------------------------*/
  5757. int f_puts (
  5758. const FATFS_TCHAR* str, /* Pointer to the string to be output */
  5759. FIL* fp /* Pointer to the file object */
  5760. )
  5761. {
  5762. putbuff pb;
  5763. putc_init(&pb, fp);
  5764. while (*str) putc_bfd(&pb, *str++); /* Put the string */
  5765. return putc_flush(&pb);
  5766. }
  5767. /*-----------------------------------------------------------------------*/
  5768. /* Put a Formatted String to the File (with sub-functions) */
  5769. /*-----------------------------------------------------------------------*/
  5770. #if FF_PRINT_FLOAT && FF_INTDEF == 2
  5771. #include <math.h>
  5772. static int ilog10 (double n) /* Calculate log10(n) in integer output */
  5773. {
  5774. int rv = 0;
  5775. while (n >= 10) { /* Decimate digit in right shift */
  5776. if (n >= 100000) {
  5777. n /= 100000; rv += 5;
  5778. } else {
  5779. n /= 10; rv++;
  5780. }
  5781. }
  5782. while (n < 1) { /* Decimate digit in left shift */
  5783. if (n < 0.00001) {
  5784. n *= 100000; rv -= 5;
  5785. } else {
  5786. n *= 10; rv--;
  5787. }
  5788. }
  5789. return rv;
  5790. }
  5791. static double i10x (int n) /* Calculate 10^n in integer input */
  5792. {
  5793. double rv = 1;
  5794. while (n > 0) { /* Left shift */
  5795. if (n >= 5) {
  5796. rv *= 100000; n -= 5;
  5797. } else {
  5798. rv *= 10; n--;
  5799. }
  5800. }
  5801. while (n < 0) { /* Right shift */
  5802. if (n <= -5) {
  5803. rv /= 100000; n += 5;
  5804. } else {
  5805. rv /= 10; n++;
  5806. }
  5807. }
  5808. return rv;
  5809. }
  5810. static void ftoa (
  5811. char* buf, /* Buffer to output the floating point string */
  5812. double val, /* Value to output */
  5813. int prec, /* Number of fractional digits */
  5814. FATFS_TCHAR fmt /* Notation */
  5815. )
  5816. {
  5817. int d;
  5818. int e = 0, m = 0;
  5819. char sign = 0;
  5820. double w;
  5821. const char *er = 0;
  5822. const char ds = FF_PRINT_FLOAT == 2 ? ',' : '.';
  5823. if (isnan(val)) { /* Not a number? */
  5824. er = "NaN";
  5825. } else {
  5826. if (prec < 0) prec = 6; /* Default precision? (6 fractional digits) */
  5827. if (val < 0) { /* Nagative? */
  5828. val = 0 - val; sign = '-';
  5829. } else {
  5830. sign = '+';
  5831. }
  5832. if (isinf(val)) { /* Infinite? */
  5833. er = "INF";
  5834. } else {
  5835. if (fmt == 'f') { /* Decimal notation? */
  5836. val += i10x(0 - prec) / 2; /* Round (nearest) */
  5837. m = ilog10(val);
  5838. if (m < 0) m = 0;
  5839. if (m + prec + 3 >= SZ_NUM_BUF) er = "OV"; /* Buffer overflow? */
  5840. } else { /* E notation */
  5841. if (val != 0) { /* Not a true zero? */
  5842. val += i10x(ilog10(val) - prec) / 2; /* Round (nearest) */
  5843. e = ilog10(val);
  5844. if (e > 99 || prec + 7 >= SZ_NUM_BUF) { /* Buffer overflow or E > +99? */
  5845. er = "OV";
  5846. } else {
  5847. if (e < -99) e = -99;
  5848. val /= i10x(e); /* Normalize */
  5849. }
  5850. }
  5851. }
  5852. }
  5853. if (!er) { /* Not error condition */
  5854. if (sign == '-') *buf++ = sign; /* Add a - if negative value */
  5855. do { /* Put decimal number */
  5856. if (m == -1) *buf++ = ds; /* Insert a decimal separator when get into fractional part */
  5857. w = i10x(m); /* Snip the highest digit d */
  5858. d = (int)(val / w); val -= d * w;
  5859. *buf++ = (char)('0' + d); /* Put the digit */
  5860. } while (--m >= -prec); /* Output all digits specified by prec */
  5861. if (fmt != 'f') { /* Put exponent if needed */
  5862. *buf++ = (char)fmt;
  5863. if (e < 0) {
  5864. e = 0 - e; *buf++ = '-';
  5865. } else {
  5866. *buf++ = '+';
  5867. }
  5868. *buf++ = (char)('0' + e / 10);
  5869. *buf++ = (char)('0' + e % 10);
  5870. }
  5871. }
  5872. }
  5873. if (er) { /* Error condition */
  5874. if (sign) *buf++ = sign; /* Add sign if needed */
  5875. do *buf++ = *er++; while (*er); /* Put error symbol */
  5876. }
  5877. *buf = 0; /* Term */
  5878. }
  5879. #endif /* FF_PRINT_FLOAT && FF_INTDEF == 2 */
  5880. int f_printf (
  5881. FIL* fp, /* Pointer to the file object */
  5882. const FATFS_TCHAR* fmt, /* Pointer to the format string */
  5883. ... /* Optional arguments... */
  5884. )
  5885. {
  5886. va_list arp;
  5887. putbuff pb;
  5888. UINT i, j, w, f, r;
  5889. int prec;
  5890. #if FF_PRINT_LLI && FF_INTDEF == 2
  5891. QWORD v;
  5892. #else
  5893. DWORD v;
  5894. #endif
  5895. FATFS_TCHAR tc, pad, *tp;
  5896. FATFS_TCHAR nul = 0;
  5897. char d, str[SZ_NUM_BUF];
  5898. putc_init(&pb, fp);
  5899. va_start(arp, fmt);
  5900. for (;;) {
  5901. tc = *fmt++;
  5902. if (tc == 0) break; /* End of format string */
  5903. if (tc != '%') { /* Not an escape character (pass-through) */
  5904. putc_bfd(&pb, tc);
  5905. continue;
  5906. }
  5907. f = w = 0; pad = ' '; prec = -1; /* Initialize parms */
  5908. tc = *fmt++;
  5909. if (tc == '0') { /* Flag: '0' padded */
  5910. pad = '0'; tc = *fmt++;
  5911. } else if (tc == '-') { /* Flag: Left aligned */
  5912. f = 2; tc = *fmt++;
  5913. }
  5914. if (tc == '*') { /* Minimum width from an argument */
  5915. w = va_arg(arp, int);
  5916. tc = *fmt++;
  5917. } else {
  5918. while (IsDigit(tc)) { /* Minimum width */
  5919. w = w * 10 + tc - '0';
  5920. tc = *fmt++;
  5921. }
  5922. }
  5923. if (tc == '.') { /* Precision */
  5924. tc = *fmt++;
  5925. if (tc == '*') { /* Precision from an argument */
  5926. prec = va_arg(arp, int);
  5927. tc = *fmt++;
  5928. } else {
  5929. prec = 0;
  5930. while (IsDigit(tc)) { /* Precision */
  5931. prec = prec * 10 + tc - '0';
  5932. tc = *fmt++;
  5933. }
  5934. }
  5935. }
  5936. if (tc == 'l') { /* Size: long int */
  5937. f |= 4; tc = *fmt++;
  5938. #if FF_PRINT_LLI && FF_INTDEF == 2
  5939. if (tc == 'l') { /* Size: long long int */
  5940. f |= 8; tc = *fmt++;
  5941. }
  5942. #endif
  5943. }
  5944. if (tc == 0) break; /* End of format string */
  5945. switch (tc) { /* Atgument type is... */
  5946. case 'b': /* Unsigned binary */
  5947. r = 2; break;
  5948. case 'o': /* Unsigned octal */
  5949. r = 8; break;
  5950. case 'd': /* Signed decimal */
  5951. case 'u': /* Unsigned decimal */
  5952. r = 10; break;
  5953. case 'x': /* Unsigned hexdecimal (lower case) */
  5954. case 'X': /* Unsigned hexdecimal (upper case) */
  5955. r = 16; break;
  5956. case 'c': /* Character */
  5957. putc_bfd(&pb, (FATFS_TCHAR)va_arg(arp, int));
  5958. continue;
  5959. case 's': /* String */
  5960. tp = va_arg(arp, FATFS_TCHAR*); /* Get a pointer argument */
  5961. if (!tp) tp = &nul; /* Null ptr generates a null string */
  5962. for (j = 0; tp[j]; j++) ; /* j = tcslen(tp) */
  5963. if (prec >= 0 && j > (UINT)prec) j = prec; /* Limited length of string body */
  5964. for ( ; !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */
  5965. while (*tp && prec--) putc_bfd(&pb, *tp++); /* Body */
  5966. while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */
  5967. continue;
  5968. #if FF_PRINT_FLOAT && FF_INTDEF == 2
  5969. case 'f': /* Floating point (decimal) */
  5970. case 'e': /* Floating point (e) */
  5971. case 'E': /* Floating point (E) */
  5972. ftoa(str, va_arg(arp, double), prec, tc); /* Make a flaoting point string */
  5973. for (j = strlen(str); !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */
  5974. for (i = 0; str[i]; putc_bfd(&pb, str[i++])) ; /* Body */
  5975. while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */
  5976. continue;
  5977. #endif
  5978. default: /* Unknown type (pass-through) */
  5979. putc_bfd(&pb, tc); continue;
  5980. }
  5981. /* Get an integer argument and put it in numeral */
  5982. #if FF_PRINT_LLI && FF_INTDEF == 2
  5983. if (f & 8) { /* long long argument? */
  5984. v = (QWORD)va_arg(arp, LONGLONG);
  5985. } else {
  5986. if (f & 4) { /* long argument? */
  5987. v = (tc == 'd') ? (QWORD)(LONGLONG)va_arg(arp, long) : (QWORD)va_arg(arp, unsigned long);
  5988. } else { /* int/short/char argument */
  5989. v = (tc == 'd') ? (QWORD)(LONGLONG)va_arg(arp, int) : (QWORD)va_arg(arp, unsigned int);
  5990. }
  5991. }
  5992. if (tc == 'd' && (v & 0x8000000000000000)) { /* Negative value? */
  5993. v = 0 - v; f |= 1;
  5994. }
  5995. #else
  5996. if (f & 4) { /* long argument? */
  5997. v = (DWORD)va_arg(arp, long);
  5998. } else { /* int/short/char argument */
  5999. v = (tc == 'd') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int);
  6000. }
  6001. if (tc == 'd' && (v & 0x80000000)) { /* Negative value? */
  6002. v = 0 - v; f |= 1;
  6003. }
  6004. #endif
  6005. i = 0;
  6006. do { /* Make an integer number string */
  6007. d = (char)(v % r); v /= r;
  6008. if (d > 9) d += (tc == 'x') ? 0x27 : 0x07;
  6009. str[i++] = d + '0';
  6010. } while (v && i < SZ_NUM_BUF);
  6011. if (f & 1) str[i++] = '-'; /* Sign */
  6012. /* Write it */
  6013. for (j = i; !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */
  6014. do putc_bfd(&pb, (FATFS_TCHAR)str[--i]); while (i); /* Body */
  6015. while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */
  6016. }
  6017. va_end(arp);
  6018. return putc_flush(&pb);
  6019. }
  6020. #endif /* !FF_FS_READONLY */
  6021. #endif /* FF_USE_STRFUNC */
  6022. #if FF_CODE_PAGE == 0
  6023. /*-----------------------------------------------------------------------*/
  6024. /* Set Active Codepage for the Path Name */
  6025. /*-----------------------------------------------------------------------*/
  6026. FRESULT f_setcp (
  6027. WORD cp /* Value to be set as active code page */
  6028. )
  6029. {
  6030. static const WORD validcp[22] = { 437, 720, 737, 771, 775, 850, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 869, 932, 936, 949, 950, 0};
  6031. static const BYTE* const tables[22] = {Ct437, Ct720, Ct737, Ct771, Ct775, Ct850, Ct852, Ct855, Ct857, Ct860, Ct861, Ct862, Ct863, Ct864, Ct865, Ct866, Ct869, Dc932, Dc936, Dc949, Dc950, 0};
  6032. UINT i;
  6033. for (i = 0; validcp[i] != 0 && validcp[i] != cp; i++) ; /* Find the code page */
  6034. if (validcp[i] != cp) return FR_INVALID_PARAMETER; /* Not found? */
  6035. CodePage = cp;
  6036. if (cp >= 900) { /* DBCS */
  6037. ExCvt = 0;
  6038. DbcTbl = tables[i];
  6039. } else { /* SBCS */
  6040. ExCvt = tables[i];
  6041. DbcTbl = 0;
  6042. }
  6043. return FR_OK;
  6044. }
  6045. #endif /* FF_CODE_PAGE == 0 */