ff.c 242 KB

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