fd1761839a5bc749446dc06bd52b7233fb1cb19b
[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 [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_FLASH_LFN] =
99 {
100 .VFAT_LongFileName =
101 {
102 .Ordinal = 1 | FAT_ORDINAL_LAST_ENTRY,
103 .Attribute = FAT_FLAG_LONG_FILE_NAME,
104 .Reserved1 = 0,
105 .Reserved2 = 0,
106
107 .Checksum = FAT_CHECKSUM('F','L','A','S','H',' ',' ',' ','B','I','N'),
108
109 .Unicode1 = 'F',
110 .Unicode2 = 'L',
111 .Unicode3 = 'A',
112 .Unicode4 = 'S',
113 .Unicode5 = 'H',
114 .Unicode6 = '.',
115 .Unicode7 = 'B',
116 .Unicode8 = 'I',
117 .Unicode9 = 'N',
118 .Unicode10 = 0,
119 .Unicode11 = 0,
120 .Unicode12 = 0,
121 .Unicode13 = 0,
122 }
123 },
124
125 /* MSDOS file entry for the virtual Firmware image. */
126 [DISK_FILE_ENTRY_FLASH_MSDOS] =
127 {
128 .MSDOS_File =
129 {
130 .Filename = "FLASH ",
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 = FLASH_FILE_SIZE_BYTES,
138 }
139 },
140
141 [DISK_FILE_ENTRY_EEPROM_LFN] =
142 {
143 .VFAT_LongFileName =
144 {
145 .Ordinal = 1 | FAT_ORDINAL_LAST_ENTRY,
146 .Attribute = FAT_FLAG_LONG_FILE_NAME,
147 .Reserved1 = 0,
148 .Reserved2 = 0,
149
150 .Checksum = FAT_CHECKSUM('E','E','P','R','O','M',' ',' ','B','I','N'),
151
152 .Unicode1 = 'E',
153 .Unicode2 = 'E',
154 .Unicode3 = 'P',
155 .Unicode4 = 'R',
156 .Unicode5 = 'O',
157 .Unicode6 = 'M',
158 .Unicode7 = '.',
159 .Unicode8 = 'B',
160 .Unicode9 = 'I',
161 .Unicode10 = 'N',
162 .Unicode11 = 0,
163 .Unicode12 = 0,
164 .Unicode13 = 0,
165 }
166 },
167
168 [DISK_FILE_ENTRY_EEPROM_MSDOS] =
169 {
170 .MSDOS_File =
171 {
172 .Filename = "EEPROM ",
173 .Extension = "BIN",
174 .Attributes = 0,
175 .Reserved = {0},
176 .CreationTime = FAT_TIME(1, 1, 0),
177 .CreationDate = FAT_DATE(14, 2, 1989),
178 .StartingCluster = 2 + FILE_CLUSTERS(FLASH_FILE_SIZE_BYTES),
179 .FileSizeBytes = EEPROM_FILE_SIZE_BYTES,
180 }
181 },
182 };
183
184 /** Starting cluster of the virtual FLASH.BIN file on disk, tracked so that the
185 * offset from the start of the data sector can be determined. On Windows
186 * systems files are usually replaced using the original file's disk clusters,
187 * while Linux appears to overwrite with an offset which must be compensated for.
188 */
189 static uint16_t* FLASHFileStartCluster = &FirmwareFileEntries[DISK_FILE_ENTRY_FLASH_MSDOS].MSDOS_File.StartingCluster;
190
191 /** Starting cluster of the virtual EEPROM.BIN file on disk, tracked so that the
192 * offset from the start of the data sector can be determined. On Windows
193 * systems files are usually replaced using the original file's disk clusters,
194 * while Linux appears to overwrite with an offset which must be compensated for.
195 */
196 static uint16_t* EEPROMFileStartCluster = &FirmwareFileEntries[DISK_FILE_ENTRY_EEPROM_MSDOS].MSDOS_File.StartingCluster;
197
198
199 /** Updates a FAT12 cluster entry in the FAT file table with the specified next
200 * chain index. If the cluster is the last in the file chain, the magic value
201 * \c 0xFFF should be used.
202 *
203 * \note FAT data cluster indexes are offset by 2, so that cluster 2 is the
204 * first file data cluster on the disk. See the FAT specification.
205 *
206 * \param[out] FATTable Pointer to the FAT12 allocation table
207 * \param[in] Index Index of the cluster entry to update
208 * \param[in] ChainEntry Next cluster index in the file chain
209 */
210 static void UpdateFAT12ClusterEntry(uint8_t* const FATTable,
211 const uint16_t Index,
212 const uint16_t ChainEntry)
213 {
214 /* Calculate the starting offset of the cluster entry in the FAT12 table */
215 uint8_t FATOffset = (Index + (Index >> 1));
216 bool UpperNibble = ((Index & 1) != 0);
217
218 /* Check if the start of the entry is at an upper nibble of the byte, fill
219 * out FAT12 entry as required */
220 if (UpperNibble)
221 {
222 FATTable[FATOffset] = (FATTable[FATOffset] & 0x0F) | ((ChainEntry & 0x0F) << 4);
223 FATTable[FATOffset + 1] = (ChainEntry >> 4);
224 }
225 else
226 {
227 FATTable[FATOffset] = ChainEntry;
228 FATTable[FATOffset + 1] = (FATTable[FATOffset] & 0xF0) | (ChainEntry >> 8);
229 }
230 }
231
232 /** Updates a FAT12 cluster chain in the FAT file table with a linear chain of
233 * the specified length.
234 *
235 * \note FAT data cluster indexes are offset by 2, so that cluster 2 is the
236 * first file data cluster on the disk. See the FAT specification.
237 *
238 * \param[out] FATTable Pointer to the FAT12 allocation table
239 * \param[in] Index Index of the start of the cluster chain to update
240 * \param[in] ChainLength Length of the chain to write, in clusters
241 */
242 static void UpdateFAT12ClusterChain(uint8_t* const FATTable,
243 const uint16_t Index,
244 const uint16_t ChainLength)
245 {
246 for (uint16_t i = 0; i < ChainLength; i++)
247 {
248 uint16_t CurrentCluster = Index + i;
249 uint16_t NextCluster = CurrentCluster + 1;
250
251 /* Mark last cluster as end of file */
252 if (i == (ChainLength - 1))
253 NextCluster = 0xFFF;
254
255 UpdateFAT12ClusterEntry(FATTable, CurrentCluster, NextCluster);
256 }
257 }
258
259 /** Reads or writes a block of data from/to the physical device FLASH using a
260 * block buffer stored in RAM, if the requested block is within the virtual
261 * firmware file's sector ranges in the emulated FAT file system.
262 *
263 * \param[in] BlockNumber Physical disk block to read from/write to
264 * \param[in,out] BlockBuffer Pointer to the start of the block buffer in RAM
265 * \param[in] Read If \c true, the requested block is read, if
266 * \c false, the requested block is written
267 */
268 static void ReadWriteFLASHFileBlock(const uint16_t BlockNumber,
269 uint8_t* BlockBuffer,
270 const bool Read)
271 {
272 uint16_t FileStartBlock = DISK_BLOCK_DataStartBlock + (*FLASHFileStartCluster - 2) * SECTOR_PER_CLUSTER;
273 uint16_t FileEndBlock = FileStartBlock + (FILE_SECTORS(FLASH_FILE_SIZE_BYTES) - 1);
274
275 /* Range check the write request - abort if requested block is not within the
276 * virtual firmware file sector range */
277 if (!((BlockNumber >= FileStartBlock) && (BlockNumber <= FileEndBlock)))
278 return;
279
280 #if (FLASHEND > 0xFFFF)
281 uint32_t FlashAddress = (uint32_t)(BlockNumber - FileStartBlock) * SECTOR_SIZE_BYTES;
282 #else
283 uint16_t FlashAddress = (uint16_t)(BlockNumber - FileStartBlock) * SECTOR_SIZE_BYTES;
284 #endif
285
286 if (Read)
287 {
288 /* Read out the mapped block of data from the device's FLASH */
289 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i++)
290 {
291 #if (FLASHEND > 0xFFFF)
292 BlockBuffer[i] = pgm_read_byte_far(FlashAddress++);
293 #else
294 BlockBuffer[i] = pgm_read_byte(FlashAddress++);
295 #endif
296 }
297 }
298 else
299 {
300 /* Write out the mapped block of data to the device's FLASH */
301 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i += 2)
302 {
303 if ((FlashAddress % SPM_PAGESIZE) == 0)
304 {
305 /* Erase the given FLASH page, ready to be programmed */
306 BootloaderAPI_ErasePage(FlashAddress);
307 }
308
309 /* Write the next data word to the FLASH page */
310 BootloaderAPI_FillWord(FlashAddress, (BlockBuffer[i + 1] << 8) | BlockBuffer[i]);
311 FlashAddress += 2;
312
313 if ((FlashAddress % SPM_PAGESIZE) == 0)
314 {
315 /* Write the filled FLASH page to memory */
316 BootloaderAPI_WritePage(FlashAddress - SPM_PAGESIZE);
317 }
318 }
319 }
320 }
321
322 /** Reads or writes a block of data from/to the physical device EEPROM using a
323 * block buffer stored in RAM, if the requested block is within the virtual
324 * firmware file's sector ranges in the emulated FAT file system.
325 *
326 * \param[in] BlockNumber Physical disk block to read from/write to
327 * \param[in,out] BlockBuffer Pointer to the start of the block buffer in RAM
328 * \param[in] Read If \c true, the requested block is read, if
329 * \c false, the requested block is written
330 */
331 static void ReadWriteEEPROMFileBlock(const uint16_t BlockNumber,
332 uint8_t* BlockBuffer,
333 const bool Read)
334 {
335 uint16_t FileStartBlock = DISK_BLOCK_DataStartBlock + (*EEPROMFileStartCluster - 2) * SECTOR_PER_CLUSTER;
336 uint16_t FileEndBlock = FileStartBlock + (FILE_SECTORS(EEPROM_FILE_SIZE_BYTES) - 1);
337
338 /* Range check the write request - abort if requested block is not within the
339 * virtual firmware file sector range */
340 if (!((BlockNumber >= FileStartBlock) && (BlockNumber <= FileEndBlock)))
341 return;
342
343 uint16_t EEPROMAddress = (uint16_t)(BlockNumber - FileStartBlock) * SECTOR_SIZE_BYTES;
344
345 if (Read)
346 {
347 /* Read out the mapped block of data from the device's EEPROM */
348 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i++)
349 BlockBuffer[i] = eeprom_read_byte((void*)EEPROMAddress++);
350 }
351 else
352 {
353 /* Write out the mapped block of data to the device's EEPROM */
354 for (uint16_t i = 0; i < SECTOR_SIZE_BYTES; i++)
355 eeprom_update_byte((void*)EEPROMAddress++, BlockBuffer[i]);
356 }
357 }
358
359 /** Writes a block of data to the virtual FAT filesystem, from the USB Mass
360 * Storage interface.
361 *
362 * \param[in] BlockNumber Index of the block to write.
363 */
364 void VirtualFAT_WriteBlock(const uint16_t BlockNumber)
365 {
366 uint8_t BlockBuffer[SECTOR_SIZE_BYTES];
367
368 /* Buffer the entire block to be written from the host */
369 Endpoint_Read_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
370 Endpoint_ClearOUT();
371
372 switch (BlockNumber)
373 {
374 case DISK_BLOCK_BootBlock:
375 case DISK_BLOCK_FATBlock1:
376 case DISK_BLOCK_FATBlock2:
377 /* Ignore writes to the boot and FAT blocks */
378
379 break;
380
381 case DISK_BLOCK_RootFilesBlock:
382 /* Copy over the updated directory entries */
383 memcpy(FirmwareFileEntries, BlockBuffer, sizeof(FirmwareFileEntries));
384
385 break;
386
387 default:
388 ReadWriteFLASHFileBlock(BlockNumber, BlockBuffer, false);
389 ReadWriteEEPROMFileBlock(BlockNumber, BlockBuffer, false);
390
391 break;
392 }
393 }
394
395 /** Reads a block of data from the virtual FAT filesystem, and sends it to the
396 * host via the USB Mass Storage interface.
397 *
398 * \param[in] BlockNumber Index of the block to read.
399 */
400 void VirtualFAT_ReadBlock(const uint16_t BlockNumber)
401 {
402 uint8_t BlockBuffer[SECTOR_SIZE_BYTES];
403 memset(BlockBuffer, 0x00, sizeof(BlockBuffer));
404
405 switch (BlockNumber)
406 {
407 case DISK_BLOCK_BootBlock:
408 memcpy(BlockBuffer, &BootBlock, sizeof(FATBootBlock_t));
409
410 /* Add the magic signature to the end of the block */
411 BlockBuffer[SECTOR_SIZE_BYTES - 2] = 0x55;
412 BlockBuffer[SECTOR_SIZE_BYTES - 1] = 0xAA;
413
414 break;
415
416 case DISK_BLOCK_FATBlock1:
417 case DISK_BLOCK_FATBlock2:
418 /* Cluster 0: Media type/Reserved */
419 UpdateFAT12ClusterEntry(BlockBuffer, 0, 0xF00 | BootBlock.MediaDescriptor);
420
421 /* Cluster 1: Reserved */
422 UpdateFAT12ClusterEntry(BlockBuffer, 1, 0xFFF);
423
424 /* Cluster 2 onwards: Cluster chain of FLASH.BIN */
425 UpdateFAT12ClusterChain(BlockBuffer, *FLASHFileStartCluster, FILE_CLUSTERS(FLASH_FILE_SIZE_BYTES));
426
427 /* Cluster 2+n onwards: Cluster chain of EEPROM.BIN */
428 UpdateFAT12ClusterChain(BlockBuffer, *EEPROMFileStartCluster, FILE_CLUSTERS(EEPROM_FILE_SIZE_BYTES));
429
430 break;
431
432 case DISK_BLOCK_RootFilesBlock:
433 memcpy(BlockBuffer, FirmwareFileEntries, sizeof(FirmwareFileEntries));
434
435 break;
436
437 default:
438 ReadWriteFLASHFileBlock(BlockNumber, BlockBuffer, true);
439 ReadWriteEEPROMFileBlock(BlockNumber, BlockBuffer, true);
440
441 break;
442 }
443
444 /* Write the entire read block Buffer to the host */
445 Endpoint_Write_Stream_LE(BlockBuffer, sizeof(BlockBuffer), NULL);
446 Endpoint_ClearIN();
447 }