ff.c 222 KB

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