ff.c 244 KB

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