ff.c 208 KB

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