Clean up the Mass Storage bootloader virtual FAT directory entry definitions.
[pub/USBasp.git] / Bootloaders / MassStorage / Lib / VirtualFAT.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2013.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2013 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaims all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 *
33 * Virtualized FAT12 filesystem implementation, to perform self-programming
34 * in response to read and write requests to the virtual filesystem by the
35 * host PC.
36 */
37
38 #define INCLUDE_FROM_VIRTUAL_FAT_C
39 #include "VirtualFAT.h"
40
41 /** FAT filesystem boot sector block, must be the first sector on the physical
42 * disk so that the host can identify the presence of a FAT filesystem. This
43 * block is truncated; normally a large bootstrap section is located near the
44 * end of the block for booting purposes however as this is not meant to be a
45 * bootable disk it is omitted for space reasons.
46 *
47 * \note When returning the boot block to the host, the magic signature 0xAA55
48 * must be added to the very end of the block to identify it as a boot
49 * block.
50 */
51 static const FATBootBlock_t BootBlock =
52 {
53 .Bootstrap = {0xEB, 0x3C, 0x90},
54 .Description = "mkdosfs",
55 .SectorSize = SECTOR_SIZE_BYTES,
56 .SectorsPerCluster = SECTOR_PER_CLUSTER,
57 .ReservedSectors = 1,
58 .FATCopies = 2,
59 .RootDirectoryEntries = (SECTOR_SIZE_BYTES / sizeof(FATDirectoryEntry_t)),
60 .TotalSectors16 = LUN_MEDIA_BLOCKS,
61 .MediaDescriptor = 0xF8,
62 .SectorsPerFAT = 1,
63 .SectorsPerTrack = (LUN_MEDIA_BLOCKS % 64),
64 .Heads = (LUN_MEDIA_BLOCKS / 64),
65 .HiddenSectors = 0,
66 .TotalSectors32 = 0,
67 .PhysicalDriveNum = 0,
68 .ExtendedBootRecordSig = 0x29,
69 .VolumeSerialNumber = 0x12345678,
70 .VolumeLabel = "LUFA BOOT ",
71 .FilesystemIdentifier = "FAT12 ",
72 };
73
74 /** FAT 8.3 style directory entry, for the virtual FLASH contents file. */
75 static FATDirectoryEntry_t FirmwareFileEntries[] =
76 {
77 /* Root volume label entry; disk label is contained in the Filename and
78 * Extension fields (concatenated) with a special attribute flag - other
79 * fields are ignored. Should be the same as the label in the boot block.
80 */
81 {
82 .MSDOS_Directory =
83 {
84 .Name = "LUFA BOOT ",
85 .Attributes = FAT_FLAG_VOLUME_NAME,
86 .Reserved = {0},
87 .CreationTime = 0,
88 .CreationDate = 0,
89 .StartingCluster = 0,
90 .Reserved2 = 0,
91 }
92 },
93
94 /* VFAT Long File Name entry for the virtual firmware file; required to
95 * prevent corruption of systems that are unable to detect the device
96 * as being a legacy MSDOS style FAT12 volume to prevent corruption. */
97 {
98 .VFAT_LongFileName =
99 {
100 .Ordinal = FAT_ORDINAL_LAST_ENTRY | 1,
101 .Attribute = FAT_FLAG_LONG_FILE_NAME,
102 .Reserved1 = 0,
103 .Reserved2 = 0,
104
105 .Checksum = 0x57,
106
107 .Unicode1 = 'F',
108 .Unicode2 = 'I',
109 .Unicode3 = 'R',
110 .Unicode4 = 'M',
111 .Unicode5 = 'W',
112 .Unicode6 = 'A',
113 .Unicode7 = 'R',
114 .Unicode8 = 'E',
115 .Unicode9 = '.',
116 .Unicode10 = 'B',
117 .Unicode11 = 'I',
118 .Unicode12 = 'N',
119 .Unicode13 = 0,
120 }
121 },
122
123 /* MSDOS file entry for the virtual Firmware image. */
124 {
125 .MSDOS_File =
126 {
127 .Filename = "FIRMWARE",
128 .Extension = "BIN",
129 .Attributes = 0,
130 .Reserved = {0},
131 .CreationTime = FAT_TIME(1, 1, 0),
132 .CreationDate = FAT_DATE(14, 2, 1989),
133 .StartingCluster = 2,
134 .FileSizeBytes = FIRMWARE_FILE_SIZE_BYTES,
135 }
136 },
137 };
138
139
140 /** Updates a FAT12 cluster entry in the FAT file table with the specified next
141 * chain index. If the cluster is the last in the file chain, the magic value
142 * 0xFFF is used.
143 *
144 * \note FAT data cluster indexes are offset by 2, so that cluster 2 is the
145 * first file data cluster on the disk. See the FAT specification.
146 *
147 * \param[out] FATTable Pointer to the FAT12 allocation table
148 * \param[in] Index Index of the cluster entry to update
149 * \param[in] ChainEntry Next cluster index in the file chain
150 */
151 static void UpdateFAT12ClusterEntry(uint8_t* const FATTable,
152 const uint16_t Index,
153 const uint16_t ChainEntry)
154 {
155 /* Calculate the starting offset of the cluster entry in the FAT12 table */
156 uint8_t FATOffset = (Index + (Index >> 1));
157 bool UpperNibble = ((Index & 1) != 0);
158
159 /* Check if the start of the entry is at an upper nibble of the byte, fill
160 * out FAT12 entry as required */
161 if (UpperNibble)
162 {
163 FATTable[FATOffset] = (FATTable[FATOffset] & 0x0F) | ((ChainEntry & 0x0F) << 4);
164 FATTable[FATOffset + 1] = (ChainEntry >> 4);
165 }
166 else
167 {
168 FATTable[FATOffset] = ChainEntry;
169 FATTable[FATOffset + 1] = (FATTable[FATOffset] & 0xF0) | (ChainEntry >> 8);
170 }
171 }
172
173 /** Writes a block of data to the virtual FAT filesystem, from the USB Mass
174 * Storage interface.
175 *
176 * \param[in] BlockNumber Index of the block to write.
177 */
178 static void WriteVirtualBlock(const uint16_t BlockNumber)
179 {
180 uint8_t BlockBuffer[SECTOR_SIZE_BYTES];
181
182 /* Buffer the entire block to be written from the host */
183 Endpoint_Read_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
184 Endpoint_ClearOUT();
185
186 if ((BlockNumber >= 4) && (BlockNumber < (4 + FILE_SECTORS(FIRMWARE_FILE_SIZE_BYTES))))
187 {
188 #if (FLASHEND > 0xFFFF)
189 uint32_t WriteFlashAddress = (uint32_t)(BlockNumber - 4) * SECTOR_SIZE_BYTES;
190 #else
191 uint16_t WriteFlashAddress = (uint16_t)(BlockNumber - 4) * SECTOR_SIZE_BYTES;
192 #endif
193
194 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i += 2)
195 {
196 if ((WriteFlashAddress % SPM_PAGESIZE) == 0)
197 {
198 /* Erase the given FLASH page, ready to be programmed */
199 BootloaderAPI_ErasePage(WriteFlashAddress);
200 }
201
202 /* Write the next data word to the FLASH page */
203 BootloaderAPI_FillWord(WriteFlashAddress, (BlockBuffer[i + 1] << 8) | BlockBuffer[i]);
204 WriteFlashAddress += 2;
205
206 if ((WriteFlashAddress % SPM_PAGESIZE) == 0)
207 {
208 /* Write the filled FLASH page to memory */
209 BootloaderAPI_WritePage(WriteFlashAddress - SPM_PAGESIZE);
210 }
211 }
212 }
213 }
214
215 /** Reads a block of data from the virtual FAT filesystem, and sends it to the
216 * host via the USB Mass Storage interface.
217 *
218 * \param[in] BlockNumber Index of the block to read.
219 */
220 static void ReadVirtualBlock(const uint16_t BlockNumber)
221 {
222 uint8_t BlockBuffer[SECTOR_SIZE_BYTES];
223 memset(BlockBuffer, 0x00, sizeof(BlockBuffer));
224
225 switch (BlockNumber)
226 {
227 case 0: /* Block 0: Boot block sector */
228 memcpy(BlockBuffer, &BootBlock, sizeof(FATBootBlock_t));
229
230 /* Add the magic signature to the end of the block */
231 BlockBuffer[SECTOR_SIZE_BYTES - 2] = 0x55;
232 BlockBuffer[SECTOR_SIZE_BYTES - 1] = 0xAA;
233 break;
234
235 case 1: /* Block 1: First FAT12 cluster chain copy */
236 case 2: /* Block 2: Second FAT12 cluster chain copy */
237 /* Cluster 0: Media type/Reserved */
238 UpdateFAT12ClusterEntry(BlockBuffer, 0, 0xF00 | BootBlock.MediaDescriptor);
239
240 /* Cluster 1: Reserved */
241 UpdateFAT12ClusterEntry(BlockBuffer, 1, 0xFFF);
242
243 /* Cluster 2 onwards: Cluster chain of FIRMWARE.BIN */
244 for (uint16_t i = 0; i < FILE_CLUSTERS(FIRMWARE_FILE_SIZE_BYTES); i++)
245 UpdateFAT12ClusterEntry(BlockBuffer, i+2, i+3);
246
247 /* Mark last cluster as end of file */
248 UpdateFAT12ClusterEntry(BlockBuffer, FILE_CLUSTERS(FIRMWARE_FILE_SIZE_BYTES) + 1, 0xFFF);
249 break;
250
251 case 3: /* Block 3: Root file entries */
252 memcpy(BlockBuffer, FirmwareFileEntries, sizeof(FirmwareFileEntries));
253 break;
254
255 default: /* Blocks 4 onwards: Data allocation section */
256 if ((BlockNumber >= 4) && (BlockNumber < (4 + FILE_SECTORS(FIRMWARE_FILE_SIZE_BYTES))))
257 {
258 #if (FLASHEND > 0xFFFF)
259 uint32_t ReadFlashAddress = (uint32_t)(BlockNumber - 4) * SECTOR_SIZE_BYTES;
260
261 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i++)
262 BlockBuffer[i] = pgm_read_byte_far(ReadFlashAddress++);
263 #else
264 uint16_t ReadFlashAddress = (uint16_t)(BlockNumber - 4) * SECTOR_SIZE_BYTES;
265
266 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i++)
267 BlockBuffer[i] = pgm_read_byte(ReadFlashAddress++);
268 #endif
269 }
270
271 break;
272 }
273
274 /* Write the entire read block Buffer to the host */
275 Endpoint_Write_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
276 Endpoint_ClearIN();
277 }
278
279 /** Writes a number of blocks to the virtual FAT file system, from the host
280 * PC via the USB Mass Storage interface.
281 *
282 * \param[in] BlockAddress Data block starting address for the write sequence
283 * \param[in] TotalBlocks Number of blocks of data to write
284 */
285 void VirtualFAT_WriteBlocks(const uint16_t BlockAddress,
286 uint16_t TotalBlocks)
287 {
288 uint16_t CurrentBlock = (uint16_t)BlockAddress;
289
290 /* Emulated FAT is performed per-block, pass each requested block index
291 * to the emulated FAT block write function */
292 while (TotalBlocks--)
293 WriteVirtualBlock(CurrentBlock++);
294 }
295
296 /** Reads a number of blocks from the virtual FAT file system, and sends them
297 * to the host PC via the USB Mass Storage interface.
298 *
299 * \param[in] BlockAddress Data block starting address for the read sequence
300 * \param[in] TotalBlocks Number of blocks of data to read
301 */
302 void VirtualFAT_ReadBlocks(const uint16_t BlockAddress,
303 uint16_t TotalBlocks)
304 {
305 uint16_t CurrentBlock = (uint16_t)BlockAddress;
306
307 /* Emulated FAT is performed per-block, pass each requested block index
308 * to the emulated FAT block read function */
309 while (TotalBlocks--)
310 ReadVirtualBlock(CurrentBlock++);
311 }
312