ff.c 247 KB

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