ff.c 202 KB

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