hv_drv_UsbFatfs.c 297 KB

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