e50014be812de40ad39da7421898c4722fdf737c
[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 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 [DISK_FILE_ENTRY_VolumeID] =
82 {
83 .MSDOS_Directory =
84 {
85 .Name = "LUFA BOOT ",
86 .Attributes = FAT_FLAG_VOLUME_NAME,
87 .Reserved = {0},
88 .CreationTime = 0,
89 .CreationDate = 0,
90 .StartingCluster = 0,
91 .Reserved2 = 0,
92 }
93 },
94
95 /* VFAT Long File Name entry for the virtual firmware file; required to
96 * prevent corruption from systems that are unable to detect the device
97 * as being a legacy MSDOS style FAT12 volume. */
98 [DISK_FILE_ENTRY_FirmwareLFN] =
99 {
100 .VFAT_LongFileName =
101 {
102 .Ordinal = FAT_ORDINAL_LAST_ENTRY | 1,
103 .Attribute = FAT_FLAG_LONG_FILE_NAME,
104 .Reserved1 = 0,
105 .Reserved2 = 0,
106
107 .Checksum = 0x57,
108
109 .Unicode1 = 'F',
110 .Unicode2 = 'I',
111 .Unicode3 = 'R',
112 .Unicode4 = 'M',
113 .Unicode5 = 'W',
114 .Unicode6 = 'A',
115 .Unicode7 = 'R',
116 .Unicode8 = 'E',
117 .Unicode9 = '.',
118 .Unicode10 = 'B',
119 .Unicode11 = 'I',
120 .Unicode12 = 'N',
121 .Unicode13 = 0,
122 }
123 },
124
125 /* MSDOS file entry for the virtual Firmware image. */
126 [DISK_FILE_ENTRY_FirmwareMSDOS] =
127 {
128 .MSDOS_File =
129 {
130 .Filename = "FIRMWARE",
131 .Extension = "BIN",
132 .Attributes = 0,
133 .Reserved = {0},
134 .CreationTime = FAT_TIME(1, 1, 0),
135 .CreationDate = FAT_DATE(14, 2, 1989),
136 .StartingCluster = 2,
137 .FileSizeBytes = FIRMWARE_FILE_SIZE_BYTES,
138 }
139 },
140 };
141
142 /** Starting block of the virtual firmware file image on disk. On Windows, files
143 * are (usually?) replaced using the original file's physical sectors. On Linux
144 * file replacements are performed with an offset.
145 */
146 uint16_t FileStartBlock = DISK_BLOCK_DataStartBlock;
147
148
149 /** Updates a FAT12 cluster entry in the FAT file table with the specified next
150 * chain index. If the cluster is the last in the file chain, the magic value
151 * 0xFFF is used.
152 *
153 * \note FAT data cluster indexes are offset by 2, so that cluster 2 is the
154 * first file data cluster on the disk. See the FAT specification.
155 *
156 * \param[out] FATTable Pointer to the FAT12 allocation table
157 * \param[in] Index Index of the cluster entry to update
158 * \param[in] ChainEntry Next cluster index in the file chain
159 */
160 static void UpdateFAT12ClusterEntry(uint8_t* const FATTable,
161 const uint16_t Index,
162 const uint16_t ChainEntry)
163 {
164 /* Calculate the starting offset of the cluster entry in the FAT12 table */
165 uint8_t FATOffset = (Index + (Index >> 1));
166 bool UpperNibble = ((Index & 1) != 0);
167
168 /* Check if the start of the entry is at an upper nibble of the byte, fill
169 * out FAT12 entry as required */
170 if (UpperNibble)
171 {
172 FATTable[FATOffset] = (FATTable[FATOffset] & 0x0F) | ((ChainEntry & 0x0F) << 4);
173 FATTable[FATOffset + 1] = (ChainEntry >> 4);
174 }
175 else
176 {
177 FATTable[FATOffset] = ChainEntry;
178 FATTable[FATOffset + 1] = (FATTable[FATOffset] & 0xF0) | (ChainEntry >> 8);
179 }
180 }
181
182 /** Reads or writes a block of data from/to the physical device FLASH using a
183 * block buffer stored in RAM, if the requested block is within the virtual
184 * firmware file's sector ranges in the emulated FAT file system.
185 *
186 * \param[in] BlockNumber Physical disk block to read from
187 * \param[in,out] BlockBuffer Pointer to the start of the block buffer in RAM
188 * \param[in] Read If \c true, the requested block is read, if
189 * \c false, the requested block is written
190 */
191 static void ReadWriteFirmwareFileBlock(const uint16_t BlockNumber,
192 uint8_t* BlockBuffer,
193 const bool Read)
194 {
195 /* Range check the write request - abort if requested block is not within the
196 * virtual firmware file sector range */
197 if (!((BlockNumber >= FileStartBlock) && (BlockNumber < (FileStartBlock + FILE_SECTORS(FIRMWARE_FILE_SIZE_BYTES)))))
198 return;
199
200 #if (FLASHEND > 0xFFFF)
201 uint32_t FlashAddress = (uint32_t)(BlockNumber - FileStartBlock) * SECTOR_SIZE_BYTES;
202 #else
203 uint16_t FlashAddress = (uint16_t)(BlockNumber - FileStartBlock) * SECTOR_SIZE_BYTES;
204 #endif
205
206 if (Read)
207 {
208 /* Read out the mapped block of data from the device's FLASH */
209 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i++)
210 {
211 #if (FLASHEND > 0xFFFF)
212 BlockBuffer[i] = pgm_read_byte_far(FlashAddress++);
213 #else
214 BlockBuffer[i] = pgm_read_byte(FlashAddress++);
215 #endif
216 }
217 }
218 else
219 {
220 /* Write out the mapped block of data to the device's FLASH */
221 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i += 2)
222 {
223 if ((FlashAddress % SPM_PAGESIZE) == 0)
224 {
225 /* Erase the given FLASH page, ready to be programmed */
226 BootloaderAPI_ErasePage(FlashAddress);
227 }
228
229 /* Write the next data word to the FLASH page */
230 BootloaderAPI_FillWord(FlashAddress, (BlockBuffer[i + 1] << 8) | BlockBuffer[i]);
231 FlashAddress += 2;
232
233 if ((FlashAddress % SPM_PAGESIZE) == 0)
234 {
235 /* Write the filled FLASH page to memory */
236 BootloaderAPI_WritePage(FlashAddress - SPM_PAGESIZE);
237 }
238 }
239 }
240 }
241
242 /** Writes a block of data to the virtual FAT filesystem, from the USB Mass
243 * Storage interface.
244 *
245 * \param[in] BlockNumber Index of the block to write.
246 */
247 void VirtualFAT_WriteBlock(const uint16_t BlockNumber)
248 {
249 uint8_t BlockBuffer[SECTOR_SIZE_BYTES];
250
251 /* Buffer the entire block to be written from the host */
252 Endpoint_Read_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
253 Endpoint_ClearOUT();
254
255 if (BlockNumber == DISK_BLOCK_RootFilesBlock)
256 {
257 /* Copy over the updated directory entries */
258 memcpy(FirmwareFileEntries, BlockBuffer, sizeof(FirmwareFileEntries));
259
260 /* Save the new firmware file block offset so the written and read file
261 * contents can be correctly mapped to the device's FLASH pages */
262 FileStartBlock = DISK_BLOCK_DataStartBlock +
263 (FirmwareFileEntries[DISK_FILE_ENTRY_FirmwareMSDOS].MSDOS_File.StartingCluster - 2) * SECTOR_PER_CLUSTER;
264 }
265 else
266 {
267 ReadWriteFirmwareFileBlock(BlockNumber, BlockBuffer, false);
268 }
269 }
270
271 /** Reads a block of data from the virtual FAT filesystem, and sends it to the
272 * host via the USB Mass Storage interface.
273 *
274 * \param[in] BlockNumber Index of the block to read.
275 */
276 void VirtualFAT_ReadBlock(const uint16_t BlockNumber)
277 {
278 uint8_t BlockBuffer[SECTOR_SIZE_BYTES];
279 memset(BlockBuffer, 0x00, sizeof(BlockBuffer));
280
281 switch (BlockNumber)
282 {
283 case DISK_BLOCK_BootBlock:
284 memcpy(BlockBuffer, &BootBlock, sizeof(FATBootBlock_t));
285
286 /* Add the magic signature to the end of the block */
287 BlockBuffer[SECTOR_SIZE_BYTES - 2] = 0x55;
288 BlockBuffer[SECTOR_SIZE_BYTES - 1] = 0xAA;
289
290 break;
291
292 case DISK_BLOCK_FATBlock1:
293 case DISK_BLOCK_FATBlock2:
294 /* Cluster 0: Media type/Reserved */
295 UpdateFAT12ClusterEntry(BlockBuffer, 0, 0xF00 | BootBlock.MediaDescriptor);
296
297 /* Cluster 1: Reserved */
298 UpdateFAT12ClusterEntry(BlockBuffer, 1, 0xFFF);
299
300 /* Cluster 2 onwards: Cluster chain of FIRMWARE.BIN */
301 for (uint16_t i = 0; i <= FILE_CLUSTERS(FIRMWARE_FILE_SIZE_BYTES); i++)
302 {
303 uint16_t CurrentCluster = FirmwareFileEntries[DISK_FILE_ENTRY_FirmwareMSDOS].MSDOS_File.StartingCluster + i;
304 uint16_t NextCluster = CurrentCluster + 1;
305
306 /* Mark last cluster as end of file */
307 if (i == FILE_CLUSTERS(FIRMWARE_FILE_SIZE_BYTES))
308 NextCluster = 0xFFF;
309
310 UpdateFAT12ClusterEntry(BlockBuffer, CurrentCluster, NextCluster);
311 }
312
313 break;
314
315 case DISK_BLOCK_RootFilesBlock:
316 memcpy(BlockBuffer, FirmwareFileEntries, sizeof(FirmwareFileEntries));
317
318 break;
319
320 default: /* Blocks 4 onwards: Data allocation section */
321 ReadWriteFirmwareFileBlock(BlockNumber, BlockBuffer, true);
322
323 break;
324 }
325
326 /* Write the entire read block Buffer to the host */
327 Endpoint_Write_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
328 Endpoint_ClearIN();
329 }