ff.c 241 KB

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