qom: Use returned bool to check for failure, Coccinelle part
[qemu/ar7.git] / block / vvfat.c
blobe3e27e0d6c4c1668b1aa239e12aaa6ee00e5d8b8
1 /* vim:set shiftwidth=4 ts=4: */
2 /*
3 * QEMU Block driver for virtual VFAT (shadows a local directory)
5 * Copyright (c) 2004,2005 Johannes E. Schindelin
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu/osdep.h"
27 #include <dirent.h>
28 #include "qapi/error.h"
29 #include "block/block_int.h"
30 #include "block/qdict.h"
31 #include "qemu/module.h"
32 #include "qemu/option.h"
33 #include "qemu/bswap.h"
34 #include "migration/blocker.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "qemu/ctype.h"
38 #include "qemu/cutils.h"
39 #include "qemu/error-report.h"
41 #ifndef S_IWGRP
42 #define S_IWGRP 0
43 #endif
44 #ifndef S_IWOTH
45 #define S_IWOTH 0
46 #endif
48 /* TODO: add ":bootsector=blabla.img:" */
49 /* LATER TODO: add automatic boot sector generation from
50 BOOTEASY.ASM and Ranish Partition Manager
51 Note that DOS assumes the system files to be the first files in the
52 file system (test if the boot sector still relies on that fact)! */
53 /* MAYBE TODO: write block-visofs.c */
54 /* TODO: call try_commit() only after a timeout */
56 /* #define DEBUG */
58 #ifdef DEBUG
60 #define DLOG(a) a
62 static void checkpoint(void);
64 #else
66 #define DLOG(a)
68 #endif
70 /* bootsector OEM name. see related compatibility problems at:
71 * https://jdebp.eu/FGA/volume-boot-block-oem-name-field.html
72 * http://seasip.info/Misc/oemid.html
74 #define BOOTSECTOR_OEM_NAME "MSWIN4.1"
76 #define DIR_DELETED 0xe5
77 #define DIR_KANJI DIR_DELETED
78 #define DIR_KANJI_FAKE 0x05
79 #define DIR_FREE 0x00
81 /* dynamic array functions */
82 typedef struct array_t {
83 char* pointer;
84 unsigned int size,next,item_size;
85 } array_t;
87 static inline void array_init(array_t* array,unsigned int item_size)
89 array->pointer = NULL;
90 array->size=0;
91 array->next=0;
92 array->item_size=item_size;
95 static inline void array_free(array_t* array)
97 g_free(array->pointer);
98 array->size=array->next=0;
101 /* does not automatically grow */
102 static inline void* array_get(array_t* array,unsigned int index) {
103 assert(index < array->next);
104 assert(array->pointer);
105 return array->pointer + index * array->item_size;
108 static inline void array_ensure_allocated(array_t *array, int index)
110 if((index + 1) * array->item_size > array->size) {
111 int new_size = (index + 32) * array->item_size;
112 array->pointer = g_realloc(array->pointer, new_size);
113 assert(array->pointer);
114 memset(array->pointer + array->size, 0, new_size - array->size);
115 array->size = new_size;
116 array->next = index + 1;
120 static inline void* array_get_next(array_t* array) {
121 unsigned int next = array->next;
123 array_ensure_allocated(array, next);
124 array->next = next + 1;
125 return array_get(array, next);
128 static inline void* array_insert(array_t* array,unsigned int index,unsigned int count) {
129 if((array->next+count)*array->item_size>array->size) {
130 int increment=count*array->item_size;
131 array->pointer=g_realloc(array->pointer,array->size+increment);
132 if(!array->pointer)
133 return NULL;
134 array->size+=increment;
136 memmove(array->pointer+(index+count)*array->item_size,
137 array->pointer+index*array->item_size,
138 (array->next-index)*array->item_size);
139 array->next+=count;
140 return array->pointer+index*array->item_size;
143 static inline int array_remove_slice(array_t* array,int index, int count)
145 assert(index >=0);
146 assert(count > 0);
147 assert(index + count <= array->next);
149 memmove(array->pointer + index * array->item_size,
150 array->pointer + (index + count) * array->item_size,
151 (array->next - index - count) * array->item_size);
153 array->next -= count;
154 return 0;
157 static int array_remove(array_t* array,int index)
159 return array_remove_slice(array, index, 1);
162 /* return the index for a given member */
163 static int array_index(array_t* array, void* pointer)
165 size_t offset = (char*)pointer - array->pointer;
166 assert((offset % array->item_size) == 0);
167 assert(offset/array->item_size < array->next);
168 return offset/array->item_size;
171 /* These structures are used to fake a disk and the VFAT filesystem.
172 * For this reason we need to use QEMU_PACKED. */
174 typedef struct bootsector_t {
175 uint8_t jump[3];
176 uint8_t name[8];
177 uint16_t sector_size;
178 uint8_t sectors_per_cluster;
179 uint16_t reserved_sectors;
180 uint8_t number_of_fats;
181 uint16_t root_entries;
182 uint16_t total_sectors16;
183 uint8_t media_type;
184 uint16_t sectors_per_fat;
185 uint16_t sectors_per_track;
186 uint16_t number_of_heads;
187 uint32_t hidden_sectors;
188 uint32_t total_sectors;
189 union {
190 struct {
191 uint8_t drive_number;
192 uint8_t reserved1;
193 uint8_t signature;
194 uint32_t id;
195 uint8_t volume_label[11];
196 uint8_t fat_type[8];
197 uint8_t ignored[0x1c0];
198 } QEMU_PACKED fat16;
199 struct {
200 uint32_t sectors_per_fat;
201 uint16_t flags;
202 uint8_t major,minor;
203 uint32_t first_cluster_of_root_dir;
204 uint16_t info_sector;
205 uint16_t backup_boot_sector;
206 uint8_t reserved[12];
207 uint8_t drive_number;
208 uint8_t reserved1;
209 uint8_t signature;
210 uint32_t id;
211 uint8_t volume_label[11];
212 uint8_t fat_type[8];
213 uint8_t ignored[0x1a4];
214 } QEMU_PACKED fat32;
215 } u;
216 uint8_t magic[2];
217 } QEMU_PACKED bootsector_t;
219 typedef struct {
220 uint8_t head;
221 uint8_t sector;
222 uint8_t cylinder;
223 } mbr_chs_t;
225 typedef struct partition_t {
226 uint8_t attributes; /* 0x80 = bootable */
227 mbr_chs_t start_CHS;
228 uint8_t fs_type; /* 0x1 = FAT12, 0x6 = FAT16, 0xe = FAT16_LBA, 0xb = FAT32, 0xc = FAT32_LBA */
229 mbr_chs_t end_CHS;
230 uint32_t start_sector_long;
231 uint32_t length_sector_long;
232 } QEMU_PACKED partition_t;
234 typedef struct mbr_t {
235 uint8_t ignored[0x1b8];
236 uint32_t nt_id;
237 uint8_t ignored2[2];
238 partition_t partition[4];
239 uint8_t magic[2];
240 } QEMU_PACKED mbr_t;
242 typedef struct direntry_t {
243 uint8_t name[8 + 3];
244 uint8_t attributes;
245 uint8_t reserved[2];
246 uint16_t ctime;
247 uint16_t cdate;
248 uint16_t adate;
249 uint16_t begin_hi;
250 uint16_t mtime;
251 uint16_t mdate;
252 uint16_t begin;
253 uint32_t size;
254 } QEMU_PACKED direntry_t;
256 /* this structure are used to transparently access the files */
258 typedef struct mapping_t {
259 /* begin is the first cluster, end is the last+1 */
260 uint32_t begin,end;
261 /* as s->directory is growable, no pointer may be used here */
262 unsigned int dir_index;
263 /* the clusters of a file may be in any order; this points to the first */
264 int first_mapping_index;
265 union {
266 /* offset is
267 * - the offset in the file (in clusters) for a file, or
268 * - the next cluster of the directory for a directory
270 struct {
271 uint32_t offset;
272 } file;
273 struct {
274 int parent_mapping_index;
275 int first_dir_index;
276 } dir;
277 } info;
278 /* path contains the full path, i.e. it always starts with s->path */
279 char* path;
281 enum {
282 MODE_UNDEFINED = 0,
283 MODE_NORMAL = 1,
284 MODE_MODIFIED = 2,
285 MODE_DIRECTORY = 4,
286 MODE_DELETED = 8,
287 } mode;
288 int read_only;
289 } mapping_t;
291 #ifdef DEBUG
292 static void print_direntry(const struct direntry_t*);
293 static void print_mapping(const struct mapping_t* mapping);
294 #endif
296 /* here begins the real VVFAT driver */
298 typedef struct BDRVVVFATState {
299 CoMutex lock;
300 BlockDriverState* bs; /* pointer to parent */
301 unsigned char first_sectors[0x40*0x200];
303 int fat_type; /* 16 or 32 */
304 array_t fat,directory,mapping;
305 char volume_label[11];
307 uint32_t offset_to_bootsector; /* 0 for floppy, 0x3f for disk */
309 unsigned int cluster_size;
310 unsigned int sectors_per_cluster;
311 unsigned int sectors_per_fat;
312 uint32_t last_cluster_of_root_directory;
313 /* how many entries are available in root directory (0 for FAT32) */
314 uint16_t root_entries;
315 uint32_t sector_count; /* total number of sectors of the partition */
316 uint32_t cluster_count; /* total number of clusters of this partition */
317 uint32_t max_fat_value;
318 uint32_t offset_to_fat;
319 uint32_t offset_to_root_dir;
321 int current_fd;
322 mapping_t* current_mapping;
323 unsigned char* cluster; /* points to current cluster */
324 unsigned char* cluster_buffer; /* points to a buffer to hold temp data */
325 unsigned int current_cluster;
327 /* write support */
328 char* qcow_filename;
329 BdrvChild* qcow;
330 void* fat2;
331 char* used_clusters;
332 array_t commits;
333 const char* path;
334 int downcase_short_names;
336 Error *migration_blocker;
337 } BDRVVVFATState;
339 /* take the sector position spos and convert it to Cylinder/Head/Sector position
340 * if the position is outside the specified geometry, fill maximum value for CHS
341 * and return 1 to signal overflow.
343 static int sector2CHS(mbr_chs_t *chs, int spos, int cyls, int heads, int secs)
345 int head,sector;
346 sector = spos % secs; spos /= secs;
347 head = spos % heads; spos /= heads;
348 if (spos >= cyls) {
349 /* Overflow,
350 it happens if 32bit sector positions are used, while CHS is only 24bit.
351 Windows/Dos is said to take 1023/255/63 as nonrepresentable CHS */
352 chs->head = 0xFF;
353 chs->sector = 0xFF;
354 chs->cylinder = 0xFF;
355 return 1;
357 chs->head = (uint8_t)head;
358 chs->sector = (uint8_t)( (sector+1) | ((spos>>8)<<6) );
359 chs->cylinder = (uint8_t)spos;
360 return 0;
363 static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)
365 /* TODO: if the files mbr.img and bootsect.img exist, use them */
366 mbr_t* real_mbr=(mbr_t*)s->first_sectors;
367 partition_t* partition = &(real_mbr->partition[0]);
368 int lba;
370 memset(s->first_sectors,0,512);
372 /* Win NT Disk Signature */
373 real_mbr->nt_id= cpu_to_le32(0xbe1afdfa);
375 partition->attributes=0x80; /* bootable */
377 /* LBA is used when partition is outside the CHS geometry */
378 lba = sector2CHS(&partition->start_CHS, s->offset_to_bootsector,
379 cyls, heads, secs);
380 lba |= sector2CHS(&partition->end_CHS, s->bs->total_sectors - 1,
381 cyls, heads, secs);
383 /*LBA partitions are identified only by start/length_sector_long not by CHS*/
384 partition->start_sector_long = cpu_to_le32(s->offset_to_bootsector);
385 partition->length_sector_long = cpu_to_le32(s->bs->total_sectors
386 - s->offset_to_bootsector);
388 /* FAT12/FAT16/FAT32 */
389 /* DOS uses different types when partition is LBA,
390 probably to prevent older versions from using CHS on them */
391 partition->fs_type = s->fat_type == 12 ? 0x1 :
392 s->fat_type == 16 ? (lba ? 0xe : 0x06) :
393 /*s->fat_type == 32*/ (lba ? 0xc : 0x0b);
395 real_mbr->magic[0]=0x55; real_mbr->magic[1]=0xaa;
398 /* direntry functions */
400 static direntry_t *create_long_filename(BDRVVVFATState *s, const char *filename)
402 int number_of_entries, i;
403 glong length;
404 direntry_t *entry;
406 gunichar2 *longname = g_utf8_to_utf16(filename, -1, NULL, &length, NULL);
407 if (!longname) {
408 fprintf(stderr, "vvfat: invalid UTF-8 name: %s\n", filename);
409 return NULL;
412 number_of_entries = DIV_ROUND_UP(length * 2, 26);
414 for(i=0;i<number_of_entries;i++) {
415 entry=array_get_next(&(s->directory));
416 entry->attributes=0xf;
417 entry->reserved[0]=0;
418 entry->begin=0;
419 entry->name[0]=(number_of_entries-i)|(i==0?0x40:0);
421 for(i=0;i<26*number_of_entries;i++) {
422 int offset=(i%26);
423 if(offset<10) offset=1+offset;
424 else if(offset<22) offset=14+offset-10;
425 else offset=28+offset-22;
426 entry=array_get(&(s->directory),s->directory.next-1-(i/26));
427 if (i >= 2 * length + 2) {
428 entry->name[offset] = 0xff;
429 } else if (i % 2 == 0) {
430 entry->name[offset] = longname[i / 2] & 0xff;
431 } else {
432 entry->name[offset] = longname[i / 2] >> 8;
435 g_free(longname);
436 return array_get(&(s->directory),s->directory.next-number_of_entries);
439 static char is_free(const direntry_t* direntry)
441 return direntry->name[0] == DIR_DELETED || direntry->name[0] == DIR_FREE;
444 static char is_volume_label(const direntry_t* direntry)
446 return direntry->attributes == 0x28;
449 static char is_long_name(const direntry_t* direntry)
451 return direntry->attributes == 0xf;
454 static char is_short_name(const direntry_t* direntry)
456 return !is_volume_label(direntry) && !is_long_name(direntry)
457 && !is_free(direntry);
460 static char is_directory(const direntry_t* direntry)
462 return direntry->attributes & 0x10 && direntry->name[0] != DIR_DELETED;
465 static inline char is_dot(const direntry_t* direntry)
467 return is_short_name(direntry) && direntry->name[0] == '.';
470 static char is_file(const direntry_t* direntry)
472 return is_short_name(direntry) && !is_directory(direntry);
475 static inline uint32_t begin_of_direntry(const direntry_t* direntry)
477 return le16_to_cpu(direntry->begin)|(le16_to_cpu(direntry->begin_hi)<<16);
480 static inline uint32_t filesize_of_direntry(const direntry_t* direntry)
482 return le32_to_cpu(direntry->size);
485 static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin)
487 direntry->begin = cpu_to_le16(begin & 0xffff);
488 direntry->begin_hi = cpu_to_le16((begin >> 16) & 0xffff);
491 static bool valid_filename(const unsigned char *name)
493 unsigned char c;
494 if (!strcmp((const char*)name, ".") || !strcmp((const char*)name, "..")) {
495 return false;
497 for (; (c = *name); name++) {
498 if (!((c >= '0' && c <= '9') ||
499 (c >= 'A' && c <= 'Z') ||
500 (c >= 'a' && c <= 'z') ||
501 c > 127 ||
502 strchr("$%'-_@~`!(){}^#&.+,;=[]", c) != NULL))
504 return false;
507 return true;
510 static uint8_t to_valid_short_char(gunichar c)
512 c = g_unichar_toupper(c);
513 if ((c >= '0' && c <= '9') ||
514 (c >= 'A' && c <= 'Z') ||
515 strchr("$%'-_@~`!(){}^#&", c) != NULL) {
516 return c;
517 } else {
518 return 0;
522 static direntry_t *create_short_filename(BDRVVVFATState *s,
523 const char *filename,
524 unsigned int directory_start)
526 int i, j = 0;
527 direntry_t *entry = array_get_next(&(s->directory));
528 const gchar *p, *last_dot = NULL;
529 gunichar c;
530 bool lossy_conversion = false;
531 char tail[8];
533 if (!entry) {
534 return NULL;
536 memset(entry->name, 0x20, sizeof(entry->name));
538 /* copy filename and search last dot */
539 for (p = filename; ; p = g_utf8_next_char(p)) {
540 c = g_utf8_get_char(p);
541 if (c == '\0') {
542 break;
543 } else if (c == '.') {
544 if (j == 0) {
545 /* '.' at start of filename */
546 lossy_conversion = true;
547 } else {
548 if (last_dot) {
549 lossy_conversion = true;
551 last_dot = p;
553 } else if (!last_dot) {
554 /* first part of the name; copy it */
555 uint8_t v = to_valid_short_char(c);
556 if (j < 8 && v) {
557 entry->name[j++] = v;
558 } else {
559 lossy_conversion = true;
564 /* copy extension (if any) */
565 if (last_dot) {
566 j = 0;
567 for (p = g_utf8_next_char(last_dot); ; p = g_utf8_next_char(p)) {
568 c = g_utf8_get_char(p);
569 if (c == '\0') {
570 break;
571 } else {
572 /* extension; copy it */
573 uint8_t v = to_valid_short_char(c);
574 if (j < 3 && v) {
575 entry->name[8 + (j++)] = v;
576 } else {
577 lossy_conversion = true;
583 if (entry->name[0] == DIR_KANJI) {
584 entry->name[0] = DIR_KANJI_FAKE;
587 /* numeric-tail generation */
588 for (j = 0; j < 8; j++) {
589 if (entry->name[j] == ' ') {
590 break;
593 for (i = lossy_conversion ? 1 : 0; i < 999999; i++) {
594 direntry_t *entry1;
595 if (i > 0) {
596 int len = snprintf(tail, sizeof(tail), "~%u", (unsigned)i);
597 assert(len <= 7);
598 memcpy(entry->name + MIN(j, 8 - len), tail, len);
600 for (entry1 = array_get(&(s->directory), directory_start);
601 entry1 < entry; entry1++) {
602 if (!is_long_name(entry1) &&
603 !memcmp(entry1->name, entry->name, 11)) {
604 break; /* found dupe */
607 if (entry1 == entry) {
608 /* no dupe found */
609 return entry;
612 return NULL;
615 /* fat functions */
617 static inline uint8_t fat_chksum(const direntry_t* entry)
619 uint8_t chksum=0;
620 int i;
622 for (i = 0; i < ARRAY_SIZE(entry->name); i++) {
623 chksum = (((chksum & 0xfe) >> 1) |
624 ((chksum & 0x01) ? 0x80 : 0)) + entry->name[i];
627 return chksum;
630 /* if return_time==0, this returns the fat_date, else the fat_time */
631 static uint16_t fat_datetime(time_t time,int return_time) {
632 struct tm* t;
633 struct tm t1;
634 t = &t1;
635 localtime_r(&time,t);
636 if(return_time)
637 return cpu_to_le16((t->tm_sec/2)|(t->tm_min<<5)|(t->tm_hour<<11));
638 return cpu_to_le16((t->tm_mday)|((t->tm_mon+1)<<5)|((t->tm_year-80)<<9));
641 static inline void fat_set(BDRVVVFATState* s,unsigned int cluster,uint32_t value)
643 if(s->fat_type==32) {
644 uint32_t* entry=array_get(&(s->fat),cluster);
645 *entry=cpu_to_le32(value);
646 } else if(s->fat_type==16) {
647 uint16_t* entry=array_get(&(s->fat),cluster);
648 *entry=cpu_to_le16(value&0xffff);
649 } else {
650 int offset = (cluster*3/2);
651 unsigned char* p = array_get(&(s->fat), offset);
652 switch (cluster&1) {
653 case 0:
654 p[0] = value&0xff;
655 p[1] = (p[1]&0xf0) | ((value>>8)&0xf);
656 break;
657 case 1:
658 p[0] = (p[0]&0xf) | ((value&0xf)<<4);
659 p[1] = (value>>4);
660 break;
665 static inline uint32_t fat_get(BDRVVVFATState* s,unsigned int cluster)
667 if(s->fat_type==32) {
668 uint32_t* entry=array_get(&(s->fat),cluster);
669 return le32_to_cpu(*entry);
670 } else if(s->fat_type==16) {
671 uint16_t* entry=array_get(&(s->fat),cluster);
672 return le16_to_cpu(*entry);
673 } else {
674 const uint8_t* x=(uint8_t*)(s->fat.pointer)+cluster*3/2;
675 return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
679 static inline int fat_eof(BDRVVVFATState* s,uint32_t fat_entry)
681 if(fat_entry>s->max_fat_value-8)
682 return -1;
683 return 0;
686 static inline void init_fat(BDRVVVFATState* s)
688 if (s->fat_type == 12) {
689 array_init(&(s->fat),1);
690 array_ensure_allocated(&(s->fat),
691 s->sectors_per_fat * 0x200 * 3 / 2 - 1);
692 } else {
693 array_init(&(s->fat),(s->fat_type==32?4:2));
694 array_ensure_allocated(&(s->fat),
695 s->sectors_per_fat * 0x200 / s->fat.item_size - 1);
697 memset(s->fat.pointer,0,s->fat.size);
699 switch(s->fat_type) {
700 case 12: s->max_fat_value=0xfff; break;
701 case 16: s->max_fat_value=0xffff; break;
702 case 32: s->max_fat_value=0x0fffffff; break;
703 default: s->max_fat_value=0; /* error... */
708 static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,
709 unsigned int directory_start, const char* filename, int is_dot)
711 int long_index = s->directory.next;
712 direntry_t* entry = NULL;
713 direntry_t* entry_long = NULL;
715 if(is_dot) {
716 entry=array_get_next(&(s->directory));
717 memset(entry->name, 0x20, sizeof(entry->name));
718 memcpy(entry->name,filename,strlen(filename));
719 return entry;
722 entry_long=create_long_filename(s,filename);
723 entry = create_short_filename(s, filename, directory_start);
725 /* calculate checksum; propagate to long name */
726 if(entry_long) {
727 uint8_t chksum=fat_chksum(entry);
729 /* calculate anew, because realloc could have taken place */
730 entry_long=array_get(&(s->directory),long_index);
731 while(entry_long<entry && is_long_name(entry_long)) {
732 entry_long->reserved[1]=chksum;
733 entry_long++;
737 return entry;
741 * Read a directory. (the index of the corresponding mapping must be passed).
743 static int read_directory(BDRVVVFATState* s, int mapping_index)
745 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
746 direntry_t* direntry;
747 const char* dirname = mapping->path;
748 int first_cluster = mapping->begin;
749 int parent_index = mapping->info.dir.parent_mapping_index;
750 mapping_t* parent_mapping = (mapping_t*)
751 (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);
752 int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;
754 DIR* dir=opendir(dirname);
755 struct dirent* entry;
756 int i;
758 assert(mapping->mode & MODE_DIRECTORY);
760 if(!dir) {
761 mapping->end = mapping->begin;
762 return -1;
765 i = mapping->info.dir.first_dir_index =
766 first_cluster == 0 ? 0 : s->directory.next;
768 if (first_cluster != 0) {
769 /* create the top entries of a subdirectory */
770 (void)create_short_and_long_name(s, i, ".", 1);
771 (void)create_short_and_long_name(s, i, "..", 1);
774 /* actually read the directory, and allocate the mappings */
775 while((entry=readdir(dir))) {
776 unsigned int length=strlen(dirname)+2+strlen(entry->d_name);
777 char* buffer;
778 direntry_t* direntry;
779 struct stat st;
780 int is_dot=!strcmp(entry->d_name,".");
781 int is_dotdot=!strcmp(entry->d_name,"..");
783 if (first_cluster == 0 && s->directory.next >= s->root_entries - 1) {
784 fprintf(stderr, "Too many entries in root directory\n");
785 closedir(dir);
786 return -2;
789 if(first_cluster == 0 && (is_dotdot || is_dot))
790 continue;
792 buffer = g_malloc(length);
793 snprintf(buffer,length,"%s/%s",dirname,entry->d_name);
795 if(stat(buffer,&st)<0) {
796 g_free(buffer);
797 continue;
800 /* create directory entry for this file */
801 if (!is_dot && !is_dotdot) {
802 direntry = create_short_and_long_name(s, i, entry->d_name, 0);
803 } else {
804 direntry = array_get(&(s->directory), is_dot ? i : i + 1);
806 direntry->attributes=(S_ISDIR(st.st_mode)?0x10:0x20);
807 direntry->reserved[0]=direntry->reserved[1]=0;
808 direntry->ctime=fat_datetime(st.st_ctime,1);
809 direntry->cdate=fat_datetime(st.st_ctime,0);
810 direntry->adate=fat_datetime(st.st_atime,0);
811 direntry->begin_hi=0;
812 direntry->mtime=fat_datetime(st.st_mtime,1);
813 direntry->mdate=fat_datetime(st.st_mtime,0);
814 if(is_dotdot)
815 set_begin_of_direntry(direntry, first_cluster_of_parent);
816 else if(is_dot)
817 set_begin_of_direntry(direntry, first_cluster);
818 else
819 direntry->begin=0; /* do that later */
820 if (st.st_size > 0x7fffffff) {
821 fprintf(stderr, "File %s is larger than 2GB\n", buffer);
822 g_free(buffer);
823 closedir(dir);
824 return -2;
826 direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);
828 /* create mapping for this file */
829 if(!is_dot && !is_dotdot && (S_ISDIR(st.st_mode) || st.st_size)) {
830 s->current_mapping = array_get_next(&(s->mapping));
831 s->current_mapping->begin=0;
832 s->current_mapping->end=st.st_size;
834 * we get the direntry of the most recent direntry, which
835 * contains the short name and all the relevant information.
837 s->current_mapping->dir_index=s->directory.next-1;
838 s->current_mapping->first_mapping_index = -1;
839 if (S_ISDIR(st.st_mode)) {
840 s->current_mapping->mode = MODE_DIRECTORY;
841 s->current_mapping->info.dir.parent_mapping_index =
842 mapping_index;
843 } else {
844 s->current_mapping->mode = MODE_UNDEFINED;
845 s->current_mapping->info.file.offset = 0;
847 s->current_mapping->path=buffer;
848 s->current_mapping->read_only =
849 (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0;
850 } else {
851 g_free(buffer);
854 closedir(dir);
856 /* fill with zeroes up to the end of the cluster */
857 while(s->directory.next%(0x10*s->sectors_per_cluster)) {
858 direntry_t* direntry=array_get_next(&(s->directory));
859 memset(direntry,0,sizeof(direntry_t));
862 if (s->fat_type != 32 &&
863 mapping_index == 0 &&
864 s->directory.next < s->root_entries) {
865 /* root directory */
866 int cur = s->directory.next;
867 array_ensure_allocated(&(s->directory), s->root_entries - 1);
868 s->directory.next = s->root_entries;
869 memset(array_get(&(s->directory), cur), 0,
870 (s->root_entries - cur) * sizeof(direntry_t));
873 /* re-get the mapping, since s->mapping was possibly realloc()ed */
874 mapping = array_get(&(s->mapping), mapping_index);
875 first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)
876 * 0x20 / s->cluster_size;
877 mapping->end = first_cluster;
879 direntry = array_get(&(s->directory), mapping->dir_index);
880 set_begin_of_direntry(direntry, mapping->begin);
882 return 0;
885 static inline uint32_t sector2cluster(BDRVVVFATState* s,off_t sector_num)
887 return (sector_num - s->offset_to_root_dir) / s->sectors_per_cluster;
890 static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
892 return s->offset_to_root_dir + s->sectors_per_cluster * cluster_num;
895 static int init_directories(BDRVVVFATState* s,
896 const char *dirname, int heads, int secs,
897 Error **errp)
899 bootsector_t* bootsector;
900 mapping_t* mapping;
901 unsigned int i;
902 unsigned int cluster;
904 memset(&(s->first_sectors[0]),0,0x40*0x200);
906 s->cluster_size=s->sectors_per_cluster*0x200;
907 s->cluster_buffer=g_malloc(s->cluster_size);
910 * The formula: sc = spf+1+spf*spc*(512*8/fat_type),
911 * where sc is sector_count,
912 * spf is sectors_per_fat,
913 * spc is sectors_per_clusters, and
914 * fat_type = 12, 16 or 32.
916 i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;
917 s->sectors_per_fat=(s->sector_count+i)/i; /* round up */
919 s->offset_to_fat = s->offset_to_bootsector + 1;
920 s->offset_to_root_dir = s->offset_to_fat + s->sectors_per_fat * 2;
922 array_init(&(s->mapping),sizeof(mapping_t));
923 array_init(&(s->directory),sizeof(direntry_t));
925 /* add volume label */
927 direntry_t* entry=array_get_next(&(s->directory));
928 entry->attributes=0x28; /* archive | volume label */
929 memcpy(entry->name, s->volume_label, sizeof(entry->name));
932 /* Now build FAT, and write back information into directory */
933 init_fat(s);
935 /* TODO: if there are more entries, bootsector has to be adjusted! */
936 s->root_entries = 0x02 * 0x10 * s->sectors_per_cluster;
937 s->cluster_count=sector2cluster(s, s->sector_count);
939 mapping = array_get_next(&(s->mapping));
940 mapping->begin = 0;
941 mapping->dir_index = 0;
942 mapping->info.dir.parent_mapping_index = -1;
943 mapping->first_mapping_index = -1;
944 mapping->path = g_strdup(dirname);
945 i = strlen(mapping->path);
946 if (i > 0 && mapping->path[i - 1] == '/')
947 mapping->path[i - 1] = '\0';
948 mapping->mode = MODE_DIRECTORY;
949 mapping->read_only = 0;
950 s->path = mapping->path;
952 for (i = 0, cluster = 0; i < s->mapping.next; i++) {
953 /* MS-DOS expects the FAT to be 0 for the root directory
954 * (except for the media byte). */
955 /* LATER TODO: still true for FAT32? */
956 int fix_fat = (i != 0);
957 mapping = array_get(&(s->mapping), i);
959 if (mapping->mode & MODE_DIRECTORY) {
960 char *path = mapping->path;
961 mapping->begin = cluster;
962 if(read_directory(s, i)) {
963 error_setg(errp, "Could not read directory %s", path);
964 return -1;
966 mapping = array_get(&(s->mapping), i);
967 } else {
968 assert(mapping->mode == MODE_UNDEFINED);
969 mapping->mode=MODE_NORMAL;
970 mapping->begin = cluster;
971 if (mapping->end > 0) {
972 direntry_t* direntry = array_get(&(s->directory),
973 mapping->dir_index);
975 mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;
976 set_begin_of_direntry(direntry, mapping->begin);
977 } else {
978 mapping->end = cluster + 1;
979 fix_fat = 0;
983 assert(mapping->begin < mapping->end);
985 /* next free cluster */
986 cluster = mapping->end;
988 if(cluster > s->cluster_count) {
989 error_setg(errp,
990 "Directory does not fit in FAT%d (capacity %.2f MB)",
991 s->fat_type, s->sector_count / 2000.0);
992 return -1;
995 /* fix fat for entry */
996 if (fix_fat) {
997 int j;
998 for(j = mapping->begin; j < mapping->end - 1; j++)
999 fat_set(s, j, j+1);
1000 fat_set(s, mapping->end - 1, s->max_fat_value);
1004 mapping = array_get(&(s->mapping), 0);
1005 s->last_cluster_of_root_directory = mapping->end;
1007 /* the FAT signature */
1008 fat_set(s,0,s->max_fat_value);
1009 fat_set(s,1,s->max_fat_value);
1011 s->current_mapping = NULL;
1013 bootsector = (bootsector_t *)(s->first_sectors
1014 + s->offset_to_bootsector * 0x200);
1015 bootsector->jump[0]=0xeb;
1016 bootsector->jump[1]=0x3e;
1017 bootsector->jump[2]=0x90;
1018 memcpy(bootsector->name, BOOTSECTOR_OEM_NAME, 8);
1019 bootsector->sector_size=cpu_to_le16(0x200);
1020 bootsector->sectors_per_cluster=s->sectors_per_cluster;
1021 bootsector->reserved_sectors=cpu_to_le16(1);
1022 bootsector->number_of_fats=0x2; /* number of FATs */
1023 bootsector->root_entries = cpu_to_le16(s->root_entries);
1024 bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
1025 /* media descriptor: hard disk=0xf8, floppy=0xf0 */
1026 bootsector->media_type = (s->offset_to_bootsector > 0 ? 0xf8 : 0xf0);
1027 s->fat.pointer[0] = bootsector->media_type;
1028 bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
1029 bootsector->sectors_per_track = cpu_to_le16(secs);
1030 bootsector->number_of_heads = cpu_to_le16(heads);
1031 bootsector->hidden_sectors = cpu_to_le32(s->offset_to_bootsector);
1032 bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
1034 /* LATER TODO: if FAT32, this is wrong */
1035 /* drive_number: fda=0, hda=0x80 */
1036 bootsector->u.fat16.drive_number = s->offset_to_bootsector == 0 ? 0 : 0x80;
1037 bootsector->u.fat16.signature=0x29;
1038 bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);
1040 memcpy(bootsector->u.fat16.volume_label, s->volume_label,
1041 sizeof(bootsector->u.fat16.volume_label));
1042 memcpy(bootsector->u.fat16.fat_type,
1043 s->fat_type == 12 ? "FAT12 " : "FAT16 ", 8);
1044 bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;
1046 return 0;
1049 #ifdef DEBUG
1050 static BDRVVVFATState *vvv = NULL;
1051 #endif
1053 static int enable_write_target(BlockDriverState *bs, Error **errp);
1054 static int is_consistent(BDRVVVFATState *s);
1056 static QemuOptsList runtime_opts = {
1057 .name = "vvfat",
1058 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1059 .desc = {
1061 .name = "dir",
1062 .type = QEMU_OPT_STRING,
1063 .help = "Host directory to map to the vvfat device",
1066 .name = "fat-type",
1067 .type = QEMU_OPT_NUMBER,
1068 .help = "FAT type (12, 16 or 32)",
1071 .name = "floppy",
1072 .type = QEMU_OPT_BOOL,
1073 .help = "Create a floppy rather than a hard disk image",
1076 .name = "label",
1077 .type = QEMU_OPT_STRING,
1078 .help = "Use a volume label other than QEMU VVFAT",
1081 .name = "rw",
1082 .type = QEMU_OPT_BOOL,
1083 .help = "Make the image writable",
1085 { /* end of list */ }
1089 static void vvfat_parse_filename(const char *filename, QDict *options,
1090 Error **errp)
1092 int fat_type = 0;
1093 bool floppy = false;
1094 bool rw = false;
1095 int i;
1097 if (!strstart(filename, "fat:", NULL)) {
1098 error_setg(errp, "File name string must start with 'fat:'");
1099 return;
1102 /* Parse options */
1103 if (strstr(filename, ":32:")) {
1104 fat_type = 32;
1105 } else if (strstr(filename, ":16:")) {
1106 fat_type = 16;
1107 } else if (strstr(filename, ":12:")) {
1108 fat_type = 12;
1111 if (strstr(filename, ":floppy:")) {
1112 floppy = true;
1115 if (strstr(filename, ":rw:")) {
1116 rw = true;
1119 /* Get the directory name without options */
1120 i = strrchr(filename, ':') - filename;
1121 assert(i >= 3);
1122 if (filename[i - 2] == ':' && qemu_isalpha(filename[i - 1])) {
1123 /* workaround for DOS drive names */
1124 filename += i - 1;
1125 } else {
1126 filename += i + 1;
1129 /* Fill in the options QDict */
1130 qdict_put_str(options, "dir", filename);
1131 qdict_put_int(options, "fat-type", fat_type);
1132 qdict_put_bool(options, "floppy", floppy);
1133 qdict_put_bool(options, "rw", rw);
1136 static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
1137 Error **errp)
1139 BDRVVVFATState *s = bs->opaque;
1140 int cyls, heads, secs;
1141 bool floppy;
1142 const char *dirname, *label;
1143 QemuOpts *opts;
1144 Error *local_err = NULL;
1145 int ret;
1147 #ifdef DEBUG
1148 vvv = s;
1149 #endif
1151 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1152 if (!qemu_opts_absorb_qdict(opts, options, &local_err)) {
1153 error_propagate(errp, local_err);
1154 ret = -EINVAL;
1155 goto fail;
1158 dirname = qemu_opt_get(opts, "dir");
1159 if (!dirname) {
1160 error_setg(errp, "vvfat block driver requires a 'dir' option");
1161 ret = -EINVAL;
1162 goto fail;
1165 s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
1166 floppy = qemu_opt_get_bool(opts, "floppy", false);
1168 memset(s->volume_label, ' ', sizeof(s->volume_label));
1169 label = qemu_opt_get(opts, "label");
1170 if (label) {
1171 size_t label_length = strlen(label);
1172 if (label_length > 11) {
1173 error_setg(errp, "vvfat label cannot be longer than 11 bytes");
1174 ret = -EINVAL;
1175 goto fail;
1177 memcpy(s->volume_label, label, label_length);
1178 } else {
1179 memcpy(s->volume_label, "QEMU VVFAT", 10);
1182 if (floppy) {
1183 /* 1.44MB or 2.88MB floppy. 2.88MB can be FAT12 (default) or FAT16. */
1184 if (!s->fat_type) {
1185 s->fat_type = 12;
1186 secs = 36;
1187 s->sectors_per_cluster = 2;
1188 } else {
1189 secs = s->fat_type == 12 ? 18 : 36;
1190 s->sectors_per_cluster = 1;
1192 cyls = 80;
1193 heads = 2;
1194 } else {
1195 /* 32MB or 504MB disk*/
1196 if (!s->fat_type) {
1197 s->fat_type = 16;
1199 s->offset_to_bootsector = 0x3f;
1200 cyls = s->fat_type == 12 ? 64 : 1024;
1201 heads = 16;
1202 secs = 63;
1205 switch (s->fat_type) {
1206 case 32:
1207 warn_report("FAT32 has not been tested. You are welcome to do so!");
1208 break;
1209 case 16:
1210 case 12:
1211 break;
1212 default:
1213 error_setg(errp, "Valid FAT types are only 12, 16 and 32");
1214 ret = -EINVAL;
1215 goto fail;
1219 s->bs = bs;
1221 /* LATER TODO: if FAT32, adjust */
1222 s->sectors_per_cluster=0x10;
1224 s->current_cluster=0xffffffff;
1226 s->qcow = NULL;
1227 s->qcow_filename = NULL;
1228 s->fat2 = NULL;
1229 s->downcase_short_names = 1;
1231 DLOG(fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
1232 dirname, cyls, heads, secs));
1234 s->sector_count = cyls * heads * secs - s->offset_to_bootsector;
1236 if (qemu_opt_get_bool(opts, "rw", false)) {
1237 if (!bdrv_is_read_only(bs)) {
1238 ret = enable_write_target(bs, errp);
1239 if (ret < 0) {
1240 goto fail;
1242 } else {
1243 ret = -EPERM;
1244 error_setg(errp,
1245 "Unable to set VVFAT to 'rw' when drive is read-only");
1246 goto fail;
1248 } else {
1249 ret = bdrv_apply_auto_read_only(bs, NULL, errp);
1250 if (ret < 0) {
1251 goto fail;
1255 bs->total_sectors = cyls * heads * secs;
1257 if (init_directories(s, dirname, heads, secs, errp)) {
1258 ret = -EIO;
1259 goto fail;
1262 s->sector_count = s->offset_to_root_dir
1263 + s->sectors_per_cluster * s->cluster_count;
1265 /* Disable migration when vvfat is used rw */
1266 if (s->qcow) {
1267 error_setg(&s->migration_blocker,
1268 "The vvfat (rw) format used by node '%s' "
1269 "does not support live migration",
1270 bdrv_get_device_or_node_name(bs));
1271 ret = migrate_add_blocker(s->migration_blocker, &local_err);
1272 if (local_err) {
1273 error_propagate(errp, local_err);
1274 error_free(s->migration_blocker);
1275 goto fail;
1279 if (s->offset_to_bootsector > 0) {
1280 init_mbr(s, cyls, heads, secs);
1283 qemu_co_mutex_init(&s->lock);
1285 ret = 0;
1286 fail:
1287 qemu_opts_del(opts);
1288 return ret;
1291 static void vvfat_refresh_limits(BlockDriverState *bs, Error **errp)
1293 bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
1296 static inline void vvfat_close_current_file(BDRVVVFATState *s)
1298 if(s->current_mapping) {
1299 s->current_mapping = NULL;
1300 if (s->current_fd) {
1301 qemu_close(s->current_fd);
1302 s->current_fd = 0;
1305 s->current_cluster = -1;
1308 /* mappings between index1 and index2-1 are supposed to be ordered
1309 * return value is the index of the last mapping for which end>cluster_num
1311 static inline int find_mapping_for_cluster_aux(BDRVVVFATState* s,int cluster_num,int index1,int index2)
1313 while(1) {
1314 int index3;
1315 mapping_t* mapping;
1316 index3=(index1+index2)/2;
1317 mapping=array_get(&(s->mapping),index3);
1318 assert(mapping->begin < mapping->end);
1319 if(mapping->begin>=cluster_num) {
1320 assert(index2!=index3 || index2==0);
1321 if(index2==index3)
1322 return index1;
1323 index2=index3;
1324 } else {
1325 if(index1==index3)
1326 return mapping->end<=cluster_num ? index2 : index1;
1327 index1=index3;
1329 assert(index1<=index2);
1330 DLOG(mapping=array_get(&(s->mapping),index1);
1331 assert(mapping->begin<=cluster_num);
1332 assert(index2 >= s->mapping.next ||
1333 ((mapping = array_get(&(s->mapping),index2)) &&
1334 mapping->end>cluster_num)));
1338 static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_num)
1340 int index=find_mapping_for_cluster_aux(s,cluster_num,0,s->mapping.next);
1341 mapping_t* mapping;
1342 if(index>=s->mapping.next)
1343 return NULL;
1344 mapping=array_get(&(s->mapping),index);
1345 if(mapping->begin>cluster_num)
1346 return NULL;
1347 assert(mapping->begin<=cluster_num && mapping->end>cluster_num);
1348 return mapping;
1351 static int open_file(BDRVVVFATState* s,mapping_t* mapping)
1353 if(!mapping)
1354 return -1;
1355 if(!s->current_mapping ||
1356 strcmp(s->current_mapping->path,mapping->path)) {
1357 /* open file */
1358 int fd = qemu_open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
1359 if(fd<0)
1360 return -1;
1361 vvfat_close_current_file(s);
1362 s->current_fd = fd;
1363 s->current_mapping = mapping;
1365 return 0;
1368 static inline int read_cluster(BDRVVVFATState *s,int cluster_num)
1370 if(s->current_cluster != cluster_num) {
1371 int result=0;
1372 off_t offset;
1373 assert(!s->current_mapping || s->current_fd || (s->current_mapping->mode & MODE_DIRECTORY));
1374 if(!s->current_mapping
1375 || s->current_mapping->begin>cluster_num
1376 || s->current_mapping->end<=cluster_num) {
1377 /* binary search of mappings for file */
1378 mapping_t* mapping=find_mapping_for_cluster(s,cluster_num);
1380 assert(!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end));
1382 if (mapping && mapping->mode & MODE_DIRECTORY) {
1383 vvfat_close_current_file(s);
1384 s->current_mapping = mapping;
1385 read_cluster_directory:
1386 offset = s->cluster_size*(cluster_num-s->current_mapping->begin);
1387 s->cluster = (unsigned char*)s->directory.pointer+offset
1388 + 0x20*s->current_mapping->info.dir.first_dir_index;
1389 assert(((s->cluster-(unsigned char*)s->directory.pointer)%s->cluster_size)==0);
1390 assert((char*)s->cluster+s->cluster_size <= s->directory.pointer+s->directory.next*s->directory.item_size);
1391 s->current_cluster = cluster_num;
1392 return 0;
1395 if(open_file(s,mapping))
1396 return -2;
1397 } else if (s->current_mapping->mode & MODE_DIRECTORY)
1398 goto read_cluster_directory;
1400 assert(s->current_fd);
1402 offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset;
1403 if(lseek(s->current_fd, offset, SEEK_SET)!=offset)
1404 return -3;
1405 s->cluster=s->cluster_buffer;
1406 result=read(s->current_fd,s->cluster,s->cluster_size);
1407 if(result<0) {
1408 s->current_cluster = -1;
1409 return -1;
1411 s->current_cluster = cluster_num;
1413 return 0;
1416 #ifdef DEBUG
1417 static void print_direntry(const direntry_t* direntry)
1419 int j = 0;
1420 char buffer[1024];
1422 fprintf(stderr, "direntry %p: ", direntry);
1423 if(!direntry)
1424 return;
1425 if(is_long_name(direntry)) {
1426 unsigned char* c=(unsigned char*)direntry;
1427 int i;
1428 for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)
1429 #define ADD_CHAR(c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;}
1430 ADD_CHAR(c[i]);
1431 for(i=14;i<26 && c[i] && c[i]!=0xff;i+=2)
1432 ADD_CHAR(c[i]);
1433 for(i=28;i<32 && c[i] && c[i]!=0xff;i+=2)
1434 ADD_CHAR(c[i]);
1435 buffer[j] = 0;
1436 fprintf(stderr, "%s\n", buffer);
1437 } else {
1438 int i;
1439 for(i=0;i<11;i++)
1440 ADD_CHAR(direntry->name[i]);
1441 buffer[j] = 0;
1442 fprintf(stderr,"%s attributes=0x%02x begin=%d size=%d\n",
1443 buffer,
1444 direntry->attributes,
1445 begin_of_direntry(direntry),le32_to_cpu(direntry->size));
1449 static void print_mapping(const mapping_t* mapping)
1451 fprintf(stderr, "mapping (%p): begin, end = %d, %d, dir_index = %d, "
1452 "first_mapping_index = %d, name = %s, mode = 0x%x, " ,
1453 mapping, mapping->begin, mapping->end, mapping->dir_index,
1454 mapping->first_mapping_index, mapping->path, mapping->mode);
1456 if (mapping->mode & MODE_DIRECTORY)
1457 fprintf(stderr, "parent_mapping_index = %d, first_dir_index = %d\n", mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);
1458 else
1459 fprintf(stderr, "offset = %d\n", mapping->info.file.offset);
1461 #endif
1463 static int vvfat_read(BlockDriverState *bs, int64_t sector_num,
1464 uint8_t *buf, int nb_sectors)
1466 BDRVVVFATState *s = bs->opaque;
1467 int i;
1469 for(i=0;i<nb_sectors;i++,sector_num++) {
1470 if (sector_num >= bs->total_sectors)
1471 return -1;
1472 if (s->qcow) {
1473 int64_t n;
1474 int ret;
1475 ret = bdrv_is_allocated(s->qcow->bs, sector_num * BDRV_SECTOR_SIZE,
1476 (nb_sectors - i) * BDRV_SECTOR_SIZE, &n);
1477 if (ret < 0) {
1478 return ret;
1480 if (ret) {
1481 DLOG(fprintf(stderr, "sectors %" PRId64 "+%" PRId64
1482 " allocated\n", sector_num,
1483 n >> BDRV_SECTOR_BITS));
1484 if (bdrv_pread(s->qcow, sector_num * BDRV_SECTOR_SIZE,
1485 buf + i * 0x200, n) < 0) {
1486 return -1;
1488 i += (n >> BDRV_SECTOR_BITS) - 1;
1489 sector_num += (n >> BDRV_SECTOR_BITS) - 1;
1490 continue;
1492 DLOG(fprintf(stderr, "sector %" PRId64 " not allocated\n",
1493 sector_num));
1495 if (sector_num < s->offset_to_root_dir) {
1496 if (sector_num < s->offset_to_fat) {
1497 memcpy(buf + i * 0x200,
1498 &(s->first_sectors[sector_num * 0x200]),
1499 0x200);
1500 } else if (sector_num < s->offset_to_fat + s->sectors_per_fat) {
1501 memcpy(buf + i * 0x200,
1502 &(s->fat.pointer[(sector_num
1503 - s->offset_to_fat) * 0x200]),
1504 0x200);
1505 } else if (sector_num < s->offset_to_root_dir) {
1506 memcpy(buf + i * 0x200,
1507 &(s->fat.pointer[(sector_num - s->offset_to_fat
1508 - s->sectors_per_fat) * 0x200]),
1509 0x200);
1511 } else {
1512 uint32_t sector = sector_num - s->offset_to_root_dir,
1513 sector_offset_in_cluster=(sector%s->sectors_per_cluster),
1514 cluster_num=sector/s->sectors_per_cluster;
1515 if(cluster_num > s->cluster_count || read_cluster(s, cluster_num) != 0) {
1516 /* LATER TODO: strict: return -1; */
1517 memset(buf+i*0x200,0,0x200);
1518 continue;
1520 memcpy(buf+i*0x200,s->cluster+sector_offset_in_cluster*0x200,0x200);
1523 return 0;
1526 static int coroutine_fn
1527 vvfat_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1528 QEMUIOVector *qiov, int flags)
1530 int ret;
1531 BDRVVVFATState *s = bs->opaque;
1532 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
1533 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1534 void *buf;
1536 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1537 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1539 buf = g_try_malloc(bytes);
1540 if (bytes && buf == NULL) {
1541 return -ENOMEM;
1544 qemu_co_mutex_lock(&s->lock);
1545 ret = vvfat_read(bs, sector_num, buf, nb_sectors);
1546 qemu_co_mutex_unlock(&s->lock);
1548 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1549 g_free(buf);
1551 return ret;
1554 /* LATER TODO: statify all functions */
1557 * Idea of the write support (use snapshot):
1559 * 1. check if all data is consistent, recording renames, modifications,
1560 * new files and directories (in s->commits).
1562 * 2. if the data is not consistent, stop committing
1564 * 3. handle renames, and create new files and directories (do not yet
1565 * write their contents)
1567 * 4. walk the directories, fixing the mapping and direntries, and marking
1568 * the handled mappings as not deleted
1570 * 5. commit the contents of the files
1572 * 6. handle deleted files and directories
1576 typedef struct commit_t {
1577 char* path;
1578 union {
1579 struct { uint32_t cluster; } rename;
1580 struct { int dir_index; uint32_t modified_offset; } writeout;
1581 struct { uint32_t first_cluster; } new_file;
1582 struct { uint32_t cluster; } mkdir;
1583 } param;
1584 /* DELETEs and RMDIRs are handled differently: see handle_deletes() */
1585 enum {
1586 ACTION_RENAME, ACTION_WRITEOUT, ACTION_NEW_FILE, ACTION_MKDIR
1587 } action;
1588 } commit_t;
1590 static void clear_commits(BDRVVVFATState* s)
1592 int i;
1593 DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));
1594 for (i = 0; i < s->commits.next; i++) {
1595 commit_t* commit = array_get(&(s->commits), i);
1596 assert(commit->path || commit->action == ACTION_WRITEOUT);
1597 if (commit->action != ACTION_WRITEOUT) {
1598 assert(commit->path);
1599 g_free(commit->path);
1600 } else
1601 assert(commit->path == NULL);
1603 s->commits.next = 0;
1606 static void schedule_rename(BDRVVVFATState* s,
1607 uint32_t cluster, char* new_path)
1609 commit_t* commit = array_get_next(&(s->commits));
1610 commit->path = new_path;
1611 commit->param.rename.cluster = cluster;
1612 commit->action = ACTION_RENAME;
1615 static void schedule_writeout(BDRVVVFATState* s,
1616 int dir_index, uint32_t modified_offset)
1618 commit_t* commit = array_get_next(&(s->commits));
1619 commit->path = NULL;
1620 commit->param.writeout.dir_index = dir_index;
1621 commit->param.writeout.modified_offset = modified_offset;
1622 commit->action = ACTION_WRITEOUT;
1625 static void schedule_new_file(BDRVVVFATState* s,
1626 char* path, uint32_t first_cluster)
1628 commit_t* commit = array_get_next(&(s->commits));
1629 commit->path = path;
1630 commit->param.new_file.first_cluster = first_cluster;
1631 commit->action = ACTION_NEW_FILE;
1634 static void schedule_mkdir(BDRVVVFATState* s, uint32_t cluster, char* path)
1636 commit_t* commit = array_get_next(&(s->commits));
1637 commit->path = path;
1638 commit->param.mkdir.cluster = cluster;
1639 commit->action = ACTION_MKDIR;
1642 typedef struct {
1644 * Since the sequence number is at most 0x3f, and the filename
1645 * length is at most 13 times the sequence number, the maximal
1646 * filename length is 0x3f * 13 bytes.
1648 unsigned char name[0x3f * 13 + 1];
1649 gunichar2 name2[0x3f * 13 + 1];
1650 int checksum, len;
1651 int sequence_number;
1652 } long_file_name;
1654 static void lfn_init(long_file_name* lfn)
1656 lfn->sequence_number = lfn->len = 0;
1657 lfn->checksum = 0x100;
1660 /* return 0 if parsed successfully, > 0 if no long name, < 0 if error */
1661 static int parse_long_name(long_file_name* lfn,
1662 const direntry_t* direntry)
1664 int i, j, offset;
1665 const unsigned char* pointer = (const unsigned char*)direntry;
1667 if (!is_long_name(direntry))
1668 return 1;
1670 if (pointer[0] & 0x40) {
1671 /* first entry; do some initialization */
1672 lfn->sequence_number = pointer[0] & 0x3f;
1673 lfn->checksum = pointer[13];
1674 lfn->name[0] = 0;
1675 lfn->name[lfn->sequence_number * 13] = 0;
1676 } else if ((pointer[0] & 0x3f) != --lfn->sequence_number) {
1677 /* not the expected sequence number */
1678 return -1;
1679 } else if (pointer[13] != lfn->checksum) {
1680 /* not the expected checksum */
1681 return -2;
1682 } else if (pointer[12] || pointer[26] || pointer[27]) {
1683 /* invalid zero fields */
1684 return -3;
1687 offset = 13 * (lfn->sequence_number - 1);
1688 for (i = 0, j = 1; i < 13; i++, j+=2) {
1689 if (j == 11)
1690 j = 14;
1691 else if (j == 26)
1692 j = 28;
1694 if (pointer[j] == 0 && pointer[j + 1] == 0) {
1695 /* end of long file name */
1696 break;
1698 gunichar2 c = (pointer[j + 1] << 8) + pointer[j];
1699 lfn->name2[offset + i] = c;
1702 if (pointer[0] & 0x40) {
1703 /* first entry; set len */
1704 lfn->len = offset + i;
1706 if ((pointer[0] & 0x3f) == 0x01) {
1707 /* last entry; finalize entry */
1708 glong olen;
1709 gchar *utf8 = g_utf16_to_utf8(lfn->name2, lfn->len, NULL, &olen, NULL);
1710 if (!utf8) {
1711 return -4;
1713 lfn->len = olen;
1714 memcpy(lfn->name, utf8, olen + 1);
1715 g_free(utf8);
1718 return 0;
1721 /* returns 0 if successful, >0 if no short_name, and <0 on error */
1722 static int parse_short_name(BDRVVVFATState* s,
1723 long_file_name* lfn, direntry_t* direntry)
1725 int i, j;
1727 if (!is_short_name(direntry))
1728 return 1;
1730 for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);
1731 for (i = 0; i <= j; i++) {
1732 uint8_t c = direntry->name[i];
1733 if (c != to_valid_short_char(c)) {
1734 return -1;
1735 } else if (s->downcase_short_names) {
1736 lfn->name[i] = qemu_tolower(direntry->name[i]);
1737 } else {
1738 lfn->name[i] = direntry->name[i];
1742 for (j = 2; j >= 0 && direntry->name[8 + j] == ' '; j--) {
1744 if (j >= 0) {
1745 lfn->name[i++] = '.';
1746 lfn->name[i + j + 1] = '\0';
1747 for (;j >= 0; j--) {
1748 uint8_t c = direntry->name[8 + j];
1749 if (c != to_valid_short_char(c)) {
1750 return -2;
1751 } else if (s->downcase_short_names) {
1752 lfn->name[i + j] = qemu_tolower(c);
1753 } else {
1754 lfn->name[i + j] = c;
1757 } else
1758 lfn->name[i + j + 1] = '\0';
1760 if (lfn->name[0] == DIR_KANJI_FAKE) {
1761 lfn->name[0] = DIR_KANJI;
1763 lfn->len = strlen((char*)lfn->name);
1765 return 0;
1768 static inline uint32_t modified_fat_get(BDRVVVFATState* s,
1769 unsigned int cluster)
1771 if (cluster < s->last_cluster_of_root_directory) {
1772 if (cluster + 1 == s->last_cluster_of_root_directory)
1773 return s->max_fat_value;
1774 else
1775 return cluster + 1;
1778 if (s->fat_type==32) {
1779 uint32_t* entry=((uint32_t*)s->fat2)+cluster;
1780 return le32_to_cpu(*entry);
1781 } else if (s->fat_type==16) {
1782 uint16_t* entry=((uint16_t*)s->fat2)+cluster;
1783 return le16_to_cpu(*entry);
1784 } else {
1785 const uint8_t* x=s->fat2+cluster*3/2;
1786 return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
1790 static inline bool cluster_was_modified(BDRVVVFATState *s,
1791 uint32_t cluster_num)
1793 int was_modified = 0;
1794 int i;
1796 if (s->qcow == NULL) {
1797 return 0;
1800 for (i = 0; !was_modified && i < s->sectors_per_cluster; i++) {
1801 was_modified = bdrv_is_allocated(s->qcow->bs,
1802 (cluster2sector(s, cluster_num) +
1803 i) * BDRV_SECTOR_SIZE,
1804 BDRV_SECTOR_SIZE, NULL);
1808 * Note that this treats failures to learn allocation status the
1809 * same as if an allocation has occurred. It's as safe as
1810 * anything else, given that a failure to learn allocation status
1811 * will probably result in more failures.
1813 return !!was_modified;
1816 static const char* get_basename(const char* path)
1818 char* basename = strrchr(path, '/');
1819 if (basename == NULL)
1820 return path;
1821 else
1822 return basename + 1; /* strip '/' */
1826 * The array s->used_clusters holds the states of the clusters. If it is
1827 * part of a file, it has bit 2 set, in case of a directory, bit 1. If it
1828 * was modified, bit 3 is set.
1829 * If any cluster is allocated, but not part of a file or directory, this
1830 * driver refuses to commit.
1832 typedef enum {
1833 USED_DIRECTORY = 1, USED_FILE = 2, USED_ANY = 3, USED_ALLOCATED = 4
1834 } used_t;
1837 * get_cluster_count_for_direntry() not only determines how many clusters
1838 * are occupied by direntry, but also if it was renamed or modified.
1840 * A file is thought to be renamed *only* if there already was a file with
1841 * exactly the same first cluster, but a different name.
1843 * Further, the files/directories handled by this function are
1844 * assumed to be *not* deleted (and *only* those).
1846 static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,
1847 direntry_t* direntry, const char* path)
1850 * This is a little bit tricky:
1851 * IF the guest OS just inserts a cluster into the file chain,
1852 * and leaves the rest alone, (i.e. the original file had clusters
1853 * 15 -> 16, but now has 15 -> 32 -> 16), then the following happens:
1855 * - do_commit will write the cluster into the file at the given
1856 * offset, but
1858 * - the cluster which is overwritten should be moved to a later
1859 * position in the file.
1861 * I am not aware that any OS does something as braindead, but this
1862 * situation could happen anyway when not committing for a long time.
1863 * Just to be sure that this does not bite us, detect it, and copy the
1864 * contents of the clusters to-be-overwritten into the qcow.
1866 int copy_it = 0;
1867 int was_modified = 0;
1868 int32_t ret = 0;
1870 uint32_t cluster_num = begin_of_direntry(direntry);
1871 uint32_t offset = 0;
1872 int first_mapping_index = -1;
1873 mapping_t* mapping = NULL;
1874 const char* basename2 = NULL;
1876 vvfat_close_current_file(s);
1878 /* the root directory */
1879 if (cluster_num == 0)
1880 return 0;
1882 /* write support */
1883 if (s->qcow) {
1884 basename2 = get_basename(path);
1886 mapping = find_mapping_for_cluster(s, cluster_num);
1888 if (mapping) {
1889 const char* basename;
1891 assert(mapping->mode & MODE_DELETED);
1892 mapping->mode &= ~MODE_DELETED;
1894 basename = get_basename(mapping->path);
1896 assert(mapping->mode & MODE_NORMAL);
1898 /* rename */
1899 if (strcmp(basename, basename2))
1900 schedule_rename(s, cluster_num, g_strdup(path));
1901 } else if (is_file(direntry))
1902 /* new file */
1903 schedule_new_file(s, g_strdup(path), cluster_num);
1904 else {
1905 abort();
1906 return 0;
1910 while(1) {
1911 if (s->qcow) {
1912 if (!copy_it && cluster_was_modified(s, cluster_num)) {
1913 if (mapping == NULL ||
1914 mapping->begin > cluster_num ||
1915 mapping->end <= cluster_num)
1916 mapping = find_mapping_for_cluster(s, cluster_num);
1919 if (mapping &&
1920 (mapping->mode & MODE_DIRECTORY) == 0) {
1922 /* was modified in qcow */
1923 if (offset != mapping->info.file.offset + s->cluster_size
1924 * (cluster_num - mapping->begin)) {
1925 /* offset of this cluster in file chain has changed */
1926 abort();
1927 copy_it = 1;
1928 } else if (offset == 0) {
1929 const char* basename = get_basename(mapping->path);
1931 if (strcmp(basename, basename2))
1932 copy_it = 1;
1933 first_mapping_index = array_index(&(s->mapping), mapping);
1936 if (mapping->first_mapping_index != first_mapping_index
1937 && mapping->info.file.offset > 0) {
1938 abort();
1939 copy_it = 1;
1942 /* need to write out? */
1943 if (!was_modified && is_file(direntry)) {
1944 was_modified = 1;
1945 schedule_writeout(s, mapping->dir_index, offset);
1950 if (copy_it) {
1951 int i;
1953 * This is horribly inefficient, but that is okay, since
1954 * it is rarely executed, if at all.
1956 int64_t offset = cluster2sector(s, cluster_num);
1958 vvfat_close_current_file(s);
1959 for (i = 0; i < s->sectors_per_cluster; i++) {
1960 int res;
1962 res = bdrv_is_allocated(s->qcow->bs,
1963 (offset + i) * BDRV_SECTOR_SIZE,
1964 BDRV_SECTOR_SIZE, NULL);
1965 if (res < 0) {
1966 return -1;
1968 if (!res) {
1969 res = vvfat_read(s->bs, offset, s->cluster_buffer, 1);
1970 if (res) {
1971 return -1;
1973 res = bdrv_pwrite(s->qcow, offset * BDRV_SECTOR_SIZE,
1974 s->cluster_buffer, BDRV_SECTOR_SIZE);
1975 if (res < 0) {
1976 return -2;
1983 ret++;
1984 if (s->used_clusters[cluster_num] & USED_ANY)
1985 return 0;
1986 s->used_clusters[cluster_num] = USED_FILE;
1988 cluster_num = modified_fat_get(s, cluster_num);
1990 if (fat_eof(s, cluster_num))
1991 return ret;
1992 else if (cluster_num < 2 || cluster_num > s->max_fat_value - 16)
1993 return -1;
1995 offset += s->cluster_size;
2000 * This function looks at the modified data (qcow).
2001 * It returns 0 upon inconsistency or error, and the number of clusters
2002 * used by the directory, its subdirectories and their files.
2004 static int check_directory_consistency(BDRVVVFATState *s,
2005 int cluster_num, const char* path)
2007 int ret = 0;
2008 unsigned char* cluster = g_malloc(s->cluster_size);
2009 direntry_t* direntries = (direntry_t*)cluster;
2010 mapping_t* mapping = find_mapping_for_cluster(s, cluster_num);
2012 long_file_name lfn;
2013 int path_len = strlen(path);
2014 char path2[PATH_MAX + 1];
2016 assert(path_len < PATH_MAX); /* len was tested before! */
2017 pstrcpy(path2, sizeof(path2), path);
2018 path2[path_len] = '/';
2019 path2[path_len + 1] = '\0';
2021 if (mapping) {
2022 const char* basename = get_basename(mapping->path);
2023 const char* basename2 = get_basename(path);
2025 assert(mapping->mode & MODE_DIRECTORY);
2027 assert(mapping->mode & MODE_DELETED);
2028 mapping->mode &= ~MODE_DELETED;
2030 if (strcmp(basename, basename2))
2031 schedule_rename(s, cluster_num, g_strdup(path));
2032 } else
2033 /* new directory */
2034 schedule_mkdir(s, cluster_num, g_strdup(path));
2036 lfn_init(&lfn);
2037 do {
2038 int i;
2039 int subret = 0;
2041 ret++;
2043 if (s->used_clusters[cluster_num] & USED_ANY) {
2044 fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num);
2045 goto fail;
2047 s->used_clusters[cluster_num] = USED_DIRECTORY;
2049 DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num)));
2050 subret = vvfat_read(s->bs, cluster2sector(s, cluster_num), cluster,
2051 s->sectors_per_cluster);
2052 if (subret) {
2053 fprintf(stderr, "Error fetching direntries\n");
2054 fail:
2055 g_free(cluster);
2056 return 0;
2059 for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) {
2060 int cluster_count = 0;
2062 DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i));
2063 if (is_volume_label(direntries + i) || is_dot(direntries + i) ||
2064 is_free(direntries + i))
2065 continue;
2067 subret = parse_long_name(&lfn, direntries + i);
2068 if (subret < 0) {
2069 fprintf(stderr, "Error in long name\n");
2070 goto fail;
2072 if (subret == 0 || is_free(direntries + i))
2073 continue;
2075 if (fat_chksum(direntries+i) != lfn.checksum) {
2076 subret = parse_short_name(s, &lfn, direntries + i);
2077 if (subret < 0) {
2078 fprintf(stderr, "Error in short name (%d)\n", subret);
2079 goto fail;
2081 if (subret > 0 || !strcmp((char*)lfn.name, ".")
2082 || !strcmp((char*)lfn.name, ".."))
2083 continue;
2085 lfn.checksum = 0x100; /* cannot use long name twice */
2087 if (!valid_filename(lfn.name)) {
2088 fprintf(stderr, "Invalid file name\n");
2089 goto fail;
2091 if (path_len + 1 + lfn.len >= PATH_MAX) {
2092 fprintf(stderr, "Name too long: %s/%s\n", path, lfn.name);
2093 goto fail;
2095 pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1,
2096 (char*)lfn.name);
2098 if (is_directory(direntries + i)) {
2099 if (begin_of_direntry(direntries + i) == 0) {
2100 DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i));
2101 goto fail;
2103 cluster_count = check_directory_consistency(s,
2104 begin_of_direntry(direntries + i), path2);
2105 if (cluster_count == 0) {
2106 DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i));
2107 goto fail;
2109 } else if (is_file(direntries + i)) {
2110 /* check file size with FAT */
2111 cluster_count = get_cluster_count_for_direntry(s, direntries + i, path2);
2112 if (cluster_count !=
2113 DIV_ROUND_UP(le32_to_cpu(direntries[i].size), s->cluster_size)) {
2114 DLOG(fprintf(stderr, "Cluster count mismatch\n"));
2115 goto fail;
2117 } else
2118 abort(); /* cluster_count = 0; */
2120 ret += cluster_count;
2123 cluster_num = modified_fat_get(s, cluster_num);
2124 } while(!fat_eof(s, cluster_num));
2126 g_free(cluster);
2127 return ret;
2130 /* returns 1 on success */
2131 static int is_consistent(BDRVVVFATState* s)
2133 int i, check;
2134 int used_clusters_count = 0;
2136 DLOG(checkpoint());
2138 * - get modified FAT
2139 * - compare the two FATs (TODO)
2140 * - get buffer for marking used clusters
2141 * - recurse direntries from root (using bs->bdrv_pread to make
2142 * sure to get the new data)
2143 * - check that the FAT agrees with the size
2144 * - count the number of clusters occupied by this directory and
2145 * its files
2146 * - check that the cumulative used cluster count agrees with the
2147 * FAT
2148 * - if all is fine, return number of used clusters
2150 if (s->fat2 == NULL) {
2151 int size = 0x200 * s->sectors_per_fat;
2152 s->fat2 = g_malloc(size);
2153 memcpy(s->fat2, s->fat.pointer, size);
2155 check = vvfat_read(s->bs,
2156 s->offset_to_fat, s->fat2, s->sectors_per_fat);
2157 if (check) {
2158 fprintf(stderr, "Could not copy fat\n");
2159 return 0;
2161 assert (s->used_clusters);
2162 for (i = 0; i < sector2cluster(s, s->sector_count); i++)
2163 s->used_clusters[i] &= ~USED_ANY;
2165 clear_commits(s);
2167 /* mark every mapped file/directory as deleted.
2168 * (check_directory_consistency() will unmark those still present). */
2169 if (s->qcow)
2170 for (i = 0; i < s->mapping.next; i++) {
2171 mapping_t* mapping = array_get(&(s->mapping), i);
2172 if (mapping->first_mapping_index < 0)
2173 mapping->mode |= MODE_DELETED;
2176 used_clusters_count = check_directory_consistency(s, 0, s->path);
2177 if (used_clusters_count <= 0) {
2178 DLOG(fprintf(stderr, "problem in directory\n"));
2179 return 0;
2182 check = s->last_cluster_of_root_directory;
2183 for (i = check; i < sector2cluster(s, s->sector_count); i++) {
2184 if (modified_fat_get(s, i)) {
2185 if(!s->used_clusters[i]) {
2186 DLOG(fprintf(stderr, "FAT was modified (%d), but cluster is not used?\n", i));
2187 return 0;
2189 check++;
2192 if (s->used_clusters[i] == USED_ALLOCATED) {
2193 /* allocated, but not used... */
2194 DLOG(fprintf(stderr, "unused, modified cluster: %d\n", i));
2195 return 0;
2199 if (check != used_clusters_count)
2200 return 0;
2202 return used_clusters_count;
2205 static inline void adjust_mapping_indices(BDRVVVFATState* s,
2206 int offset, int adjust)
2208 int i;
2210 for (i = 0; i < s->mapping.next; i++) {
2211 mapping_t* mapping = array_get(&(s->mapping), i);
2213 #define ADJUST_MAPPING_INDEX(name) \
2214 if (mapping->name >= offset) \
2215 mapping->name += adjust
2217 ADJUST_MAPPING_INDEX(first_mapping_index);
2218 if (mapping->mode & MODE_DIRECTORY)
2219 ADJUST_MAPPING_INDEX(info.dir.parent_mapping_index);
2223 /* insert or update mapping */
2224 static mapping_t* insert_mapping(BDRVVVFATState* s,
2225 uint32_t begin, uint32_t end)
2228 * - find mapping where mapping->begin >= begin,
2229 * - if mapping->begin > begin: insert
2230 * - adjust all references to mappings!
2231 * - else: adjust
2232 * - replace name
2234 int index = find_mapping_for_cluster_aux(s, begin, 0, s->mapping.next);
2235 mapping_t* mapping = NULL;
2236 mapping_t* first_mapping = array_get(&(s->mapping), 0);
2238 if (index < s->mapping.next && (mapping = array_get(&(s->mapping), index))
2239 && mapping->begin < begin) {
2240 mapping->end = begin;
2241 index++;
2242 mapping = array_get(&(s->mapping), index);
2244 if (index >= s->mapping.next || mapping->begin > begin) {
2245 mapping = array_insert(&(s->mapping), index, 1);
2246 mapping->path = NULL;
2247 adjust_mapping_indices(s, index, +1);
2250 mapping->begin = begin;
2251 mapping->end = end;
2253 DLOG(mapping_t* next_mapping;
2254 assert(index + 1 >= s->mapping.next ||
2255 ((next_mapping = array_get(&(s->mapping), index + 1)) &&
2256 next_mapping->begin >= end)));
2258 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
2259 s->current_mapping = array_get(&(s->mapping),
2260 s->current_mapping - first_mapping);
2262 return mapping;
2265 static int remove_mapping(BDRVVVFATState* s, int mapping_index)
2267 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
2268 mapping_t* first_mapping = array_get(&(s->mapping), 0);
2270 /* free mapping */
2271 if (mapping->first_mapping_index < 0) {
2272 g_free(mapping->path);
2275 /* remove from s->mapping */
2276 array_remove(&(s->mapping), mapping_index);
2278 /* adjust all references to mappings */
2279 adjust_mapping_indices(s, mapping_index, -1);
2281 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
2282 s->current_mapping = array_get(&(s->mapping),
2283 s->current_mapping - first_mapping);
2285 return 0;
2288 static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust)
2290 int i;
2291 for (i = 0; i < s->mapping.next; i++) {
2292 mapping_t* mapping = array_get(&(s->mapping), i);
2293 if (mapping->dir_index >= offset)
2294 mapping->dir_index += adjust;
2295 if ((mapping->mode & MODE_DIRECTORY) &&
2296 mapping->info.dir.first_dir_index >= offset)
2297 mapping->info.dir.first_dir_index += adjust;
2301 static direntry_t* insert_direntries(BDRVVVFATState* s,
2302 int dir_index, int count)
2305 * make room in s->directory,
2306 * adjust_dirindices
2308 direntry_t* result = array_insert(&(s->directory), dir_index, count);
2309 if (result == NULL)
2310 return NULL;
2311 adjust_dirindices(s, dir_index, count);
2312 return result;
2315 static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)
2317 int ret = array_remove_slice(&(s->directory), dir_index, count);
2318 if (ret)
2319 return ret;
2320 adjust_dirindices(s, dir_index, -count);
2321 return 0;
2325 * Adapt the mappings of the cluster chain starting at first cluster
2326 * (i.e. if a file starts at first_cluster, the chain is followed according
2327 * to the modified fat, and the corresponding entries in s->mapping are
2328 * adjusted)
2330 static int commit_mappings(BDRVVVFATState* s,
2331 uint32_t first_cluster, int dir_index)
2333 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2334 direntry_t* direntry = array_get(&(s->directory), dir_index);
2335 uint32_t cluster = first_cluster;
2337 vvfat_close_current_file(s);
2339 assert(mapping);
2340 assert(mapping->begin == first_cluster);
2341 mapping->first_mapping_index = -1;
2342 mapping->dir_index = dir_index;
2343 mapping->mode = (dir_index <= 0 || is_directory(direntry)) ?
2344 MODE_DIRECTORY : MODE_NORMAL;
2346 while (!fat_eof(s, cluster)) {
2347 uint32_t c, c1;
2349 for (c = cluster, c1 = modified_fat_get(s, c); c + 1 == c1;
2350 c = c1, c1 = modified_fat_get(s, c1));
2352 c++;
2353 if (c > mapping->end) {
2354 int index = array_index(&(s->mapping), mapping);
2355 int i, max_i = s->mapping.next - index;
2356 for (i = 1; i < max_i && mapping[i].begin < c; i++);
2357 while (--i > 0)
2358 remove_mapping(s, index + 1);
2360 assert(mapping == array_get(&(s->mapping), s->mapping.next - 1)
2361 || mapping[1].begin >= c);
2362 mapping->end = c;
2364 if (!fat_eof(s, c1)) {
2365 int i = find_mapping_for_cluster_aux(s, c1, 0, s->mapping.next);
2366 mapping_t* next_mapping = i >= s->mapping.next ? NULL :
2367 array_get(&(s->mapping), i);
2369 if (next_mapping == NULL || next_mapping->begin > c1) {
2370 int i1 = array_index(&(s->mapping), mapping);
2372 next_mapping = insert_mapping(s, c1, c1+1);
2374 if (c1 < c)
2375 i1++;
2376 mapping = array_get(&(s->mapping), i1);
2379 next_mapping->dir_index = mapping->dir_index;
2380 next_mapping->first_mapping_index =
2381 mapping->first_mapping_index < 0 ?
2382 array_index(&(s->mapping), mapping) :
2383 mapping->first_mapping_index;
2384 next_mapping->path = mapping->path;
2385 next_mapping->mode = mapping->mode;
2386 next_mapping->read_only = mapping->read_only;
2387 if (mapping->mode & MODE_DIRECTORY) {
2388 next_mapping->info.dir.parent_mapping_index =
2389 mapping->info.dir.parent_mapping_index;
2390 next_mapping->info.dir.first_dir_index =
2391 mapping->info.dir.first_dir_index +
2392 0x10 * s->sectors_per_cluster *
2393 (mapping->end - mapping->begin);
2394 } else
2395 next_mapping->info.file.offset = mapping->info.file.offset +
2396 mapping->end - mapping->begin;
2398 mapping = next_mapping;
2401 cluster = c1;
2404 return 0;
2407 static int commit_direntries(BDRVVVFATState* s,
2408 int dir_index, int parent_mapping_index)
2410 direntry_t* direntry = array_get(&(s->directory), dir_index);
2411 uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);
2412 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2413 int factor = 0x10 * s->sectors_per_cluster;
2414 int old_cluster_count, new_cluster_count;
2415 int current_dir_index;
2416 int first_dir_index;
2417 int ret, i;
2418 uint32_t c;
2420 assert(direntry);
2421 assert(mapping);
2422 assert(mapping->begin == first_cluster);
2423 assert(mapping->info.dir.first_dir_index < s->directory.next);
2424 assert(mapping->mode & MODE_DIRECTORY);
2425 assert(dir_index == 0 || is_directory(direntry));
2427 DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n",
2428 mapping->path, parent_mapping_index));
2430 current_dir_index = mapping->info.dir.first_dir_index;
2431 first_dir_index = current_dir_index;
2432 mapping->info.dir.parent_mapping_index = parent_mapping_index;
2434 if (first_cluster == 0) {
2435 old_cluster_count = new_cluster_count =
2436 s->last_cluster_of_root_directory;
2437 } else {
2438 for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2439 c = fat_get(s, c))
2440 old_cluster_count++;
2442 for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2443 c = modified_fat_get(s, c))
2444 new_cluster_count++;
2447 if (new_cluster_count > old_cluster_count) {
2448 if (insert_direntries(s,
2449 current_dir_index + factor * old_cluster_count,
2450 factor * (new_cluster_count - old_cluster_count)) == NULL)
2451 return -1;
2452 } else if (new_cluster_count < old_cluster_count)
2453 remove_direntries(s,
2454 current_dir_index + factor * new_cluster_count,
2455 factor * (old_cluster_count - new_cluster_count));
2457 for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {
2458 direntry_t *first_direntry;
2459 void* direntry = array_get(&(s->directory), current_dir_index);
2460 int ret = vvfat_read(s->bs, cluster2sector(s, c), direntry,
2461 s->sectors_per_cluster);
2462 if (ret)
2463 return ret;
2465 /* The first directory entry on the filesystem is the volume name */
2466 first_direntry = (direntry_t*) s->directory.pointer;
2467 assert(!memcmp(first_direntry->name, s->volume_label, 11));
2469 current_dir_index += factor;
2472 ret = commit_mappings(s, first_cluster, dir_index);
2473 if (ret)
2474 return ret;
2476 /* recurse */
2477 for (i = 0; i < factor * new_cluster_count; i++) {
2478 direntry = array_get(&(s->directory), first_dir_index + i);
2479 if (is_directory(direntry) && !is_dot(direntry)) {
2480 mapping = find_mapping_for_cluster(s, first_cluster);
2481 if (mapping == NULL) {
2482 return -1;
2484 assert(mapping->mode & MODE_DIRECTORY);
2485 ret = commit_direntries(s, first_dir_index + i,
2486 array_index(&(s->mapping), mapping));
2487 if (ret)
2488 return ret;
2492 return 0;
2495 /* commit one file (adjust contents, adjust mapping),
2496 return first_mapping_index */
2497 static int commit_one_file(BDRVVVFATState* s,
2498 int dir_index, uint32_t offset)
2500 direntry_t* direntry = array_get(&(s->directory), dir_index);
2501 uint32_t c = begin_of_direntry(direntry);
2502 uint32_t first_cluster = c;
2503 mapping_t* mapping = find_mapping_for_cluster(s, c);
2504 uint32_t size = filesize_of_direntry(direntry);
2505 char *cluster;
2506 uint32_t i;
2507 int fd = 0;
2509 assert(offset < size);
2510 assert((offset % s->cluster_size) == 0);
2512 if (mapping == NULL) {
2513 return -1;
2516 for (i = s->cluster_size; i < offset; i += s->cluster_size)
2517 c = modified_fat_get(s, c);
2519 fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
2520 if (fd < 0) {
2521 fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
2522 strerror(errno), errno);
2523 return fd;
2525 if (offset > 0) {
2526 if (lseek(fd, offset, SEEK_SET) != offset) {
2527 qemu_close(fd);
2528 return -3;
2532 cluster = g_malloc(s->cluster_size);
2534 while (offset < size) {
2535 uint32_t c1;
2536 int rest_size = (size - offset > s->cluster_size ?
2537 s->cluster_size : size - offset);
2538 int ret;
2540 c1 = modified_fat_get(s, c);
2542 assert((size - offset == 0 && fat_eof(s, c)) ||
2543 (size > offset && c >=2 && !fat_eof(s, c)));
2545 ret = vvfat_read(s->bs, cluster2sector(s, c),
2546 (uint8_t*)cluster, DIV_ROUND_UP(rest_size, 0x200));
2548 if (ret < 0) {
2549 qemu_close(fd);
2550 g_free(cluster);
2551 return ret;
2554 if (write(fd, cluster, rest_size) < 0) {
2555 qemu_close(fd);
2556 g_free(cluster);
2557 return -2;
2560 offset += rest_size;
2561 c = c1;
2564 if (ftruncate(fd, size)) {
2565 perror("ftruncate()");
2566 qemu_close(fd);
2567 g_free(cluster);
2568 return -4;
2570 qemu_close(fd);
2571 g_free(cluster);
2573 return commit_mappings(s, first_cluster, dir_index);
2576 #ifdef DEBUG
2577 /* test, if all mappings point to valid direntries */
2578 static void check1(BDRVVVFATState* s)
2580 int i;
2581 for (i = 0; i < s->mapping.next; i++) {
2582 mapping_t* mapping = array_get(&(s->mapping), i);
2583 if (mapping->mode & MODE_DELETED) {
2584 fprintf(stderr, "deleted\n");
2585 continue;
2587 assert(mapping->dir_index < s->directory.next);
2588 direntry_t* direntry = array_get(&(s->directory), mapping->dir_index);
2589 assert(mapping->begin == begin_of_direntry(direntry) || mapping->first_mapping_index >= 0);
2590 if (mapping->mode & MODE_DIRECTORY) {
2591 assert(mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster * (mapping->end - mapping->begin) <= s->directory.next);
2592 assert((mapping->info.dir.first_dir_index % (0x10 * s->sectors_per_cluster)) == 0);
2597 /* test, if all direntries have mappings */
2598 static void check2(BDRVVVFATState* s)
2600 int i;
2601 int first_mapping = -1;
2603 for (i = 0; i < s->directory.next; i++) {
2604 direntry_t* direntry = array_get(&(s->directory), i);
2606 if (is_short_name(direntry) && begin_of_direntry(direntry)) {
2607 mapping_t* mapping = find_mapping_for_cluster(s, begin_of_direntry(direntry));
2608 assert(mapping);
2609 assert(mapping->dir_index == i || is_dot(direntry));
2610 assert(mapping->begin == begin_of_direntry(direntry) || is_dot(direntry));
2613 if ((i % (0x10 * s->sectors_per_cluster)) == 0) {
2614 /* cluster start */
2615 int j, count = 0;
2617 for (j = 0; j < s->mapping.next; j++) {
2618 mapping_t* mapping = array_get(&(s->mapping), j);
2619 if (mapping->mode & MODE_DELETED)
2620 continue;
2621 if (mapping->mode & MODE_DIRECTORY) {
2622 if (mapping->info.dir.first_dir_index <= i && mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster > i) {
2623 assert(++count == 1);
2624 if (mapping->first_mapping_index == -1)
2625 first_mapping = array_index(&(s->mapping), mapping);
2626 else
2627 assert(first_mapping == mapping->first_mapping_index);
2628 if (mapping->info.dir.parent_mapping_index < 0)
2629 assert(j == 0);
2630 else {
2631 mapping_t* parent = array_get(&(s->mapping), mapping->info.dir.parent_mapping_index);
2632 assert(parent->mode & MODE_DIRECTORY);
2633 assert(parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index);
2638 if (count == 0)
2639 first_mapping = -1;
2643 #endif
2645 static int handle_renames_and_mkdirs(BDRVVVFATState* s)
2647 int i;
2649 #ifdef DEBUG
2650 fprintf(stderr, "handle_renames\n");
2651 for (i = 0; i < s->commits.next; i++) {
2652 commit_t* commit = array_get(&(s->commits), i);
2653 fprintf(stderr, "%d, %s (%d, %d)\n", i, commit->path ? commit->path : "(null)", commit->param.rename.cluster, commit->action);
2655 #endif
2657 for (i = 0; i < s->commits.next;) {
2658 commit_t* commit = array_get(&(s->commits), i);
2659 if (commit->action == ACTION_RENAME) {
2660 mapping_t* mapping = find_mapping_for_cluster(s,
2661 commit->param.rename.cluster);
2662 char *old_path;
2664 if (mapping == NULL) {
2665 return -1;
2667 old_path = mapping->path;
2668 assert(commit->path);
2669 mapping->path = commit->path;
2670 if (rename(old_path, mapping->path))
2671 return -2;
2673 if (mapping->mode & MODE_DIRECTORY) {
2674 int l1 = strlen(mapping->path);
2675 int l2 = strlen(old_path);
2676 int diff = l1 - l2;
2677 direntry_t* direntry = array_get(&(s->directory),
2678 mapping->info.dir.first_dir_index);
2679 uint32_t c = mapping->begin;
2680 int i = 0;
2682 /* recurse */
2683 while (!fat_eof(s, c)) {
2684 do {
2685 direntry_t* d = direntry + i;
2687 if (is_file(d) || (is_directory(d) && !is_dot(d))) {
2688 int l;
2689 char *new_path;
2690 mapping_t* m = find_mapping_for_cluster(s,
2691 begin_of_direntry(d));
2692 if (m == NULL) {
2693 return -1;
2695 l = strlen(m->path);
2696 new_path = g_malloc(l + diff + 1);
2698 assert(!strncmp(m->path, mapping->path, l2));
2700 pstrcpy(new_path, l + diff + 1, mapping->path);
2701 pstrcpy(new_path + l1, l + diff + 1 - l1,
2702 m->path + l2);
2704 schedule_rename(s, m->begin, new_path);
2706 i++;
2707 } while((i % (0x10 * s->sectors_per_cluster)) != 0);
2708 c = fat_get(s, c);
2712 g_free(old_path);
2713 array_remove(&(s->commits), i);
2714 continue;
2715 } else if (commit->action == ACTION_MKDIR) {
2716 mapping_t* mapping;
2717 int j, parent_path_len;
2719 #ifdef __MINGW32__
2720 if (mkdir(commit->path))
2721 return -5;
2722 #else
2723 if (mkdir(commit->path, 0755))
2724 return -5;
2725 #endif
2727 mapping = insert_mapping(s, commit->param.mkdir.cluster,
2728 commit->param.mkdir.cluster + 1);
2729 if (mapping == NULL)
2730 return -6;
2732 mapping->mode = MODE_DIRECTORY;
2733 mapping->read_only = 0;
2734 mapping->path = commit->path;
2735 j = s->directory.next;
2736 assert(j);
2737 insert_direntries(s, s->directory.next,
2738 0x10 * s->sectors_per_cluster);
2739 mapping->info.dir.first_dir_index = j;
2741 parent_path_len = strlen(commit->path)
2742 - strlen(get_basename(commit->path)) - 1;
2743 for (j = 0; j < s->mapping.next; j++) {
2744 mapping_t* m = array_get(&(s->mapping), j);
2745 if (m->first_mapping_index < 0 && m != mapping &&
2746 !strncmp(m->path, mapping->path, parent_path_len) &&
2747 strlen(m->path) == parent_path_len)
2748 break;
2750 assert(j < s->mapping.next);
2751 mapping->info.dir.parent_mapping_index = j;
2753 array_remove(&(s->commits), i);
2754 continue;
2757 i++;
2759 return 0;
2763 * TODO: make sure that the short name is not matching *another* file
2765 static int handle_commits(BDRVVVFATState* s)
2767 int i, fail = 0;
2769 vvfat_close_current_file(s);
2771 for (i = 0; !fail && i < s->commits.next; i++) {
2772 commit_t* commit = array_get(&(s->commits), i);
2773 switch(commit->action) {
2774 case ACTION_RENAME: case ACTION_MKDIR:
2775 abort();
2776 fail = -2;
2777 break;
2778 case ACTION_WRITEOUT: {
2779 #ifndef NDEBUG
2780 /* these variables are only used by assert() below */
2781 direntry_t* entry = array_get(&(s->directory),
2782 commit->param.writeout.dir_index);
2783 uint32_t begin = begin_of_direntry(entry);
2784 mapping_t* mapping = find_mapping_for_cluster(s, begin);
2785 #endif
2787 assert(mapping);
2788 assert(mapping->begin == begin);
2789 assert(commit->path == NULL);
2791 if (commit_one_file(s, commit->param.writeout.dir_index,
2792 commit->param.writeout.modified_offset))
2793 fail = -3;
2795 break;
2797 case ACTION_NEW_FILE: {
2798 int begin = commit->param.new_file.first_cluster;
2799 mapping_t* mapping = find_mapping_for_cluster(s, begin);
2800 direntry_t* entry;
2801 int i;
2803 /* find direntry */
2804 for (i = 0; i < s->directory.next; i++) {
2805 entry = array_get(&(s->directory), i);
2806 if (is_file(entry) && begin_of_direntry(entry) == begin)
2807 break;
2810 if (i >= s->directory.next) {
2811 fail = -6;
2812 continue;
2815 /* make sure there exists an initial mapping */
2816 if (mapping && mapping->begin != begin) {
2817 mapping->end = begin;
2818 mapping = NULL;
2820 if (mapping == NULL) {
2821 mapping = insert_mapping(s, begin, begin+1);
2823 /* most members will be fixed in commit_mappings() */
2824 assert(commit->path);
2825 mapping->path = commit->path;
2826 mapping->read_only = 0;
2827 mapping->mode = MODE_NORMAL;
2828 mapping->info.file.offset = 0;
2830 if (commit_one_file(s, i, 0))
2831 fail = -7;
2833 break;
2835 default:
2836 abort();
2839 if (i > 0 && array_remove_slice(&(s->commits), 0, i))
2840 return -1;
2841 return fail;
2844 static int handle_deletes(BDRVVVFATState* s)
2846 int i, deferred = 1, deleted = 1;
2848 /* delete files corresponding to mappings marked as deleted */
2849 /* handle DELETEs and unused mappings (modified_fat_get(s, mapping->begin) == 0) */
2850 while (deferred && deleted) {
2851 deferred = 0;
2852 deleted = 0;
2854 for (i = 1; i < s->mapping.next; i++) {
2855 mapping_t* mapping = array_get(&(s->mapping), i);
2856 if (mapping->mode & MODE_DELETED) {
2857 direntry_t* entry = array_get(&(s->directory),
2858 mapping->dir_index);
2860 if (is_free(entry)) {
2861 /* remove file/directory */
2862 if (mapping->mode & MODE_DIRECTORY) {
2863 int j, next_dir_index = s->directory.next,
2864 first_dir_index = mapping->info.dir.first_dir_index;
2866 if (rmdir(mapping->path) < 0) {
2867 if (errno == ENOTEMPTY) {
2868 deferred++;
2869 continue;
2870 } else
2871 return -5;
2874 for (j = 1; j < s->mapping.next; j++) {
2875 mapping_t* m = array_get(&(s->mapping), j);
2876 if (m->mode & MODE_DIRECTORY &&
2877 m->info.dir.first_dir_index >
2878 first_dir_index &&
2879 m->info.dir.first_dir_index <
2880 next_dir_index)
2881 next_dir_index =
2882 m->info.dir.first_dir_index;
2884 remove_direntries(s, first_dir_index,
2885 next_dir_index - first_dir_index);
2887 deleted++;
2889 } else {
2890 if (unlink(mapping->path))
2891 return -4;
2892 deleted++;
2894 DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry));
2895 remove_mapping(s, i);
2900 return 0;
2904 * synchronize mapping with new state:
2906 * - copy FAT (with bdrv_pread)
2907 * - mark all filenames corresponding to mappings as deleted
2908 * - recurse direntries from root (using bs->bdrv_pread)
2909 * - delete files corresponding to mappings marked as deleted
2911 static int do_commit(BDRVVVFATState* s)
2913 int ret = 0;
2915 /* the real meat are the commits. Nothing to do? Move along! */
2916 if (s->commits.next == 0)
2917 return 0;
2919 vvfat_close_current_file(s);
2921 ret = handle_renames_and_mkdirs(s);
2922 if (ret) {
2923 fprintf(stderr, "Error handling renames (%d)\n", ret);
2924 abort();
2925 return ret;
2928 /* copy FAT (with bdrv_pread) */
2929 memcpy(s->fat.pointer, s->fat2, 0x200 * s->sectors_per_fat);
2931 /* recurse direntries from root (using bs->bdrv_pread) */
2932 ret = commit_direntries(s, 0, -1);
2933 if (ret) {
2934 fprintf(stderr, "Fatal: error while committing (%d)\n", ret);
2935 abort();
2936 return ret;
2939 ret = handle_commits(s);
2940 if (ret) {
2941 fprintf(stderr, "Error handling commits (%d)\n", ret);
2942 abort();
2943 return ret;
2946 ret = handle_deletes(s);
2947 if (ret) {
2948 fprintf(stderr, "Error deleting\n");
2949 abort();
2950 return ret;
2953 bdrv_make_empty(s->qcow, NULL);
2955 memset(s->used_clusters, 0, sector2cluster(s, s->sector_count));
2957 DLOG(checkpoint());
2958 return 0;
2961 static int try_commit(BDRVVVFATState* s)
2963 vvfat_close_current_file(s);
2964 DLOG(checkpoint());
2965 if(!is_consistent(s))
2966 return -1;
2967 return do_commit(s);
2970 static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
2971 const uint8_t *buf, int nb_sectors)
2973 BDRVVVFATState *s = bs->opaque;
2974 int i, ret;
2976 DLOG(checkpoint());
2978 /* Check if we're operating in read-only mode */
2979 if (s->qcow == NULL) {
2980 return -EACCES;
2983 vvfat_close_current_file(s);
2986 * Some sanity checks:
2987 * - do not allow writing to the boot sector
2990 if (sector_num < s->offset_to_fat)
2991 return -1;
2993 for (i = sector2cluster(s, sector_num);
2994 i <= sector2cluster(s, sector_num + nb_sectors - 1);) {
2995 mapping_t* mapping = find_mapping_for_cluster(s, i);
2996 if (mapping) {
2997 if (mapping->read_only) {
2998 fprintf(stderr, "Tried to write to write-protected file %s\n",
2999 mapping->path);
3000 return -1;
3003 if (mapping->mode & MODE_DIRECTORY) {
3004 int begin = cluster2sector(s, i);
3005 int end = begin + s->sectors_per_cluster, k;
3006 int dir_index;
3007 const direntry_t* direntries;
3008 long_file_name lfn;
3010 lfn_init(&lfn);
3012 if (begin < sector_num)
3013 begin = sector_num;
3014 if (end > sector_num + nb_sectors)
3015 end = sector_num + nb_sectors;
3016 dir_index = mapping->dir_index +
3017 0x10 * (begin - mapping->begin * s->sectors_per_cluster);
3018 direntries = (direntry_t*)(buf + 0x200 * (begin - sector_num));
3020 for (k = 0; k < (end - begin) * 0x10; k++) {
3021 /* no access to the direntry of a read-only file */
3022 if (is_short_name(direntries + k) &&
3023 (direntries[k].attributes & 1)) {
3024 if (memcmp(direntries + k,
3025 array_get(&(s->directory), dir_index + k),
3026 sizeof(direntry_t))) {
3027 warn_report("tried to write to write-protected "
3028 "file");
3029 return -1;
3034 i = mapping->end;
3035 } else
3036 i++;
3040 * Use qcow backend. Commit later.
3042 DLOG(fprintf(stderr, "Write to qcow backend: %d + %d\n", (int)sector_num, nb_sectors));
3043 ret = bdrv_pwrite(s->qcow, sector_num * BDRV_SECTOR_SIZE, buf,
3044 nb_sectors * BDRV_SECTOR_SIZE);
3045 if (ret < 0) {
3046 fprintf(stderr, "Error writing to qcow backend\n");
3047 return ret;
3050 for (i = sector2cluster(s, sector_num);
3051 i <= sector2cluster(s, sector_num + nb_sectors - 1); i++)
3052 if (i >= 0)
3053 s->used_clusters[i] |= USED_ALLOCATED;
3055 DLOG(checkpoint());
3056 /* TODO: add timeout */
3057 try_commit(s);
3059 DLOG(checkpoint());
3060 return 0;
3063 static int coroutine_fn
3064 vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3065 QEMUIOVector *qiov, int flags)
3067 int ret;
3068 BDRVVVFATState *s = bs->opaque;
3069 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
3070 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3071 void *buf;
3073 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
3074 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
3076 buf = g_try_malloc(bytes);
3077 if (bytes && buf == NULL) {
3078 return -ENOMEM;
3080 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3082 qemu_co_mutex_lock(&s->lock);
3083 ret = vvfat_write(bs, sector_num, buf, nb_sectors);
3084 qemu_co_mutex_unlock(&s->lock);
3086 g_free(buf);
3088 return ret;
3091 static int coroutine_fn vvfat_co_block_status(BlockDriverState *bs,
3092 bool want_zero, int64_t offset,
3093 int64_t bytes, int64_t *n,
3094 int64_t *map,
3095 BlockDriverState **file)
3097 *n = bytes;
3098 return BDRV_BLOCK_DATA;
3101 static int coroutine_fn
3102 write_target_commit(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3103 QEMUIOVector *qiov, int flags)
3105 int ret;
3107 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
3108 qemu_co_mutex_lock(&s->lock);
3109 ret = try_commit(s);
3110 qemu_co_mutex_unlock(&s->lock);
3112 return ret;
3115 static BlockDriver vvfat_write_target = {
3116 .format_name = "vvfat_write_target",
3117 .instance_size = sizeof(void*),
3118 .bdrv_co_pwritev = write_target_commit,
3121 static void vvfat_qcow_options(BdrvChildRole role, bool parent_is_format,
3122 int *child_flags, QDict *child_options,
3123 int parent_flags, QDict *parent_options)
3125 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "off");
3126 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
3127 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
3130 static const BdrvChildClass child_vvfat_qcow = {
3131 .parent_is_bds = true,
3132 .inherit_options = vvfat_qcow_options,
3135 static int enable_write_target(BlockDriverState *bs, Error **errp)
3137 BDRVVVFATState *s = bs->opaque;
3138 BlockDriver *bdrv_qcow = NULL;
3139 BlockDriverState *backing;
3140 QemuOpts *opts = NULL;
3141 int ret;
3142 int size = sector2cluster(s, s->sector_count);
3143 QDict *options;
3145 s->used_clusters = calloc(size, 1);
3147 array_init(&(s->commits), sizeof(commit_t));
3149 s->qcow_filename = g_malloc(PATH_MAX);
3150 ret = get_tmp_filename(s->qcow_filename, PATH_MAX);
3151 if (ret < 0) {
3152 error_setg_errno(errp, -ret, "can't create temporary file");
3153 goto err;
3156 bdrv_qcow = bdrv_find_format("qcow");
3157 if (!bdrv_qcow) {
3158 error_setg(errp, "Failed to locate qcow driver");
3159 ret = -ENOENT;
3160 goto err;
3163 opts = qemu_opts_create(bdrv_qcow->create_opts, NULL, 0, &error_abort);
3164 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s->sector_count * 512,
3165 &error_abort);
3166 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, "fat:", &error_abort);
3168 ret = bdrv_create(bdrv_qcow, s->qcow_filename, opts, errp);
3169 qemu_opts_del(opts);
3170 if (ret < 0) {
3171 goto err;
3174 options = qdict_new();
3175 qdict_put_str(options, "write-target.driver", "qcow");
3176 s->qcow = bdrv_open_child(s->qcow_filename, options, "write-target", bs,
3177 &child_vvfat_qcow,
3178 BDRV_CHILD_DATA | BDRV_CHILD_METADATA,
3179 false, errp);
3180 qobject_unref(options);
3181 if (!s->qcow) {
3182 ret = -EINVAL;
3183 goto err;
3186 #ifndef _WIN32
3187 unlink(s->qcow_filename);
3188 #endif
3190 backing = bdrv_new_open_driver(&vvfat_write_target, NULL, BDRV_O_ALLOW_RDWR,
3191 &error_abort);
3192 *(void**) backing->opaque = s;
3194 bdrv_set_backing_hd(s->bs, backing, &error_abort);
3195 bdrv_unref(backing);
3197 return 0;
3199 err:
3200 g_free(s->qcow_filename);
3201 s->qcow_filename = NULL;
3202 return ret;
3205 static void vvfat_child_perm(BlockDriverState *bs, BdrvChild *c,
3206 BdrvChildRole role,
3207 BlockReopenQueue *reopen_queue,
3208 uint64_t perm, uint64_t shared,
3209 uint64_t *nperm, uint64_t *nshared)
3211 BDRVVVFATState *s = bs->opaque;
3213 assert(c == s->qcow || (role & BDRV_CHILD_COW));
3215 if (c == s->qcow) {
3216 /* This is a private node, nobody should try to attach to it */
3217 *nperm = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
3218 *nshared = BLK_PERM_WRITE_UNCHANGED;
3219 } else {
3220 /* The backing file is there so 'commit' can use it. vvfat doesn't
3221 * access it in any way. */
3222 *nperm = 0;
3223 *nshared = BLK_PERM_ALL;
3227 static void vvfat_close(BlockDriverState *bs)
3229 BDRVVVFATState *s = bs->opaque;
3231 vvfat_close_current_file(s);
3232 array_free(&(s->fat));
3233 array_free(&(s->directory));
3234 array_free(&(s->mapping));
3235 g_free(s->cluster_buffer);
3237 if (s->qcow) {
3238 migrate_del_blocker(s->migration_blocker);
3239 error_free(s->migration_blocker);
3243 static const char *const vvfat_strong_runtime_opts[] = {
3244 "dir",
3245 "fat-type",
3246 "floppy",
3247 "label",
3248 "rw",
3250 NULL
3253 static BlockDriver bdrv_vvfat = {
3254 .format_name = "vvfat",
3255 .protocol_name = "fat",
3256 .instance_size = sizeof(BDRVVVFATState),
3258 .bdrv_parse_filename = vvfat_parse_filename,
3259 .bdrv_file_open = vvfat_open,
3260 .bdrv_refresh_limits = vvfat_refresh_limits,
3261 .bdrv_close = vvfat_close,
3262 .bdrv_child_perm = vvfat_child_perm,
3264 .bdrv_co_preadv = vvfat_co_preadv,
3265 .bdrv_co_pwritev = vvfat_co_pwritev,
3266 .bdrv_co_block_status = vvfat_co_block_status,
3268 .strong_runtime_opts = vvfat_strong_runtime_opts,
3271 static void bdrv_vvfat_init(void)
3273 bdrv_register(&bdrv_vvfat);
3276 block_init(bdrv_vvfat_init);
3278 #ifdef DEBUG
3279 static void checkpoint(void)
3281 assert(((mapping_t*)array_get(&(vvv->mapping), 0))->end == 2);
3282 check1(vvv);
3283 check2(vvv);
3284 assert(!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode & MODE_DIRECTORY));
3286 #endif