25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

6556 satır
219 KiB

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