vvfat: initialize memory after allocating it
[qemu/kevin.git] / block / vvfat.c
blob6b11596abfe0990d596eaaf4fc4ca426c72b678c
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.
25 #include "qemu/osdep.h"
26 #include <dirent.h>
27 #include "qapi/error.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
30 #include "qemu/bswap.h"
31 #include "migration/blocker.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qapi/qmp/qstring.h"
34 #include "qemu/cutils.h"
36 #ifndef S_IWGRP
37 #define S_IWGRP 0
38 #endif
39 #ifndef S_IWOTH
40 #define S_IWOTH 0
41 #endif
43 /* TODO: add ":bootsector=blabla.img:" */
44 /* LATER TODO: add automatic boot sector generation from
45 BOOTEASY.ASM and Ranish Partition Manager
46 Note that DOS assumes the system files to be the first files in the
47 file system (test if the boot sector still relies on that fact)! */
48 /* MAYBE TODO: write block-visofs.c */
49 /* TODO: call try_commit() only after a timeout */
51 /* #define DEBUG */
53 #ifdef DEBUG
55 #define DLOG(a) a
57 static void checkpoint(void);
59 #ifdef __MINGW32__
60 void nonono(const char* file, int line, const char* msg) {
61 fprintf(stderr, "Nonono! %s:%d %s\n", file, line, msg);
62 exit(-5);
64 #undef assert
65 #define assert(a) do {if (!(a)) nonono(__FILE__, __LINE__, #a);}while(0)
66 #endif
68 #else
70 #define DLOG(a)
72 #endif
74 /* bootsector OEM name. see related compatibility problems at:
75 * https://jdebp.eu/FGA/volume-boot-block-oem-name-field.html
76 * http://seasip.info/Misc/oemid.html
78 #define BOOTSECTOR_OEM_NAME "MSWIN4.1"
80 #define DIR_DELETED 0xe5
81 #define DIR_KANJI DIR_DELETED
82 #define DIR_KANJI_FAKE 0x05
83 #define DIR_FREE 0x00
85 /* dynamic array functions */
86 typedef struct array_t {
87 char* pointer;
88 unsigned int size,next,item_size;
89 } array_t;
91 static inline void array_init(array_t* array,unsigned int item_size)
93 array->pointer = NULL;
94 array->size=0;
95 array->next=0;
96 array->item_size=item_size;
99 static inline void array_free(array_t* array)
101 g_free(array->pointer);
102 array->size=array->next=0;
105 /* does not automatically grow */
106 static inline void* array_get(array_t* array,unsigned int index) {
107 assert(index < array->next);
108 return array->pointer + index * array->item_size;
111 static inline int array_ensure_allocated(array_t* array, int index)
113 if((index + 1) * array->item_size > array->size) {
114 int new_size = (index + 32) * array->item_size;
115 array->pointer = g_realloc(array->pointer, new_size);
116 if (!array->pointer)
117 return -1;
118 memset(array->pointer + array->size, 0, new_size - array->size);
119 array->size = new_size;
120 array->next = index + 1;
123 return 0;
126 static inline void* array_get_next(array_t* array) {
127 unsigned int next = array->next;
129 if (array_ensure_allocated(array, next) < 0)
130 return NULL;
132 array->next = next + 1;
133 return array_get(array, next);
136 static inline void* array_insert(array_t* array,unsigned int index,unsigned int count) {
137 if((array->next+count)*array->item_size>array->size) {
138 int increment=count*array->item_size;
139 array->pointer=g_realloc(array->pointer,array->size+increment);
140 if(!array->pointer)
141 return NULL;
142 array->size+=increment;
144 memmove(array->pointer+(index+count)*array->item_size,
145 array->pointer+index*array->item_size,
146 (array->next-index)*array->item_size);
147 array->next+=count;
148 return array->pointer+index*array->item_size;
151 /* this performs a "roll", so that the element which was at index_from becomes
152 * index_to, but the order of all other elements is preserved. */
153 static inline int array_roll(array_t* array,int index_to,int index_from,int count)
155 char* buf;
156 char* from;
157 char* to;
158 int is;
160 if(!array ||
161 index_to<0 || index_to>=array->next ||
162 index_from<0 || index_from>=array->next)
163 return -1;
165 if(index_to==index_from)
166 return 0;
168 is=array->item_size;
169 from=array->pointer+index_from*is;
170 to=array->pointer+index_to*is;
171 buf=g_malloc(is*count);
172 memcpy(buf,from,is*count);
174 if(index_to<index_from)
175 memmove(to+is*count,to,from-to);
176 else
177 memmove(from,from+is*count,to-from);
179 memcpy(to,buf,is*count);
181 g_free(buf);
183 return 0;
186 static inline int array_remove_slice(array_t* array,int index, int count)
188 assert(index >=0);
189 assert(count > 0);
190 assert(index + count <= array->next);
191 if(array_roll(array,array->next-1,index,count))
192 return -1;
193 array->next -= count;
194 return 0;
197 static int array_remove(array_t* array,int index)
199 return array_remove_slice(array, index, 1);
202 /* return the index for a given member */
203 static int array_index(array_t* array, void* pointer)
205 size_t offset = (char*)pointer - array->pointer;
206 assert((offset % array->item_size) == 0);
207 assert(offset/array->item_size < array->next);
208 return offset/array->item_size;
211 /* These structures are used to fake a disk and the VFAT filesystem.
212 * For this reason we need to use QEMU_PACKED. */
214 typedef struct bootsector_t {
215 uint8_t jump[3];
216 uint8_t name[8];
217 uint16_t sector_size;
218 uint8_t sectors_per_cluster;
219 uint16_t reserved_sectors;
220 uint8_t number_of_fats;
221 uint16_t root_entries;
222 uint16_t total_sectors16;
223 uint8_t media_type;
224 uint16_t sectors_per_fat;
225 uint16_t sectors_per_track;
226 uint16_t number_of_heads;
227 uint32_t hidden_sectors;
228 uint32_t total_sectors;
229 union {
230 struct {
231 uint8_t drive_number;
232 uint8_t reserved1;
233 uint8_t signature;
234 uint32_t id;
235 uint8_t volume_label[11];
236 uint8_t fat_type[8];
237 uint8_t ignored[0x1c0];
238 } QEMU_PACKED fat16;
239 struct {
240 uint32_t sectors_per_fat;
241 uint16_t flags;
242 uint8_t major,minor;
243 uint32_t first_cluster_of_root_dir;
244 uint16_t info_sector;
245 uint16_t backup_boot_sector;
246 uint8_t reserved[12];
247 uint8_t drive_number;
248 uint8_t reserved1;
249 uint8_t signature;
250 uint32_t id;
251 uint8_t volume_label[11];
252 uint8_t fat_type[8];
253 uint8_t ignored[0x1a4];
254 } QEMU_PACKED fat32;
255 } u;
256 uint8_t magic[2];
257 } QEMU_PACKED bootsector_t;
259 typedef struct {
260 uint8_t head;
261 uint8_t sector;
262 uint8_t cylinder;
263 } mbr_chs_t;
265 typedef struct partition_t {
266 uint8_t attributes; /* 0x80 = bootable */
267 mbr_chs_t start_CHS;
268 uint8_t fs_type; /* 0x1 = FAT12, 0x6 = FAT16, 0xe = FAT16_LBA, 0xb = FAT32, 0xc = FAT32_LBA */
269 mbr_chs_t end_CHS;
270 uint32_t start_sector_long;
271 uint32_t length_sector_long;
272 } QEMU_PACKED partition_t;
274 typedef struct mbr_t {
275 uint8_t ignored[0x1b8];
276 uint32_t nt_id;
277 uint8_t ignored2[2];
278 partition_t partition[4];
279 uint8_t magic[2];
280 } QEMU_PACKED mbr_t;
282 typedef struct direntry_t {
283 uint8_t name[8 + 3];
284 uint8_t attributes;
285 uint8_t reserved[2];
286 uint16_t ctime;
287 uint16_t cdate;
288 uint16_t adate;
289 uint16_t begin_hi;
290 uint16_t mtime;
291 uint16_t mdate;
292 uint16_t begin;
293 uint32_t size;
294 } QEMU_PACKED direntry_t;
296 /* this structure are used to transparently access the files */
298 typedef struct mapping_t {
299 /* begin is the first cluster, end is the last+1 */
300 uint32_t begin,end;
301 /* as s->directory is growable, no pointer may be used here */
302 unsigned int dir_index;
303 /* the clusters of a file may be in any order; this points to the first */
304 int first_mapping_index;
305 union {
306 /* offset is
307 * - the offset in the file (in clusters) for a file, or
308 * - the next cluster of the directory for a directory
310 struct {
311 uint32_t offset;
312 } file;
313 struct {
314 int parent_mapping_index;
315 int first_dir_index;
316 } dir;
317 } info;
318 /* path contains the full path, i.e. it always starts with s->path */
319 char* path;
321 enum {
322 MODE_UNDEFINED = 0,
323 MODE_NORMAL = 1,
324 MODE_MODIFIED = 2,
325 MODE_DIRECTORY = 4,
326 MODE_DELETED = 8,
327 } mode;
328 int read_only;
329 } mapping_t;
331 #ifdef DEBUG
332 static void print_direntry(const struct direntry_t*);
333 static void print_mapping(const struct mapping_t* mapping);
334 #endif
336 /* here begins the real VVFAT driver */
338 typedef struct BDRVVVFATState {
339 CoMutex lock;
340 BlockDriverState* bs; /* pointer to parent */
341 unsigned char first_sectors[0x40*0x200];
343 int fat_type; /* 16 or 32 */
344 array_t fat,directory,mapping;
345 char volume_label[11];
347 uint32_t offset_to_bootsector; /* 0 for floppy, 0x3f for disk */
349 unsigned int cluster_size;
350 unsigned int sectors_per_cluster;
351 unsigned int sectors_per_fat;
352 uint32_t last_cluster_of_root_directory;
353 /* how many entries are available in root directory (0 for FAT32) */
354 uint16_t root_entries;
355 uint32_t sector_count; /* total number of sectors of the partition */
356 uint32_t cluster_count; /* total number of clusters of this partition */
357 uint32_t max_fat_value;
358 uint32_t offset_to_fat;
359 uint32_t offset_to_root_dir;
361 int current_fd;
362 mapping_t* current_mapping;
363 unsigned char* cluster; /* points to current cluster */
364 unsigned char* cluster_buffer; /* points to a buffer to hold temp data */
365 unsigned int current_cluster;
367 /* write support */
368 char* qcow_filename;
369 BdrvChild* qcow;
370 void* fat2;
371 char* used_clusters;
372 array_t commits;
373 const char* path;
374 int downcase_short_names;
376 Error *migration_blocker;
377 } BDRVVVFATState;
379 /* take the sector position spos and convert it to Cylinder/Head/Sector position
380 * if the position is outside the specified geometry, fill maximum value for CHS
381 * and return 1 to signal overflow.
383 static int sector2CHS(mbr_chs_t *chs, int spos, int cyls, int heads, int secs)
385 int head,sector;
386 sector = spos % secs; spos /= secs;
387 head = spos % heads; spos /= heads;
388 if (spos >= cyls) {
389 /* Overflow,
390 it happens if 32bit sector positions are used, while CHS is only 24bit.
391 Windows/Dos is said to take 1023/255/63 as nonrepresentable CHS */
392 chs->head = 0xFF;
393 chs->sector = 0xFF;
394 chs->cylinder = 0xFF;
395 return 1;
397 chs->head = (uint8_t)head;
398 chs->sector = (uint8_t)( (sector+1) | ((spos>>8)<<6) );
399 chs->cylinder = (uint8_t)spos;
400 return 0;
403 static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)
405 /* TODO: if the files mbr.img and bootsect.img exist, use them */
406 mbr_t* real_mbr=(mbr_t*)s->first_sectors;
407 partition_t* partition = &(real_mbr->partition[0]);
408 int lba;
410 memset(s->first_sectors,0,512);
412 /* Win NT Disk Signature */
413 real_mbr->nt_id= cpu_to_le32(0xbe1afdfa);
415 partition->attributes=0x80; /* bootable */
417 /* LBA is used when partition is outside the CHS geometry */
418 lba = sector2CHS(&partition->start_CHS, s->offset_to_bootsector,
419 cyls, heads, secs);
420 lba |= sector2CHS(&partition->end_CHS, s->bs->total_sectors - 1,
421 cyls, heads, secs);
423 /*LBA partitions are identified only by start/length_sector_long not by CHS*/
424 partition->start_sector_long = cpu_to_le32(s->offset_to_bootsector);
425 partition->length_sector_long = cpu_to_le32(s->bs->total_sectors
426 - s->offset_to_bootsector);
428 /* FAT12/FAT16/FAT32 */
429 /* DOS uses different types when partition is LBA,
430 probably to prevent older versions from using CHS on them */
431 partition->fs_type = s->fat_type == 12 ? 0x1 :
432 s->fat_type == 16 ? (lba ? 0xe : 0x06) :
433 /*s->fat_type == 32*/ (lba ? 0xc : 0x0b);
435 real_mbr->magic[0]=0x55; real_mbr->magic[1]=0xaa;
438 /* direntry functions */
440 static direntry_t *create_long_filename(BDRVVVFATState *s, const char *filename)
442 int number_of_entries, i;
443 glong length;
444 direntry_t *entry;
446 gunichar2 *longname = g_utf8_to_utf16(filename, -1, NULL, &length, NULL);
447 if (!longname) {
448 fprintf(stderr, "vvfat: invalid UTF-8 name: %s\n", filename);
449 return NULL;
452 number_of_entries = (length * 2 + 25) / 26;
454 for(i=0;i<number_of_entries;i++) {
455 entry=array_get_next(&(s->directory));
456 entry->attributes=0xf;
457 entry->reserved[0]=0;
458 entry->begin=0;
459 entry->name[0]=(number_of_entries-i)|(i==0?0x40:0);
461 for(i=0;i<26*number_of_entries;i++) {
462 int offset=(i%26);
463 if(offset<10) offset=1+offset;
464 else if(offset<22) offset=14+offset-10;
465 else offset=28+offset-22;
466 entry=array_get(&(s->directory),s->directory.next-1-(i/26));
467 if (i >= 2 * length + 2) {
468 entry->name[offset] = 0xff;
469 } else if (i % 2 == 0) {
470 entry->name[offset] = longname[i / 2] & 0xff;
471 } else {
472 entry->name[offset] = longname[i / 2] >> 8;
475 g_free(longname);
476 return array_get(&(s->directory),s->directory.next-number_of_entries);
479 static char is_free(const direntry_t* direntry)
481 return direntry->name[0] == DIR_DELETED || direntry->name[0] == DIR_FREE;
484 static char is_volume_label(const direntry_t* direntry)
486 return direntry->attributes == 0x28;
489 static char is_long_name(const direntry_t* direntry)
491 return direntry->attributes == 0xf;
494 static char is_short_name(const direntry_t* direntry)
496 return !is_volume_label(direntry) && !is_long_name(direntry)
497 && !is_free(direntry);
500 static char is_directory(const direntry_t* direntry)
502 return direntry->attributes & 0x10 && direntry->name[0] != DIR_DELETED;
505 static inline char is_dot(const direntry_t* direntry)
507 return is_short_name(direntry) && direntry->name[0] == '.';
510 static char is_file(const direntry_t* direntry)
512 return is_short_name(direntry) && !is_directory(direntry);
515 static inline uint32_t begin_of_direntry(const direntry_t* direntry)
517 return le16_to_cpu(direntry->begin)|(le16_to_cpu(direntry->begin_hi)<<16);
520 static inline uint32_t filesize_of_direntry(const direntry_t* direntry)
522 return le32_to_cpu(direntry->size);
525 static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin)
527 direntry->begin = cpu_to_le16(begin & 0xffff);
528 direntry->begin_hi = cpu_to_le16((begin >> 16) & 0xffff);
531 static uint8_t to_valid_short_char(gunichar c)
533 c = g_unichar_toupper(c);
534 if ((c >= '0' && c <= '9') ||
535 (c >= 'A' && c <= 'Z') ||
536 strchr("$%'-_@~`!(){}^#&", c) != 0) {
537 return c;
538 } else {
539 return 0;
543 static direntry_t *create_short_filename(BDRVVVFATState *s,
544 const char *filename,
545 unsigned int directory_start)
547 int i, j = 0;
548 direntry_t *entry = array_get_next(&(s->directory));
549 const gchar *p, *last_dot = NULL;
550 gunichar c;
551 bool lossy_conversion = false;
552 char tail[11];
554 if (!entry) {
555 return NULL;
557 memset(entry->name, 0x20, sizeof(entry->name));
559 /* copy filename and search last dot */
560 for (p = filename; ; p = g_utf8_next_char(p)) {
561 c = g_utf8_get_char(p);
562 if (c == '\0') {
563 break;
564 } else if (c == '.') {
565 if (j == 0) {
566 /* '.' at start of filename */
567 lossy_conversion = true;
568 } else {
569 if (last_dot) {
570 lossy_conversion = true;
572 last_dot = p;
574 } else if (!last_dot) {
575 /* first part of the name; copy it */
576 uint8_t v = to_valid_short_char(c);
577 if (j < 8 && v) {
578 entry->name[j++] = v;
579 } else {
580 lossy_conversion = true;
585 /* copy extension (if any) */
586 if (last_dot) {
587 j = 0;
588 for (p = g_utf8_next_char(last_dot); ; p = g_utf8_next_char(p)) {
589 c = g_utf8_get_char(p);
590 if (c == '\0') {
591 break;
592 } else {
593 /* extension; copy it */
594 uint8_t v = to_valid_short_char(c);
595 if (j < 3 && v) {
596 entry->name[8 + (j++)] = v;
597 } else {
598 lossy_conversion = true;
604 if (entry->name[0] == DIR_KANJI) {
605 entry->name[0] = DIR_KANJI_FAKE;
608 /* numeric-tail generation */
609 for (j = 0; j < 8; j++) {
610 if (entry->name[j] == ' ') {
611 break;
614 for (i = lossy_conversion ? 1 : 0; i < 999999; i++) {
615 direntry_t *entry1;
616 if (i > 0) {
617 int len = sprintf(tail, "~%d", i);
618 memcpy(entry->name + MIN(j, 8 - len), tail, len);
620 for (entry1 = array_get(&(s->directory), directory_start);
621 entry1 < entry; entry1++) {
622 if (!is_long_name(entry1) &&
623 !memcmp(entry1->name, entry->name, 11)) {
624 break; /* found dupe */
627 if (entry1 == entry) {
628 /* no dupe found */
629 return entry;
632 return NULL;
635 /* fat functions */
637 static inline uint8_t fat_chksum(const direntry_t* entry)
639 uint8_t chksum=0;
640 int i;
642 for (i = 0; i < ARRAY_SIZE(entry->name); i++) {
643 chksum = (((chksum & 0xfe) >> 1) |
644 ((chksum & 0x01) ? 0x80 : 0)) + entry->name[i];
647 return chksum;
650 /* if return_time==0, this returns the fat_date, else the fat_time */
651 static uint16_t fat_datetime(time_t time,int return_time) {
652 struct tm* t;
653 struct tm t1;
654 t = &t1;
655 localtime_r(&time,t);
656 if(return_time)
657 return cpu_to_le16((t->tm_sec/2)|(t->tm_min<<5)|(t->tm_hour<<11));
658 return cpu_to_le16((t->tm_mday)|((t->tm_mon+1)<<5)|((t->tm_year-80)<<9));
661 static inline void fat_set(BDRVVVFATState* s,unsigned int cluster,uint32_t value)
663 if(s->fat_type==32) {
664 uint32_t* entry=array_get(&(s->fat),cluster);
665 *entry=cpu_to_le32(value);
666 } else if(s->fat_type==16) {
667 uint16_t* entry=array_get(&(s->fat),cluster);
668 *entry=cpu_to_le16(value&0xffff);
669 } else {
670 int offset = (cluster*3/2);
671 unsigned char* p = array_get(&(s->fat), offset);
672 switch (cluster&1) {
673 case 0:
674 p[0] = value&0xff;
675 p[1] = (p[1]&0xf0) | ((value>>8)&0xf);
676 break;
677 case 1:
678 p[0] = (p[0]&0xf) | ((value&0xf)<<4);
679 p[1] = (value>>4);
680 break;
685 static inline uint32_t fat_get(BDRVVVFATState* s,unsigned int cluster)
687 if(s->fat_type==32) {
688 uint32_t* entry=array_get(&(s->fat),cluster);
689 return le32_to_cpu(*entry);
690 } else if(s->fat_type==16) {
691 uint16_t* entry=array_get(&(s->fat),cluster);
692 return le16_to_cpu(*entry);
693 } else {
694 const uint8_t* x=(uint8_t*)(s->fat.pointer)+cluster*3/2;
695 return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
699 static inline int fat_eof(BDRVVVFATState* s,uint32_t fat_entry)
701 if(fat_entry>s->max_fat_value-8)
702 return -1;
703 return 0;
706 static inline void init_fat(BDRVVVFATState* s)
708 if (s->fat_type == 12) {
709 array_init(&(s->fat),1);
710 array_ensure_allocated(&(s->fat),
711 s->sectors_per_fat * 0x200 * 3 / 2 - 1);
712 } else {
713 array_init(&(s->fat),(s->fat_type==32?4:2));
714 array_ensure_allocated(&(s->fat),
715 s->sectors_per_fat * 0x200 / s->fat.item_size - 1);
717 memset(s->fat.pointer,0,s->fat.size);
719 switch(s->fat_type) {
720 case 12: s->max_fat_value=0xfff; break;
721 case 16: s->max_fat_value=0xffff; break;
722 case 32: s->max_fat_value=0x0fffffff; break;
723 default: s->max_fat_value=0; /* error... */
728 static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,
729 unsigned int directory_start, const char* filename, int is_dot)
731 int long_index = s->directory.next;
732 direntry_t* entry = NULL;
733 direntry_t* entry_long = NULL;
735 if(is_dot) {
736 entry=array_get_next(&(s->directory));
737 memset(entry->name, 0x20, sizeof(entry->name));
738 memcpy(entry->name,filename,strlen(filename));
739 return entry;
742 entry_long=create_long_filename(s,filename);
743 entry = create_short_filename(s, filename, directory_start);
745 /* calculate checksum; propagate to long name */
746 if(entry_long) {
747 uint8_t chksum=fat_chksum(entry);
749 /* calculate anew, because realloc could have taken place */
750 entry_long=array_get(&(s->directory),long_index);
751 while(entry_long<entry && is_long_name(entry_long)) {
752 entry_long->reserved[1]=chksum;
753 entry_long++;
757 return entry;
761 * Read a directory. (the index of the corresponding mapping must be passed).
763 static int read_directory(BDRVVVFATState* s, int mapping_index)
765 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
766 direntry_t* direntry;
767 const char* dirname = mapping->path;
768 int first_cluster = mapping->begin;
769 int parent_index = mapping->info.dir.parent_mapping_index;
770 mapping_t* parent_mapping = (mapping_t*)
771 (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);
772 int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;
774 DIR* dir=opendir(dirname);
775 struct dirent* entry;
776 int i;
778 assert(mapping->mode & MODE_DIRECTORY);
780 if(!dir) {
781 mapping->end = mapping->begin;
782 return -1;
785 i = mapping->info.dir.first_dir_index =
786 first_cluster == 0 ? 0 : s->directory.next;
788 if (first_cluster != 0) {
789 /* create the top entries of a subdirectory */
790 (void)create_short_and_long_name(s, i, ".", 1);
791 (void)create_short_and_long_name(s, i, "..", 1);
794 /* actually read the directory, and allocate the mappings */
795 while((entry=readdir(dir))) {
796 unsigned int length=strlen(dirname)+2+strlen(entry->d_name);
797 char* buffer;
798 direntry_t* direntry;
799 struct stat st;
800 int is_dot=!strcmp(entry->d_name,".");
801 int is_dotdot=!strcmp(entry->d_name,"..");
803 if (first_cluster == 0 && s->directory.next >= s->root_entries - 1) {
804 fprintf(stderr, "Too many entries in root directory\n");
805 closedir(dir);
806 return -2;
809 if(first_cluster == 0 && (is_dotdot || is_dot))
810 continue;
812 buffer = g_malloc(length);
813 snprintf(buffer,length,"%s/%s",dirname,entry->d_name);
815 if(stat(buffer,&st)<0) {
816 g_free(buffer);
817 continue;
820 /* create directory entry for this file */
821 if (!is_dot && !is_dotdot) {
822 direntry = create_short_and_long_name(s, i, entry->d_name, 0);
823 } else {
824 direntry = array_get(&(s->directory), is_dot ? i : i + 1);
826 direntry->attributes=(S_ISDIR(st.st_mode)?0x10:0x20);
827 direntry->reserved[0]=direntry->reserved[1]=0;
828 direntry->ctime=fat_datetime(st.st_ctime,1);
829 direntry->cdate=fat_datetime(st.st_ctime,0);
830 direntry->adate=fat_datetime(st.st_atime,0);
831 direntry->begin_hi=0;
832 direntry->mtime=fat_datetime(st.st_mtime,1);
833 direntry->mdate=fat_datetime(st.st_mtime,0);
834 if(is_dotdot)
835 set_begin_of_direntry(direntry, first_cluster_of_parent);
836 else if(is_dot)
837 set_begin_of_direntry(direntry, first_cluster);
838 else
839 direntry->begin=0; /* do that later */
840 if (st.st_size > 0x7fffffff) {
841 fprintf(stderr, "File %s is larger than 2GB\n", buffer);
842 g_free(buffer);
843 closedir(dir);
844 return -2;
846 direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);
848 /* create mapping for this file */
849 if(!is_dot && !is_dotdot && (S_ISDIR(st.st_mode) || st.st_size)) {
850 s->current_mapping = array_get_next(&(s->mapping));
851 s->current_mapping->begin=0;
852 s->current_mapping->end=st.st_size;
854 * we get the direntry of the most recent direntry, which
855 * contains the short name and all the relevant information.
857 s->current_mapping->dir_index=s->directory.next-1;
858 s->current_mapping->first_mapping_index = -1;
859 if (S_ISDIR(st.st_mode)) {
860 s->current_mapping->mode = MODE_DIRECTORY;
861 s->current_mapping->info.dir.parent_mapping_index =
862 mapping_index;
863 } else {
864 s->current_mapping->mode = MODE_UNDEFINED;
865 s->current_mapping->info.file.offset = 0;
867 s->current_mapping->path=buffer;
868 s->current_mapping->read_only =
869 (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0;
870 } else {
871 g_free(buffer);
874 closedir(dir);
876 /* fill with zeroes up to the end of the cluster */
877 while(s->directory.next%(0x10*s->sectors_per_cluster)) {
878 direntry_t* direntry=array_get_next(&(s->directory));
879 memset(direntry,0,sizeof(direntry_t));
882 if (s->fat_type != 32 &&
883 mapping_index == 0 &&
884 s->directory.next < s->root_entries) {
885 /* root directory */
886 int cur = s->directory.next;
887 array_ensure_allocated(&(s->directory), s->root_entries - 1);
888 s->directory.next = s->root_entries;
889 memset(array_get(&(s->directory), cur), 0,
890 (s->root_entries - cur) * sizeof(direntry_t));
893 /* re-get the mapping, since s->mapping was possibly realloc()ed */
894 mapping = array_get(&(s->mapping), mapping_index);
895 first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)
896 * 0x20 / s->cluster_size;
897 mapping->end = first_cluster;
899 direntry = array_get(&(s->directory), mapping->dir_index);
900 set_begin_of_direntry(direntry, mapping->begin);
902 return 0;
905 static inline uint32_t sector2cluster(BDRVVVFATState* s,off_t sector_num)
907 return (sector_num - s->offset_to_root_dir) / s->sectors_per_cluster;
910 static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
912 return s->offset_to_root_dir + s->sectors_per_cluster * cluster_num;
915 static int init_directories(BDRVVVFATState* s,
916 const char *dirname, int heads, int secs,
917 Error **errp)
919 bootsector_t* bootsector;
920 mapping_t* mapping;
921 unsigned int i;
922 unsigned int cluster;
924 memset(&(s->first_sectors[0]),0,0x40*0x200);
926 s->cluster_size=s->sectors_per_cluster*0x200;
927 s->cluster_buffer=g_malloc(s->cluster_size);
930 * The formula: sc = spf+1+spf*spc*(512*8/fat_type),
931 * where sc is sector_count,
932 * spf is sectors_per_fat,
933 * spc is sectors_per_clusters, and
934 * fat_type = 12, 16 or 32.
936 i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;
937 s->sectors_per_fat=(s->sector_count+i)/i; /* round up */
939 s->offset_to_fat = s->offset_to_bootsector + 1;
940 s->offset_to_root_dir = s->offset_to_fat + s->sectors_per_fat * 2;
942 array_init(&(s->mapping),sizeof(mapping_t));
943 array_init(&(s->directory),sizeof(direntry_t));
945 /* add volume label */
947 direntry_t* entry=array_get_next(&(s->directory));
948 entry->attributes=0x28; /* archive | volume label */
949 memcpy(entry->name, s->volume_label, sizeof(entry->name));
952 /* Now build FAT, and write back information into directory */
953 init_fat(s);
955 /* TODO: if there are more entries, bootsector has to be adjusted! */
956 s->root_entries = 0x02 * 0x10 * s->sectors_per_cluster;
957 s->cluster_count=sector2cluster(s, s->sector_count);
959 mapping = array_get_next(&(s->mapping));
960 mapping->begin = 0;
961 mapping->dir_index = 0;
962 mapping->info.dir.parent_mapping_index = -1;
963 mapping->first_mapping_index = -1;
964 mapping->path = g_strdup(dirname);
965 i = strlen(mapping->path);
966 if (i > 0 && mapping->path[i - 1] == '/')
967 mapping->path[i - 1] = '\0';
968 mapping->mode = MODE_DIRECTORY;
969 mapping->read_only = 0;
970 s->path = mapping->path;
972 for (i = 0, cluster = 0; i < s->mapping.next; i++) {
973 /* MS-DOS expects the FAT to be 0 for the root directory
974 * (except for the media byte). */
975 /* LATER TODO: still true for FAT32? */
976 int fix_fat = (i != 0);
977 mapping = array_get(&(s->mapping), i);
979 if (mapping->mode & MODE_DIRECTORY) {
980 mapping->begin = cluster;
981 if(read_directory(s, i)) {
982 error_setg(errp, "Could not read directory %s",
983 mapping->path);
984 return -1;
986 mapping = array_get(&(s->mapping), i);
987 } else {
988 assert(mapping->mode == MODE_UNDEFINED);
989 mapping->mode=MODE_NORMAL;
990 mapping->begin = cluster;
991 if (mapping->end > 0) {
992 direntry_t* direntry = array_get(&(s->directory),
993 mapping->dir_index);
995 mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;
996 set_begin_of_direntry(direntry, mapping->begin);
997 } else {
998 mapping->end = cluster + 1;
999 fix_fat = 0;
1003 assert(mapping->begin < mapping->end);
1005 /* next free cluster */
1006 cluster = mapping->end;
1008 if(cluster > s->cluster_count) {
1009 error_setg(errp,
1010 "Directory does not fit in FAT%d (capacity %.2f MB)",
1011 s->fat_type, s->sector_count / 2000.0);
1012 return -1;
1015 /* fix fat for entry */
1016 if (fix_fat) {
1017 int j;
1018 for(j = mapping->begin; j < mapping->end - 1; j++)
1019 fat_set(s, j, j+1);
1020 fat_set(s, mapping->end - 1, s->max_fat_value);
1024 mapping = array_get(&(s->mapping), 0);
1025 s->last_cluster_of_root_directory = mapping->end;
1027 /* the FAT signature */
1028 fat_set(s,0,s->max_fat_value);
1029 fat_set(s,1,s->max_fat_value);
1031 s->current_mapping = NULL;
1033 bootsector = (bootsector_t *)(s->first_sectors
1034 + s->offset_to_bootsector * 0x200);
1035 bootsector->jump[0]=0xeb;
1036 bootsector->jump[1]=0x3e;
1037 bootsector->jump[2]=0x90;
1038 memcpy(bootsector->name, BOOTSECTOR_OEM_NAME, 8);
1039 bootsector->sector_size=cpu_to_le16(0x200);
1040 bootsector->sectors_per_cluster=s->sectors_per_cluster;
1041 bootsector->reserved_sectors=cpu_to_le16(1);
1042 bootsector->number_of_fats=0x2; /* number of FATs */
1043 bootsector->root_entries = cpu_to_le16(s->root_entries);
1044 bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
1045 /* media descriptor: hard disk=0xf8, floppy=0xf0 */
1046 bootsector->media_type = (s->offset_to_bootsector > 0 ? 0xf8 : 0xf0);
1047 s->fat.pointer[0] = bootsector->media_type;
1048 bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
1049 bootsector->sectors_per_track = cpu_to_le16(secs);
1050 bootsector->number_of_heads = cpu_to_le16(heads);
1051 bootsector->hidden_sectors = cpu_to_le32(s->offset_to_bootsector);
1052 bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
1054 /* LATER TODO: if FAT32, this is wrong */
1055 /* drive_number: fda=0, hda=0x80 */
1056 bootsector->u.fat16.drive_number = s->offset_to_bootsector == 0 ? 0 : 0x80;
1057 bootsector->u.fat16.signature=0x29;
1058 bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);
1060 memcpy(bootsector->u.fat16.volume_label, s->volume_label,
1061 sizeof(bootsector->u.fat16.volume_label));
1062 memcpy(bootsector->u.fat16.fat_type,
1063 s->fat_type == 12 ? "FAT12 " : "FAT16 ", 8);
1064 bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;
1066 return 0;
1069 #ifdef DEBUG
1070 static BDRVVVFATState *vvv = NULL;
1071 #endif
1073 static int enable_write_target(BlockDriverState *bs, Error **errp);
1074 static int is_consistent(BDRVVVFATState *s);
1076 static QemuOptsList runtime_opts = {
1077 .name = "vvfat",
1078 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1079 .desc = {
1081 .name = "dir",
1082 .type = QEMU_OPT_STRING,
1083 .help = "Host directory to map to the vvfat device",
1086 .name = "fat-type",
1087 .type = QEMU_OPT_NUMBER,
1088 .help = "FAT type (12, 16 or 32)",
1091 .name = "floppy",
1092 .type = QEMU_OPT_BOOL,
1093 .help = "Create a floppy rather than a hard disk image",
1096 .name = "label",
1097 .type = QEMU_OPT_STRING,
1098 .help = "Use a volume label other than QEMU VVFAT",
1101 .name = "rw",
1102 .type = QEMU_OPT_BOOL,
1103 .help = "Make the image writable",
1105 { /* end of list */ }
1109 static void vvfat_parse_filename(const char *filename, QDict *options,
1110 Error **errp)
1112 int fat_type = 0;
1113 bool floppy = false;
1114 bool rw = false;
1115 int i;
1117 if (!strstart(filename, "fat:", NULL)) {
1118 error_setg(errp, "File name string must start with 'fat:'");
1119 return;
1122 /* Parse options */
1123 if (strstr(filename, ":32:")) {
1124 fat_type = 32;
1125 } else if (strstr(filename, ":16:")) {
1126 fat_type = 16;
1127 } else if (strstr(filename, ":12:")) {
1128 fat_type = 12;
1131 if (strstr(filename, ":floppy:")) {
1132 floppy = true;
1135 if (strstr(filename, ":rw:")) {
1136 rw = true;
1139 /* Get the directory name without options */
1140 i = strrchr(filename, ':') - filename;
1141 assert(i >= 3);
1142 if (filename[i - 2] == ':' && qemu_isalpha(filename[i - 1])) {
1143 /* workaround for DOS drive names */
1144 filename += i - 1;
1145 } else {
1146 filename += i + 1;
1149 /* Fill in the options QDict */
1150 qdict_put_str(options, "dir", filename);
1151 qdict_put_int(options, "fat-type", fat_type);
1152 qdict_put_bool(options, "floppy", floppy);
1153 qdict_put_bool(options, "rw", rw);
1156 static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
1157 Error **errp)
1159 BDRVVVFATState *s = bs->opaque;
1160 int cyls, heads, secs;
1161 bool floppy;
1162 const char *dirname, *label;
1163 QemuOpts *opts;
1164 Error *local_err = NULL;
1165 int ret;
1167 #ifdef DEBUG
1168 vvv = s;
1169 #endif
1171 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1172 qemu_opts_absorb_qdict(opts, options, &local_err);
1173 if (local_err) {
1174 error_propagate(errp, local_err);
1175 ret = -EINVAL;
1176 goto fail;
1179 dirname = qemu_opt_get(opts, "dir");
1180 if (!dirname) {
1181 error_setg(errp, "vvfat block driver requires a 'dir' option");
1182 ret = -EINVAL;
1183 goto fail;
1186 s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
1187 floppy = qemu_opt_get_bool(opts, "floppy", false);
1189 memset(s->volume_label, ' ', sizeof(s->volume_label));
1190 label = qemu_opt_get(opts, "label");
1191 if (label) {
1192 size_t label_length = strlen(label);
1193 if (label_length > 11) {
1194 error_setg(errp, "vvfat label cannot be longer than 11 bytes");
1195 ret = -EINVAL;
1196 goto fail;
1198 memcpy(s->volume_label, label, label_length);
1199 } else {
1200 memcpy(s->volume_label, "QEMU VVFAT", 10);
1203 if (floppy) {
1204 /* 1.44MB or 2.88MB floppy. 2.88MB can be FAT12 (default) or FAT16. */
1205 if (!s->fat_type) {
1206 s->fat_type = 12;
1207 secs = 36;
1208 s->sectors_per_cluster = 2;
1209 } else {
1210 secs = s->fat_type == 12 ? 18 : 36;
1211 s->sectors_per_cluster = 1;
1213 cyls = 80;
1214 heads = 2;
1215 } else {
1216 /* 32MB or 504MB disk*/
1217 if (!s->fat_type) {
1218 s->fat_type = 16;
1220 s->offset_to_bootsector = 0x3f;
1221 cyls = s->fat_type == 12 ? 64 : 1024;
1222 heads = 16;
1223 secs = 63;
1226 switch (s->fat_type) {
1227 case 32:
1228 fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "
1229 "You are welcome to do so!\n");
1230 break;
1231 case 16:
1232 case 12:
1233 break;
1234 default:
1235 error_setg(errp, "Valid FAT types are only 12, 16 and 32");
1236 ret = -EINVAL;
1237 goto fail;
1241 s->bs = bs;
1243 /* LATER TODO: if FAT32, adjust */
1244 s->sectors_per_cluster=0x10;
1246 s->current_cluster=0xffffffff;
1248 s->qcow = NULL;
1249 s->qcow_filename = NULL;
1250 s->fat2 = NULL;
1251 s->downcase_short_names = 1;
1253 fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
1254 dirname, cyls, heads, secs);
1256 s->sector_count = cyls * heads * secs - s->offset_to_bootsector;
1258 if (qemu_opt_get_bool(opts, "rw", false)) {
1259 if (!bdrv_is_read_only(bs)) {
1260 ret = enable_write_target(bs, errp);
1261 if (ret < 0) {
1262 goto fail;
1264 } else {
1265 ret = -EPERM;
1266 error_setg(errp,
1267 "Unable to set VVFAT to 'rw' when drive is read-only");
1268 goto fail;
1270 } else {
1271 /* read only is the default for safety */
1272 ret = bdrv_set_read_only(bs, true, &local_err);
1273 if (ret < 0) {
1274 error_propagate(errp, local_err);
1275 goto fail;
1279 bs->total_sectors = cyls * heads * secs;
1281 if (init_directories(s, dirname, heads, secs, errp)) {
1282 ret = -EIO;
1283 goto fail;
1286 s->sector_count = s->offset_to_root_dir
1287 + s->sectors_per_cluster * s->cluster_count;
1289 /* Disable migration when vvfat is used rw */
1290 if (s->qcow) {
1291 error_setg(&s->migration_blocker,
1292 "The vvfat (rw) format used by node '%s' "
1293 "does not support live migration",
1294 bdrv_get_device_or_node_name(bs));
1295 ret = migrate_add_blocker(s->migration_blocker, &local_err);
1296 if (local_err) {
1297 error_propagate(errp, local_err);
1298 error_free(s->migration_blocker);
1299 goto fail;
1303 if (s->offset_to_bootsector > 0) {
1304 init_mbr(s, cyls, heads, secs);
1307 qemu_co_mutex_init(&s->lock);
1309 ret = 0;
1310 fail:
1311 qemu_opts_del(opts);
1312 return ret;
1315 static void vvfat_refresh_limits(BlockDriverState *bs, Error **errp)
1317 bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
1320 static inline void vvfat_close_current_file(BDRVVVFATState *s)
1322 if(s->current_mapping) {
1323 s->current_mapping = NULL;
1324 if (s->current_fd) {
1325 qemu_close(s->current_fd);
1326 s->current_fd = 0;
1329 s->current_cluster = -1;
1332 /* mappings between index1 and index2-1 are supposed to be ordered
1333 * return value is the index of the last mapping for which end>cluster_num
1335 static inline int find_mapping_for_cluster_aux(BDRVVVFATState* s,int cluster_num,int index1,int index2)
1337 while(1) {
1338 int index3;
1339 mapping_t* mapping;
1340 index3=(index1+index2)/2;
1341 mapping=array_get(&(s->mapping),index3);
1342 assert(mapping->begin < mapping->end);
1343 if(mapping->begin>=cluster_num) {
1344 assert(index2!=index3 || index2==0);
1345 if(index2==index3)
1346 return index1;
1347 index2=index3;
1348 } else {
1349 if(index1==index3)
1350 return mapping->end<=cluster_num ? index2 : index1;
1351 index1=index3;
1353 assert(index1<=index2);
1354 DLOG(mapping=array_get(&(s->mapping),index1);
1355 assert(mapping->begin<=cluster_num);
1356 assert(index2 >= s->mapping.next ||
1357 ((mapping = array_get(&(s->mapping),index2)) &&
1358 mapping->end>cluster_num)));
1362 static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_num)
1364 int index=find_mapping_for_cluster_aux(s,cluster_num,0,s->mapping.next);
1365 mapping_t* mapping;
1366 if(index>=s->mapping.next)
1367 return NULL;
1368 mapping=array_get(&(s->mapping),index);
1369 if(mapping->begin>cluster_num)
1370 return NULL;
1371 assert(mapping->begin<=cluster_num && mapping->end>cluster_num);
1372 return mapping;
1375 static int open_file(BDRVVVFATState* s,mapping_t* mapping)
1377 if(!mapping)
1378 return -1;
1379 if(!s->current_mapping ||
1380 strcmp(s->current_mapping->path,mapping->path)) {
1381 /* open file */
1382 int fd = qemu_open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
1383 if(fd<0)
1384 return -1;
1385 vvfat_close_current_file(s);
1386 s->current_fd = fd;
1387 s->current_mapping = mapping;
1389 return 0;
1392 static inline int read_cluster(BDRVVVFATState *s,int cluster_num)
1394 if(s->current_cluster != cluster_num) {
1395 int result=0;
1396 off_t offset;
1397 assert(!s->current_mapping || s->current_fd || (s->current_mapping->mode & MODE_DIRECTORY));
1398 if(!s->current_mapping
1399 || s->current_mapping->begin>cluster_num
1400 || s->current_mapping->end<=cluster_num) {
1401 /* binary search of mappings for file */
1402 mapping_t* mapping=find_mapping_for_cluster(s,cluster_num);
1404 assert(!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end));
1406 if (mapping && mapping->mode & MODE_DIRECTORY) {
1407 vvfat_close_current_file(s);
1408 s->current_mapping = mapping;
1409 read_cluster_directory:
1410 offset = s->cluster_size*(cluster_num-s->current_mapping->begin);
1411 s->cluster = (unsigned char*)s->directory.pointer+offset
1412 + 0x20*s->current_mapping->info.dir.first_dir_index;
1413 assert(((s->cluster-(unsigned char*)s->directory.pointer)%s->cluster_size)==0);
1414 assert((char*)s->cluster+s->cluster_size <= s->directory.pointer+s->directory.next*s->directory.item_size);
1415 s->current_cluster = cluster_num;
1416 return 0;
1419 if(open_file(s,mapping))
1420 return -2;
1421 } else if (s->current_mapping->mode & MODE_DIRECTORY)
1422 goto read_cluster_directory;
1424 assert(s->current_fd);
1426 offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset;
1427 if(lseek(s->current_fd, offset, SEEK_SET)!=offset)
1428 return -3;
1429 s->cluster=s->cluster_buffer;
1430 result=read(s->current_fd,s->cluster,s->cluster_size);
1431 if(result<0) {
1432 s->current_cluster = -1;
1433 return -1;
1435 s->current_cluster = cluster_num;
1437 return 0;
1440 #ifdef DEBUG
1441 static void print_direntry(const direntry_t* direntry)
1443 int j = 0;
1444 char buffer[1024];
1446 fprintf(stderr, "direntry %p: ", direntry);
1447 if(!direntry)
1448 return;
1449 if(is_long_name(direntry)) {
1450 unsigned char* c=(unsigned char*)direntry;
1451 int i;
1452 for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)
1453 #define ADD_CHAR(c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;}
1454 ADD_CHAR(c[i]);
1455 for(i=14;i<26 && c[i] && c[i]!=0xff;i+=2)
1456 ADD_CHAR(c[i]);
1457 for(i=28;i<32 && c[i] && c[i]!=0xff;i+=2)
1458 ADD_CHAR(c[i]);
1459 buffer[j] = 0;
1460 fprintf(stderr, "%s\n", buffer);
1461 } else {
1462 int i;
1463 for(i=0;i<11;i++)
1464 ADD_CHAR(direntry->name[i]);
1465 buffer[j] = 0;
1466 fprintf(stderr,"%s attributes=0x%02x begin=%d size=%d\n",
1467 buffer,
1468 direntry->attributes,
1469 begin_of_direntry(direntry),le32_to_cpu(direntry->size));
1473 static void print_mapping(const mapping_t* mapping)
1475 fprintf(stderr, "mapping (%p): begin, end = %d, %d, dir_index = %d, "
1476 "first_mapping_index = %d, name = %s, mode = 0x%x, " ,
1477 mapping, mapping->begin, mapping->end, mapping->dir_index,
1478 mapping->first_mapping_index, mapping->path, mapping->mode);
1480 if (mapping->mode & MODE_DIRECTORY)
1481 fprintf(stderr, "parent_mapping_index = %d, first_dir_index = %d\n", mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);
1482 else
1483 fprintf(stderr, "offset = %d\n", mapping->info.file.offset);
1485 #endif
1487 static int vvfat_read(BlockDriverState *bs, int64_t sector_num,
1488 uint8_t *buf, int nb_sectors)
1490 BDRVVVFATState *s = bs->opaque;
1491 int i;
1493 for(i=0;i<nb_sectors;i++,sector_num++) {
1494 if (sector_num >= bs->total_sectors)
1495 return -1;
1496 if (s->qcow) {
1497 int64_t n;
1498 int ret;
1499 ret = bdrv_is_allocated(s->qcow->bs, sector_num * BDRV_SECTOR_SIZE,
1500 (nb_sectors - i) * BDRV_SECTOR_SIZE, &n);
1501 if (ret < 0) {
1502 return ret;
1504 if (ret) {
1505 DLOG(fprintf(stderr, "sectors %" PRId64 "+%" PRId64
1506 " allocated\n", sector_num,
1507 n >> BDRV_SECTOR_BITS));
1508 if (bdrv_read(s->qcow, sector_num, buf + i * 0x200,
1509 n >> BDRV_SECTOR_BITS)) {
1510 return -1;
1512 i += (n >> BDRV_SECTOR_BITS) - 1;
1513 sector_num += (n >> BDRV_SECTOR_BITS) - 1;
1514 continue;
1516 DLOG(fprintf(stderr, "sector %" PRId64 " not allocated\n",
1517 sector_num));
1519 if (sector_num < s->offset_to_root_dir) {
1520 if (sector_num < s->offset_to_fat) {
1521 memcpy(buf + i * 0x200,
1522 &(s->first_sectors[sector_num * 0x200]),
1523 0x200);
1524 } else if (sector_num < s->offset_to_fat + s->sectors_per_fat) {
1525 memcpy(buf + i * 0x200,
1526 &(s->fat.pointer[(sector_num
1527 - s->offset_to_fat) * 0x200]),
1528 0x200);
1529 } else if (sector_num < s->offset_to_root_dir) {
1530 memcpy(buf + i * 0x200,
1531 &(s->fat.pointer[(sector_num - s->offset_to_fat
1532 - s->sectors_per_fat) * 0x200]),
1533 0x200);
1535 } else {
1536 uint32_t sector = sector_num - s->offset_to_root_dir,
1537 sector_offset_in_cluster=(sector%s->sectors_per_cluster),
1538 cluster_num=sector/s->sectors_per_cluster;
1539 if(cluster_num > s->cluster_count || read_cluster(s, cluster_num) != 0) {
1540 /* LATER TODO: strict: return -1; */
1541 memset(buf+i*0x200,0,0x200);
1542 continue;
1544 memcpy(buf+i*0x200,s->cluster+sector_offset_in_cluster*0x200,0x200);
1547 return 0;
1550 static int coroutine_fn
1551 vvfat_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1552 QEMUIOVector *qiov, int flags)
1554 int ret;
1555 BDRVVVFATState *s = bs->opaque;
1556 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
1557 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1558 void *buf;
1560 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1561 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1563 buf = g_try_malloc(bytes);
1564 if (bytes && buf == NULL) {
1565 return -ENOMEM;
1568 qemu_co_mutex_lock(&s->lock);
1569 ret = vvfat_read(bs, sector_num, buf, nb_sectors);
1570 qemu_co_mutex_unlock(&s->lock);
1572 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1573 g_free(buf);
1575 return ret;
1578 /* LATER TODO: statify all functions */
1581 * Idea of the write support (use snapshot):
1583 * 1. check if all data is consistent, recording renames, modifications,
1584 * new files and directories (in s->commits).
1586 * 2. if the data is not consistent, stop committing
1588 * 3. handle renames, and create new files and directories (do not yet
1589 * write their contents)
1591 * 4. walk the directories, fixing the mapping and direntries, and marking
1592 * the handled mappings as not deleted
1594 * 5. commit the contents of the files
1596 * 6. handle deleted files and directories
1600 typedef struct commit_t {
1601 char* path;
1602 union {
1603 struct { uint32_t cluster; } rename;
1604 struct { int dir_index; uint32_t modified_offset; } writeout;
1605 struct { uint32_t first_cluster; } new_file;
1606 struct { uint32_t cluster; } mkdir;
1607 } param;
1608 /* DELETEs and RMDIRs are handled differently: see handle_deletes() */
1609 enum {
1610 ACTION_RENAME, ACTION_WRITEOUT, ACTION_NEW_FILE, ACTION_MKDIR
1611 } action;
1612 } commit_t;
1614 static void clear_commits(BDRVVVFATState* s)
1616 int i;
1617 DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));
1618 for (i = 0; i < s->commits.next; i++) {
1619 commit_t* commit = array_get(&(s->commits), i);
1620 assert(commit->path || commit->action == ACTION_WRITEOUT);
1621 if (commit->action != ACTION_WRITEOUT) {
1622 assert(commit->path);
1623 g_free(commit->path);
1624 } else
1625 assert(commit->path == NULL);
1627 s->commits.next = 0;
1630 static void schedule_rename(BDRVVVFATState* s,
1631 uint32_t cluster, char* new_path)
1633 commit_t* commit = array_get_next(&(s->commits));
1634 commit->path = new_path;
1635 commit->param.rename.cluster = cluster;
1636 commit->action = ACTION_RENAME;
1639 static void schedule_writeout(BDRVVVFATState* s,
1640 int dir_index, uint32_t modified_offset)
1642 commit_t* commit = array_get_next(&(s->commits));
1643 commit->path = NULL;
1644 commit->param.writeout.dir_index = dir_index;
1645 commit->param.writeout.modified_offset = modified_offset;
1646 commit->action = ACTION_WRITEOUT;
1649 static void schedule_new_file(BDRVVVFATState* s,
1650 char* path, uint32_t first_cluster)
1652 commit_t* commit = array_get_next(&(s->commits));
1653 commit->path = path;
1654 commit->param.new_file.first_cluster = first_cluster;
1655 commit->action = ACTION_NEW_FILE;
1658 static void schedule_mkdir(BDRVVVFATState* s, uint32_t cluster, char* path)
1660 commit_t* commit = array_get_next(&(s->commits));
1661 commit->path = path;
1662 commit->param.mkdir.cluster = cluster;
1663 commit->action = ACTION_MKDIR;
1666 typedef struct {
1668 * Since the sequence number is at most 0x3f, and the filename
1669 * length is at most 13 times the sequence number, the maximal
1670 * filename length is 0x3f * 13 bytes.
1672 unsigned char name[0x3f * 13 + 1];
1673 gunichar2 name2[0x3f * 13 + 1];
1674 int checksum, len;
1675 int sequence_number;
1676 } long_file_name;
1678 static void lfn_init(long_file_name* lfn)
1680 lfn->sequence_number = lfn->len = 0;
1681 lfn->checksum = 0x100;
1684 /* return 0 if parsed successfully, > 0 if no long name, < 0 if error */
1685 static int parse_long_name(long_file_name* lfn,
1686 const direntry_t* direntry)
1688 int i, j, offset;
1689 const unsigned char* pointer = (const unsigned char*)direntry;
1691 if (!is_long_name(direntry))
1692 return 1;
1694 if (pointer[0] & 0x40) {
1695 /* first entry; do some initialization */
1696 lfn->sequence_number = pointer[0] & 0x3f;
1697 lfn->checksum = pointer[13];
1698 lfn->name[0] = 0;
1699 lfn->name[lfn->sequence_number * 13] = 0;
1700 } else if ((pointer[0] & 0x3f) != --lfn->sequence_number) {
1701 /* not the expected sequence number */
1702 return -1;
1703 } else if (pointer[13] != lfn->checksum) {
1704 /* not the expected checksum */
1705 return -2;
1706 } else if (pointer[12] || pointer[26] || pointer[27]) {
1707 /* invalid zero fields */
1708 return -3;
1711 offset = 13 * (lfn->sequence_number - 1);
1712 for (i = 0, j = 1; i < 13; i++, j+=2) {
1713 if (j == 11)
1714 j = 14;
1715 else if (j == 26)
1716 j = 28;
1718 if (pointer[j] == 0 && pointer[j + 1] == 0) {
1719 /* end of long file name */
1720 break;
1722 gunichar2 c = (pointer[j + 1] << 8) + pointer[j];
1723 lfn->name2[offset + i] = c;
1726 if (pointer[0] & 0x40) {
1727 /* first entry; set len */
1728 lfn->len = offset + i;
1730 if ((pointer[0] & 0x3f) == 0x01) {
1731 /* last entry; finalize entry */
1732 glong olen;
1733 gchar *utf8 = g_utf16_to_utf8(lfn->name2, lfn->len, NULL, &olen, NULL);
1734 if (!utf8) {
1735 return -4;
1737 lfn->len = olen;
1738 memcpy(lfn->name, utf8, olen + 1);
1739 g_free(utf8);
1742 return 0;
1745 /* returns 0 if successful, >0 if no short_name, and <0 on error */
1746 static int parse_short_name(BDRVVVFATState* s,
1747 long_file_name* lfn, direntry_t* direntry)
1749 int i, j;
1751 if (!is_short_name(direntry))
1752 return 1;
1754 for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);
1755 for (i = 0; i <= j; i++) {
1756 uint8_t c = direntry->name[i];
1757 if (c != to_valid_short_char(c)) {
1758 return -1;
1759 } else if (s->downcase_short_names) {
1760 lfn->name[i] = qemu_tolower(direntry->name[i]);
1761 } else {
1762 lfn->name[i] = direntry->name[i];
1766 for (j = 2; j >= 0 && direntry->name[8 + j] == ' '; j--) {
1768 if (j >= 0) {
1769 lfn->name[i++] = '.';
1770 lfn->name[i + j + 1] = '\0';
1771 for (;j >= 0; j--) {
1772 uint8_t c = direntry->name[8 + j];
1773 if (c != to_valid_short_char(c)) {
1774 return -2;
1775 } else if (s->downcase_short_names) {
1776 lfn->name[i + j] = qemu_tolower(c);
1777 } else {
1778 lfn->name[i + j] = c;
1781 } else
1782 lfn->name[i + j + 1] = '\0';
1784 if (lfn->name[0] == DIR_KANJI_FAKE) {
1785 lfn->name[0] = DIR_KANJI;
1787 lfn->len = strlen((char*)lfn->name);
1789 return 0;
1792 static inline uint32_t modified_fat_get(BDRVVVFATState* s,
1793 unsigned int cluster)
1795 if (cluster < s->last_cluster_of_root_directory) {
1796 if (cluster + 1 == s->last_cluster_of_root_directory)
1797 return s->max_fat_value;
1798 else
1799 return cluster + 1;
1802 if (s->fat_type==32) {
1803 uint32_t* entry=((uint32_t*)s->fat2)+cluster;
1804 return le32_to_cpu(*entry);
1805 } else if (s->fat_type==16) {
1806 uint16_t* entry=((uint16_t*)s->fat2)+cluster;
1807 return le16_to_cpu(*entry);
1808 } else {
1809 const uint8_t* x=s->fat2+cluster*3/2;
1810 return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
1814 static inline bool cluster_was_modified(BDRVVVFATState *s,
1815 uint32_t cluster_num)
1817 int was_modified = 0;
1818 int i;
1820 if (s->qcow == NULL) {
1821 return 0;
1824 for (i = 0; !was_modified && i < s->sectors_per_cluster; i++) {
1825 was_modified = bdrv_is_allocated(s->qcow->bs,
1826 (cluster2sector(s, cluster_num) +
1827 i) * BDRV_SECTOR_SIZE,
1828 BDRV_SECTOR_SIZE, NULL);
1832 * Note that this treats failures to learn allocation status the
1833 * same as if an allocation has occurred. It's as safe as
1834 * anything else, given that a failure to learn allocation status
1835 * will probably result in more failures.
1837 return !!was_modified;
1840 static const char* get_basename(const char* path)
1842 char* basename = strrchr(path, '/');
1843 if (basename == NULL)
1844 return path;
1845 else
1846 return basename + 1; /* strip '/' */
1850 * The array s->used_clusters holds the states of the clusters. If it is
1851 * part of a file, it has bit 2 set, in case of a directory, bit 1. If it
1852 * was modified, bit 3 is set.
1853 * If any cluster is allocated, but not part of a file or directory, this
1854 * driver refuses to commit.
1856 typedef enum {
1857 USED_DIRECTORY = 1, USED_FILE = 2, USED_ANY = 3, USED_ALLOCATED = 4
1858 } used_t;
1861 * get_cluster_count_for_direntry() not only determines how many clusters
1862 * are occupied by direntry, but also if it was renamed or modified.
1864 * A file is thought to be renamed *only* if there already was a file with
1865 * exactly the same first cluster, but a different name.
1867 * Further, the files/directories handled by this function are
1868 * assumed to be *not* deleted (and *only* those).
1870 static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,
1871 direntry_t* direntry, const char* path)
1874 * This is a little bit tricky:
1875 * IF the guest OS just inserts a cluster into the file chain,
1876 * and leaves the rest alone, (i.e. the original file had clusters
1877 * 15 -> 16, but now has 15 -> 32 -> 16), then the following happens:
1879 * - do_commit will write the cluster into the file at the given
1880 * offset, but
1882 * - the cluster which is overwritten should be moved to a later
1883 * position in the file.
1885 * I am not aware that any OS does something as braindead, but this
1886 * situation could happen anyway when not committing for a long time.
1887 * Just to be sure that this does not bite us, detect it, and copy the
1888 * contents of the clusters to-be-overwritten into the qcow.
1890 int copy_it = 0;
1891 int was_modified = 0;
1892 int32_t ret = 0;
1894 uint32_t cluster_num = begin_of_direntry(direntry);
1895 uint32_t offset = 0;
1896 int first_mapping_index = -1;
1897 mapping_t* mapping = NULL;
1898 const char* basename2 = NULL;
1900 vvfat_close_current_file(s);
1902 /* the root directory */
1903 if (cluster_num == 0)
1904 return 0;
1906 /* write support */
1907 if (s->qcow) {
1908 basename2 = get_basename(path);
1910 mapping = find_mapping_for_cluster(s, cluster_num);
1912 if (mapping) {
1913 const char* basename;
1915 assert(mapping->mode & MODE_DELETED);
1916 mapping->mode &= ~MODE_DELETED;
1918 basename = get_basename(mapping->path);
1920 assert(mapping->mode & MODE_NORMAL);
1922 /* rename */
1923 if (strcmp(basename, basename2))
1924 schedule_rename(s, cluster_num, g_strdup(path));
1925 } else if (is_file(direntry))
1926 /* new file */
1927 schedule_new_file(s, g_strdup(path), cluster_num);
1928 else {
1929 abort();
1930 return 0;
1934 while(1) {
1935 if (s->qcow) {
1936 if (!copy_it && cluster_was_modified(s, cluster_num)) {
1937 if (mapping == NULL ||
1938 mapping->begin > cluster_num ||
1939 mapping->end <= cluster_num)
1940 mapping = find_mapping_for_cluster(s, cluster_num);
1943 if (mapping &&
1944 (mapping->mode & MODE_DIRECTORY) == 0) {
1946 /* was modified in qcow */
1947 if (offset != mapping->info.file.offset + s->cluster_size
1948 * (cluster_num - mapping->begin)) {
1949 /* offset of this cluster in file chain has changed */
1950 abort();
1951 copy_it = 1;
1952 } else if (offset == 0) {
1953 const char* basename = get_basename(mapping->path);
1955 if (strcmp(basename, basename2))
1956 copy_it = 1;
1957 first_mapping_index = array_index(&(s->mapping), mapping);
1960 if (mapping->first_mapping_index != first_mapping_index
1961 && mapping->info.file.offset > 0) {
1962 abort();
1963 copy_it = 1;
1966 /* need to write out? */
1967 if (!was_modified && is_file(direntry)) {
1968 was_modified = 1;
1969 schedule_writeout(s, mapping->dir_index, offset);
1974 if (copy_it) {
1975 int i;
1977 * This is horribly inefficient, but that is okay, since
1978 * it is rarely executed, if at all.
1980 int64_t offset = cluster2sector(s, cluster_num);
1982 vvfat_close_current_file(s);
1983 for (i = 0; i < s->sectors_per_cluster; i++) {
1984 int res;
1986 res = bdrv_is_allocated(s->qcow->bs,
1987 (offset + i) * BDRV_SECTOR_SIZE,
1988 BDRV_SECTOR_SIZE, NULL);
1989 if (res < 0) {
1990 return -1;
1992 if (!res) {
1993 res = vvfat_read(s->bs, offset, s->cluster_buffer, 1);
1994 if (res) {
1995 return -1;
1997 res = bdrv_write(s->qcow, offset, s->cluster_buffer, 1);
1998 if (res) {
1999 return -2;
2006 ret++;
2007 if (s->used_clusters[cluster_num] & USED_ANY)
2008 return 0;
2009 s->used_clusters[cluster_num] = USED_FILE;
2011 cluster_num = modified_fat_get(s, cluster_num);
2013 if (fat_eof(s, cluster_num))
2014 return ret;
2015 else if (cluster_num < 2 || cluster_num > s->max_fat_value - 16)
2016 return -1;
2018 offset += s->cluster_size;
2023 * This function looks at the modified data (qcow).
2024 * It returns 0 upon inconsistency or error, and the number of clusters
2025 * used by the directory, its subdirectories and their files.
2027 static int check_directory_consistency(BDRVVVFATState *s,
2028 int cluster_num, const char* path)
2030 int ret = 0;
2031 unsigned char* cluster = g_malloc(s->cluster_size);
2032 direntry_t* direntries = (direntry_t*)cluster;
2033 mapping_t* mapping = find_mapping_for_cluster(s, cluster_num);
2035 long_file_name lfn;
2036 int path_len = strlen(path);
2037 char path2[PATH_MAX + 1];
2039 assert(path_len < PATH_MAX); /* len was tested before! */
2040 pstrcpy(path2, sizeof(path2), path);
2041 path2[path_len] = '/';
2042 path2[path_len + 1] = '\0';
2044 if (mapping) {
2045 const char* basename = get_basename(mapping->path);
2046 const char* basename2 = get_basename(path);
2048 assert(mapping->mode & MODE_DIRECTORY);
2050 assert(mapping->mode & MODE_DELETED);
2051 mapping->mode &= ~MODE_DELETED;
2053 if (strcmp(basename, basename2))
2054 schedule_rename(s, cluster_num, g_strdup(path));
2055 } else
2056 /* new directory */
2057 schedule_mkdir(s, cluster_num, g_strdup(path));
2059 lfn_init(&lfn);
2060 do {
2061 int i;
2062 int subret = 0;
2064 ret++;
2066 if (s->used_clusters[cluster_num] & USED_ANY) {
2067 fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num);
2068 goto fail;
2070 s->used_clusters[cluster_num] = USED_DIRECTORY;
2072 DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num)));
2073 subret = vvfat_read(s->bs, cluster2sector(s, cluster_num), cluster,
2074 s->sectors_per_cluster);
2075 if (subret) {
2076 fprintf(stderr, "Error fetching direntries\n");
2077 fail:
2078 g_free(cluster);
2079 return 0;
2082 for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) {
2083 int cluster_count = 0;
2085 DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i));
2086 if (is_volume_label(direntries + i) || is_dot(direntries + i) ||
2087 is_free(direntries + i))
2088 continue;
2090 subret = parse_long_name(&lfn, direntries + i);
2091 if (subret < 0) {
2092 fprintf(stderr, "Error in long name\n");
2093 goto fail;
2095 if (subret == 0 || is_free(direntries + i))
2096 continue;
2098 if (fat_chksum(direntries+i) != lfn.checksum) {
2099 subret = parse_short_name(s, &lfn, direntries + i);
2100 if (subret < 0) {
2101 fprintf(stderr, "Error in short name (%d)\n", subret);
2102 goto fail;
2104 if (subret > 0 || !strcmp((char*)lfn.name, ".")
2105 || !strcmp((char*)lfn.name, ".."))
2106 continue;
2108 lfn.checksum = 0x100; /* cannot use long name twice */
2110 if (path_len + 1 + lfn.len >= PATH_MAX) {
2111 fprintf(stderr, "Name too long: %s/%s\n", path, lfn.name);
2112 goto fail;
2114 pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1,
2115 (char*)lfn.name);
2117 if (is_directory(direntries + i)) {
2118 if (begin_of_direntry(direntries + i) == 0) {
2119 DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i));
2120 goto fail;
2122 cluster_count = check_directory_consistency(s,
2123 begin_of_direntry(direntries + i), path2);
2124 if (cluster_count == 0) {
2125 DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i));
2126 goto fail;
2128 } else if (is_file(direntries + i)) {
2129 /* check file size with FAT */
2130 cluster_count = get_cluster_count_for_direntry(s, direntries + i, path2);
2131 if (cluster_count !=
2132 DIV_ROUND_UP(le32_to_cpu(direntries[i].size), s->cluster_size)) {
2133 DLOG(fprintf(stderr, "Cluster count mismatch\n"));
2134 goto fail;
2136 } else
2137 abort(); /* cluster_count = 0; */
2139 ret += cluster_count;
2142 cluster_num = modified_fat_get(s, cluster_num);
2143 } while(!fat_eof(s, cluster_num));
2145 g_free(cluster);
2146 return ret;
2149 /* returns 1 on success */
2150 static int is_consistent(BDRVVVFATState* s)
2152 int i, check;
2153 int used_clusters_count = 0;
2155 DLOG(checkpoint());
2157 * - get modified FAT
2158 * - compare the two FATs (TODO)
2159 * - get buffer for marking used clusters
2160 * - recurse direntries from root (using bs->bdrv_read to make
2161 * sure to get the new data)
2162 * - check that the FAT agrees with the size
2163 * - count the number of clusters occupied by this directory and
2164 * its files
2165 * - check that the cumulative used cluster count agrees with the
2166 * FAT
2167 * - if all is fine, return number of used clusters
2169 if (s->fat2 == NULL) {
2170 int size = 0x200 * s->sectors_per_fat;
2171 s->fat2 = g_malloc(size);
2172 memcpy(s->fat2, s->fat.pointer, size);
2174 check = vvfat_read(s->bs,
2175 s->offset_to_fat, s->fat2, s->sectors_per_fat);
2176 if (check) {
2177 fprintf(stderr, "Could not copy fat\n");
2178 return 0;
2180 assert (s->used_clusters);
2181 for (i = 0; i < sector2cluster(s, s->sector_count); i++)
2182 s->used_clusters[i] &= ~USED_ANY;
2184 clear_commits(s);
2186 /* mark every mapped file/directory as deleted.
2187 * (check_directory_consistency() will unmark those still present). */
2188 if (s->qcow)
2189 for (i = 0; i < s->mapping.next; i++) {
2190 mapping_t* mapping = array_get(&(s->mapping), i);
2191 if (mapping->first_mapping_index < 0)
2192 mapping->mode |= MODE_DELETED;
2195 used_clusters_count = check_directory_consistency(s, 0, s->path);
2196 if (used_clusters_count <= 0) {
2197 DLOG(fprintf(stderr, "problem in directory\n"));
2198 return 0;
2201 check = s->last_cluster_of_root_directory;
2202 for (i = check; i < sector2cluster(s, s->sector_count); i++) {
2203 if (modified_fat_get(s, i)) {
2204 if(!s->used_clusters[i]) {
2205 DLOG(fprintf(stderr, "FAT was modified (%d), but cluster is not used?\n", i));
2206 return 0;
2208 check++;
2211 if (s->used_clusters[i] == USED_ALLOCATED) {
2212 /* allocated, but not used... */
2213 DLOG(fprintf(stderr, "unused, modified cluster: %d\n", i));
2214 return 0;
2218 if (check != used_clusters_count)
2219 return 0;
2221 return used_clusters_count;
2224 static inline void adjust_mapping_indices(BDRVVVFATState* s,
2225 int offset, int adjust)
2227 int i;
2229 for (i = 0; i < s->mapping.next; i++) {
2230 mapping_t* mapping = array_get(&(s->mapping), i);
2232 #define ADJUST_MAPPING_INDEX(name) \
2233 if (mapping->name >= offset) \
2234 mapping->name += adjust
2236 ADJUST_MAPPING_INDEX(first_mapping_index);
2237 if (mapping->mode & MODE_DIRECTORY)
2238 ADJUST_MAPPING_INDEX(info.dir.parent_mapping_index);
2242 /* insert or update mapping */
2243 static mapping_t* insert_mapping(BDRVVVFATState* s,
2244 uint32_t begin, uint32_t end)
2247 * - find mapping where mapping->begin >= begin,
2248 * - if mapping->begin > begin: insert
2249 * - adjust all references to mappings!
2250 * - else: adjust
2251 * - replace name
2253 int index = find_mapping_for_cluster_aux(s, begin, 0, s->mapping.next);
2254 mapping_t* mapping = NULL;
2255 mapping_t* first_mapping = array_get(&(s->mapping), 0);
2257 if (index < s->mapping.next && (mapping = array_get(&(s->mapping), index))
2258 && mapping->begin < begin) {
2259 mapping->end = begin;
2260 index++;
2261 mapping = array_get(&(s->mapping), index);
2263 if (index >= s->mapping.next || mapping->begin > begin) {
2264 mapping = array_insert(&(s->mapping), index, 1);
2265 mapping->path = NULL;
2266 adjust_mapping_indices(s, index, +1);
2269 mapping->begin = begin;
2270 mapping->end = end;
2272 DLOG(mapping_t* next_mapping;
2273 assert(index + 1 >= s->mapping.next ||
2274 ((next_mapping = array_get(&(s->mapping), index + 1)) &&
2275 next_mapping->begin >= end)));
2277 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
2278 s->current_mapping = array_get(&(s->mapping),
2279 s->current_mapping - first_mapping);
2281 return mapping;
2284 static int remove_mapping(BDRVVVFATState* s, int mapping_index)
2286 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
2287 mapping_t* first_mapping = array_get(&(s->mapping), 0);
2289 /* free mapping */
2290 if (mapping->first_mapping_index < 0) {
2291 g_free(mapping->path);
2294 /* remove from s->mapping */
2295 array_remove(&(s->mapping), mapping_index);
2297 /* adjust all references to mappings */
2298 adjust_mapping_indices(s, mapping_index, -1);
2300 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
2301 s->current_mapping = array_get(&(s->mapping),
2302 s->current_mapping - first_mapping);
2304 return 0;
2307 static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust)
2309 int i;
2310 for (i = 0; i < s->mapping.next; i++) {
2311 mapping_t* mapping = array_get(&(s->mapping), i);
2312 if (mapping->dir_index >= offset)
2313 mapping->dir_index += adjust;
2314 if ((mapping->mode & MODE_DIRECTORY) &&
2315 mapping->info.dir.first_dir_index >= offset)
2316 mapping->info.dir.first_dir_index += adjust;
2320 static direntry_t* insert_direntries(BDRVVVFATState* s,
2321 int dir_index, int count)
2324 * make room in s->directory,
2325 * adjust_dirindices
2327 direntry_t* result = array_insert(&(s->directory), dir_index, count);
2328 if (result == NULL)
2329 return NULL;
2330 adjust_dirindices(s, dir_index, count);
2331 return result;
2334 static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)
2336 int ret = array_remove_slice(&(s->directory), dir_index, count);
2337 if (ret)
2338 return ret;
2339 adjust_dirindices(s, dir_index, -count);
2340 return 0;
2344 * Adapt the mappings of the cluster chain starting at first cluster
2345 * (i.e. if a file starts at first_cluster, the chain is followed according
2346 * to the modified fat, and the corresponding entries in s->mapping are
2347 * adjusted)
2349 static int commit_mappings(BDRVVVFATState* s,
2350 uint32_t first_cluster, int dir_index)
2352 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2353 direntry_t* direntry = array_get(&(s->directory), dir_index);
2354 uint32_t cluster = first_cluster;
2356 vvfat_close_current_file(s);
2358 assert(mapping);
2359 assert(mapping->begin == first_cluster);
2360 mapping->first_mapping_index = -1;
2361 mapping->dir_index = dir_index;
2362 mapping->mode = (dir_index <= 0 || is_directory(direntry)) ?
2363 MODE_DIRECTORY : MODE_NORMAL;
2365 while (!fat_eof(s, cluster)) {
2366 uint32_t c, c1;
2368 for (c = cluster, c1 = modified_fat_get(s, c); c + 1 == c1;
2369 c = c1, c1 = modified_fat_get(s, c1));
2371 c++;
2372 if (c > mapping->end) {
2373 int index = array_index(&(s->mapping), mapping);
2374 int i, max_i = s->mapping.next - index;
2375 for (i = 1; i < max_i && mapping[i].begin < c; i++);
2376 while (--i > 0)
2377 remove_mapping(s, index + 1);
2379 assert(mapping == array_get(&(s->mapping), s->mapping.next - 1)
2380 || mapping[1].begin >= c);
2381 mapping->end = c;
2383 if (!fat_eof(s, c1)) {
2384 int i = find_mapping_for_cluster_aux(s, c1, 0, s->mapping.next);
2385 mapping_t* next_mapping = i >= s->mapping.next ? NULL :
2386 array_get(&(s->mapping), i);
2388 if (next_mapping == NULL || next_mapping->begin > c1) {
2389 int i1 = array_index(&(s->mapping), mapping);
2391 next_mapping = insert_mapping(s, c1, c1+1);
2393 if (c1 < c)
2394 i1++;
2395 mapping = array_get(&(s->mapping), i1);
2398 next_mapping->dir_index = mapping->dir_index;
2399 next_mapping->first_mapping_index =
2400 mapping->first_mapping_index < 0 ?
2401 array_index(&(s->mapping), mapping) :
2402 mapping->first_mapping_index;
2403 next_mapping->path = mapping->path;
2404 next_mapping->mode = mapping->mode;
2405 next_mapping->read_only = mapping->read_only;
2406 if (mapping->mode & MODE_DIRECTORY) {
2407 next_mapping->info.dir.parent_mapping_index =
2408 mapping->info.dir.parent_mapping_index;
2409 next_mapping->info.dir.first_dir_index =
2410 mapping->info.dir.first_dir_index +
2411 0x10 * s->sectors_per_cluster *
2412 (mapping->end - mapping->begin);
2413 } else
2414 next_mapping->info.file.offset = mapping->info.file.offset +
2415 mapping->end - mapping->begin;
2417 mapping = next_mapping;
2420 cluster = c1;
2423 return 0;
2426 static int commit_direntries(BDRVVVFATState* s,
2427 int dir_index, int parent_mapping_index)
2429 direntry_t* direntry = array_get(&(s->directory), dir_index);
2430 uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);
2431 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2433 int factor = 0x10 * s->sectors_per_cluster;
2434 int old_cluster_count, new_cluster_count;
2435 int current_dir_index = mapping->info.dir.first_dir_index;
2436 int first_dir_index = current_dir_index;
2437 int ret, i;
2438 uint32_t c;
2440 DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapping->path, parent_mapping_index));
2442 assert(direntry);
2443 assert(mapping);
2444 assert(mapping->begin == first_cluster);
2445 assert(mapping->info.dir.first_dir_index < s->directory.next);
2446 assert(mapping->mode & MODE_DIRECTORY);
2447 assert(dir_index == 0 || is_directory(direntry));
2449 mapping->info.dir.parent_mapping_index = parent_mapping_index;
2451 if (first_cluster == 0) {
2452 old_cluster_count = new_cluster_count =
2453 s->last_cluster_of_root_directory;
2454 } else {
2455 for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2456 c = fat_get(s, c))
2457 old_cluster_count++;
2459 for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2460 c = modified_fat_get(s, c))
2461 new_cluster_count++;
2464 if (new_cluster_count > old_cluster_count) {
2465 if (insert_direntries(s,
2466 current_dir_index + factor * old_cluster_count,
2467 factor * (new_cluster_count - old_cluster_count)) == NULL)
2468 return -1;
2469 } else if (new_cluster_count < old_cluster_count)
2470 remove_direntries(s,
2471 current_dir_index + factor * new_cluster_count,
2472 factor * (old_cluster_count - new_cluster_count));
2474 for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {
2475 direntry_t *first_direntry;
2476 void* direntry = array_get(&(s->directory), current_dir_index);
2477 int ret = vvfat_read(s->bs, cluster2sector(s, c), direntry,
2478 s->sectors_per_cluster);
2479 if (ret)
2480 return ret;
2482 /* The first directory entry on the filesystem is the volume name */
2483 first_direntry = (direntry_t*) s->directory.pointer;
2484 assert(!memcmp(first_direntry->name, s->volume_label, 11));
2486 current_dir_index += factor;
2489 ret = commit_mappings(s, first_cluster, dir_index);
2490 if (ret)
2491 return ret;
2493 /* recurse */
2494 for (i = 0; i < factor * new_cluster_count; i++) {
2495 direntry = array_get(&(s->directory), first_dir_index + i);
2496 if (is_directory(direntry) && !is_dot(direntry)) {
2497 mapping = find_mapping_for_cluster(s, first_cluster);
2498 assert(mapping->mode & MODE_DIRECTORY);
2499 ret = commit_direntries(s, first_dir_index + i,
2500 array_index(&(s->mapping), mapping));
2501 if (ret)
2502 return ret;
2506 return 0;
2509 /* commit one file (adjust contents, adjust mapping),
2510 return first_mapping_index */
2511 static int commit_one_file(BDRVVVFATState* s,
2512 int dir_index, uint32_t offset)
2514 direntry_t* direntry = array_get(&(s->directory), dir_index);
2515 uint32_t c = begin_of_direntry(direntry);
2516 uint32_t first_cluster = c;
2517 mapping_t* mapping = find_mapping_for_cluster(s, c);
2518 uint32_t size = filesize_of_direntry(direntry);
2519 char* cluster = g_malloc(s->cluster_size);
2520 uint32_t i;
2521 int fd = 0;
2523 assert(offset < size);
2524 assert((offset % s->cluster_size) == 0);
2526 for (i = s->cluster_size; i < offset; i += s->cluster_size)
2527 c = modified_fat_get(s, c);
2529 fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
2530 if (fd < 0) {
2531 fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
2532 strerror(errno), errno);
2533 g_free(cluster);
2534 return fd;
2536 if (offset > 0) {
2537 if (lseek(fd, offset, SEEK_SET) != offset) {
2538 qemu_close(fd);
2539 g_free(cluster);
2540 return -3;
2544 while (offset < size) {
2545 uint32_t c1;
2546 int rest_size = (size - offset > s->cluster_size ?
2547 s->cluster_size : size - offset);
2548 int ret;
2550 c1 = modified_fat_get(s, c);
2552 assert((size - offset == 0 && fat_eof(s, c)) ||
2553 (size > offset && c >=2 && !fat_eof(s, c)));
2555 ret = vvfat_read(s->bs, cluster2sector(s, c),
2556 (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
2558 if (ret < 0) {
2559 qemu_close(fd);
2560 g_free(cluster);
2561 return ret;
2564 if (write(fd, cluster, rest_size) < 0) {
2565 qemu_close(fd);
2566 g_free(cluster);
2567 return -2;
2570 offset += rest_size;
2571 c = c1;
2574 if (ftruncate(fd, size)) {
2575 perror("ftruncate()");
2576 qemu_close(fd);
2577 g_free(cluster);
2578 return -4;
2580 qemu_close(fd);
2581 g_free(cluster);
2583 return commit_mappings(s, first_cluster, dir_index);
2586 #ifdef DEBUG
2587 /* test, if all mappings point to valid direntries */
2588 static void check1(BDRVVVFATState* s)
2590 int i;
2591 for (i = 0; i < s->mapping.next; i++) {
2592 mapping_t* mapping = array_get(&(s->mapping), i);
2593 if (mapping->mode & MODE_DELETED) {
2594 fprintf(stderr, "deleted\n");
2595 continue;
2597 assert(mapping->dir_index < s->directory.next);
2598 direntry_t* direntry = array_get(&(s->directory), mapping->dir_index);
2599 assert(mapping->begin == begin_of_direntry(direntry) || mapping->first_mapping_index >= 0);
2600 if (mapping->mode & MODE_DIRECTORY) {
2601 assert(mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster * (mapping->end - mapping->begin) <= s->directory.next);
2602 assert((mapping->info.dir.first_dir_index % (0x10 * s->sectors_per_cluster)) == 0);
2607 /* test, if all direntries have mappings */
2608 static void check2(BDRVVVFATState* s)
2610 int i;
2611 int first_mapping = -1;
2613 for (i = 0; i < s->directory.next; i++) {
2614 direntry_t* direntry = array_get(&(s->directory), i);
2616 if (is_short_name(direntry) && begin_of_direntry(direntry)) {
2617 mapping_t* mapping = find_mapping_for_cluster(s, begin_of_direntry(direntry));
2618 assert(mapping);
2619 assert(mapping->dir_index == i || is_dot(direntry));
2620 assert(mapping->begin == begin_of_direntry(direntry) || is_dot(direntry));
2623 if ((i % (0x10 * s->sectors_per_cluster)) == 0) {
2624 /* cluster start */
2625 int j, count = 0;
2627 for (j = 0; j < s->mapping.next; j++) {
2628 mapping_t* mapping = array_get(&(s->mapping), j);
2629 if (mapping->mode & MODE_DELETED)
2630 continue;
2631 if (mapping->mode & MODE_DIRECTORY) {
2632 if (mapping->info.dir.first_dir_index <= i && mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster > i) {
2633 assert(++count == 1);
2634 if (mapping->first_mapping_index == -1)
2635 first_mapping = array_index(&(s->mapping), mapping);
2636 else
2637 assert(first_mapping == mapping->first_mapping_index);
2638 if (mapping->info.dir.parent_mapping_index < 0)
2639 assert(j == 0);
2640 else {
2641 mapping_t* parent = array_get(&(s->mapping), mapping->info.dir.parent_mapping_index);
2642 assert(parent->mode & MODE_DIRECTORY);
2643 assert(parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index);
2648 if (count == 0)
2649 first_mapping = -1;
2653 #endif
2655 static int handle_renames_and_mkdirs(BDRVVVFATState* s)
2657 int i;
2659 #ifdef DEBUG
2660 fprintf(stderr, "handle_renames\n");
2661 for (i = 0; i < s->commits.next; i++) {
2662 commit_t* commit = array_get(&(s->commits), i);
2663 fprintf(stderr, "%d, %s (%d, %d)\n", i, commit->path ? commit->path : "(null)", commit->param.rename.cluster, commit->action);
2665 #endif
2667 for (i = 0; i < s->commits.next;) {
2668 commit_t* commit = array_get(&(s->commits), i);
2669 if (commit->action == ACTION_RENAME) {
2670 mapping_t* mapping = find_mapping_for_cluster(s,
2671 commit->param.rename.cluster);
2672 char* old_path = mapping->path;
2674 assert(commit->path);
2675 mapping->path = commit->path;
2676 if (rename(old_path, mapping->path))
2677 return -2;
2679 if (mapping->mode & MODE_DIRECTORY) {
2680 int l1 = strlen(mapping->path);
2681 int l2 = strlen(old_path);
2682 int diff = l1 - l2;
2683 direntry_t* direntry = array_get(&(s->directory),
2684 mapping->info.dir.first_dir_index);
2685 uint32_t c = mapping->begin;
2686 int i = 0;
2688 /* recurse */
2689 while (!fat_eof(s, c)) {
2690 do {
2691 direntry_t* d = direntry + i;
2693 if (is_file(d) || (is_directory(d) && !is_dot(d))) {
2694 mapping_t* m = find_mapping_for_cluster(s,
2695 begin_of_direntry(d));
2696 int l = strlen(m->path);
2697 char* new_path = g_malloc(l + diff + 1);
2699 assert(!strncmp(m->path, mapping->path, l2));
2701 pstrcpy(new_path, l + diff + 1, mapping->path);
2702 pstrcpy(new_path + l1, l + diff + 1 - l1,
2703 m->path + l2);
2705 schedule_rename(s, m->begin, new_path);
2707 i++;
2708 } while((i % (0x10 * s->sectors_per_cluster)) != 0);
2709 c = fat_get(s, c);
2713 g_free(old_path);
2714 array_remove(&(s->commits), i);
2715 continue;
2716 } else if (commit->action == ACTION_MKDIR) {
2717 mapping_t* mapping;
2718 int j, parent_path_len;
2720 #ifdef __MINGW32__
2721 if (mkdir(commit->path))
2722 return -5;
2723 #else
2724 if (mkdir(commit->path, 0755))
2725 return -5;
2726 #endif
2728 mapping = insert_mapping(s, commit->param.mkdir.cluster,
2729 commit->param.mkdir.cluster + 1);
2730 if (mapping == NULL)
2731 return -6;
2733 mapping->mode = MODE_DIRECTORY;
2734 mapping->read_only = 0;
2735 mapping->path = commit->path;
2736 j = s->directory.next;
2737 assert(j);
2738 insert_direntries(s, s->directory.next,
2739 0x10 * s->sectors_per_cluster);
2740 mapping->info.dir.first_dir_index = j;
2742 parent_path_len = strlen(commit->path)
2743 - strlen(get_basename(commit->path)) - 1;
2744 for (j = 0; j < s->mapping.next; j++) {
2745 mapping_t* m = array_get(&(s->mapping), j);
2746 if (m->first_mapping_index < 0 && m != mapping &&
2747 !strncmp(m->path, mapping->path, parent_path_len) &&
2748 strlen(m->path) == parent_path_len)
2749 break;
2751 assert(j < s->mapping.next);
2752 mapping->info.dir.parent_mapping_index = j;
2754 array_remove(&(s->commits), i);
2755 continue;
2758 i++;
2760 return 0;
2764 * TODO: make sure that the short name is not matching *another* file
2766 static int handle_commits(BDRVVVFATState* s)
2768 int i, fail = 0;
2770 vvfat_close_current_file(s);
2772 for (i = 0; !fail && i < s->commits.next; i++) {
2773 commit_t* commit = array_get(&(s->commits), i);
2774 switch(commit->action) {
2775 case ACTION_RENAME: case ACTION_MKDIR:
2776 abort();
2777 fail = -2;
2778 break;
2779 case ACTION_WRITEOUT: {
2780 #ifndef NDEBUG
2781 /* these variables are only used by assert() below */
2782 direntry_t* entry = array_get(&(s->directory),
2783 commit->param.writeout.dir_index);
2784 uint32_t begin = begin_of_direntry(entry);
2785 mapping_t* mapping = find_mapping_for_cluster(s, begin);
2786 #endif
2788 assert(mapping);
2789 assert(mapping->begin == begin);
2790 assert(commit->path == NULL);
2792 if (commit_one_file(s, commit->param.writeout.dir_index,
2793 commit->param.writeout.modified_offset))
2794 fail = -3;
2796 break;
2798 case ACTION_NEW_FILE: {
2799 int begin = commit->param.new_file.first_cluster;
2800 mapping_t* mapping = find_mapping_for_cluster(s, begin);
2801 direntry_t* entry;
2802 int i;
2804 /* find direntry */
2805 for (i = 0; i < s->directory.next; i++) {
2806 entry = array_get(&(s->directory), i);
2807 if (is_file(entry) && begin_of_direntry(entry) == begin)
2808 break;
2811 if (i >= s->directory.next) {
2812 fail = -6;
2813 continue;
2816 /* make sure there exists an initial mapping */
2817 if (mapping && mapping->begin != begin) {
2818 mapping->end = begin;
2819 mapping = NULL;
2821 if (mapping == NULL) {
2822 mapping = insert_mapping(s, begin, begin+1);
2824 /* most members will be fixed in commit_mappings() */
2825 assert(commit->path);
2826 mapping->path = commit->path;
2827 mapping->read_only = 0;
2828 mapping->mode = MODE_NORMAL;
2829 mapping->info.file.offset = 0;
2831 if (commit_one_file(s, i, 0))
2832 fail = -7;
2834 break;
2836 default:
2837 abort();
2840 if (i > 0 && array_remove_slice(&(s->commits), 0, i))
2841 return -1;
2842 return fail;
2845 static int handle_deletes(BDRVVVFATState* s)
2847 int i, deferred = 1, deleted = 1;
2849 /* delete files corresponding to mappings marked as deleted */
2850 /* handle DELETEs and unused mappings (modified_fat_get(s, mapping->begin) == 0) */
2851 while (deferred && deleted) {
2852 deferred = 0;
2853 deleted = 0;
2855 for (i = 1; i < s->mapping.next; i++) {
2856 mapping_t* mapping = array_get(&(s->mapping), i);
2857 if (mapping->mode & MODE_DELETED) {
2858 direntry_t* entry = array_get(&(s->directory),
2859 mapping->dir_index);
2861 if (is_free(entry)) {
2862 /* remove file/directory */
2863 if (mapping->mode & MODE_DIRECTORY) {
2864 int j, next_dir_index = s->directory.next,
2865 first_dir_index = mapping->info.dir.first_dir_index;
2867 if (rmdir(mapping->path) < 0) {
2868 if (errno == ENOTEMPTY) {
2869 deferred++;
2870 continue;
2871 } else
2872 return -5;
2875 for (j = 1; j < s->mapping.next; j++) {
2876 mapping_t* m = array_get(&(s->mapping), j);
2877 if (m->mode & MODE_DIRECTORY &&
2878 m->info.dir.first_dir_index >
2879 first_dir_index &&
2880 m->info.dir.first_dir_index <
2881 next_dir_index)
2882 next_dir_index =
2883 m->info.dir.first_dir_index;
2885 remove_direntries(s, first_dir_index,
2886 next_dir_index - first_dir_index);
2888 deleted++;
2890 } else {
2891 if (unlink(mapping->path))
2892 return -4;
2893 deleted++;
2895 DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry));
2896 remove_mapping(s, i);
2901 return 0;
2905 * synchronize mapping with new state:
2907 * - copy FAT (with bdrv_read)
2908 * - mark all filenames corresponding to mappings as deleted
2909 * - recurse direntries from root (using bs->bdrv_read)
2910 * - delete files corresponding to mappings marked as deleted
2912 static int do_commit(BDRVVVFATState* s)
2914 int ret = 0;
2916 /* the real meat are the commits. Nothing to do? Move along! */
2917 if (s->commits.next == 0)
2918 return 0;
2920 vvfat_close_current_file(s);
2922 ret = handle_renames_and_mkdirs(s);
2923 if (ret) {
2924 fprintf(stderr, "Error handling renames (%d)\n", ret);
2925 abort();
2926 return ret;
2929 /* copy FAT (with bdrv_read) */
2930 memcpy(s->fat.pointer, s->fat2, 0x200 * s->sectors_per_fat);
2932 /* recurse direntries from root (using bs->bdrv_read) */
2933 ret = commit_direntries(s, 0, -1);
2934 if (ret) {
2935 fprintf(stderr, "Fatal: error while committing (%d)\n", ret);
2936 abort();
2937 return ret;
2940 ret = handle_commits(s);
2941 if (ret) {
2942 fprintf(stderr, "Error handling commits (%d)\n", ret);
2943 abort();
2944 return ret;
2947 ret = handle_deletes(s);
2948 if (ret) {
2949 fprintf(stderr, "Error deleting\n");
2950 abort();
2951 return ret;
2954 if (s->qcow->bs->drv->bdrv_make_empty) {
2955 s->qcow->bs->drv->bdrv_make_empty(s->qcow->bs);
2958 memset(s->used_clusters, 0, sector2cluster(s, s->sector_count));
2960 DLOG(checkpoint());
2961 return 0;
2964 static int try_commit(BDRVVVFATState* s)
2966 vvfat_close_current_file(s);
2967 DLOG(checkpoint());
2968 if(!is_consistent(s))
2969 return -1;
2970 return do_commit(s);
2973 static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
2974 const uint8_t *buf, int nb_sectors)
2976 BDRVVVFATState *s = bs->opaque;
2977 int i, ret;
2979 DLOG(checkpoint());
2981 /* Check if we're operating in read-only mode */
2982 if (s->qcow == NULL) {
2983 return -EACCES;
2986 vvfat_close_current_file(s);
2989 * Some sanity checks:
2990 * - do not allow writing to the boot sector
2993 if (sector_num < s->offset_to_fat)
2994 return -1;
2996 for (i = sector2cluster(s, sector_num);
2997 i <= sector2cluster(s, sector_num + nb_sectors - 1);) {
2998 mapping_t* mapping = find_mapping_for_cluster(s, i);
2999 if (mapping) {
3000 if (mapping->read_only) {
3001 fprintf(stderr, "Tried to write to write-protected file %s\n",
3002 mapping->path);
3003 return -1;
3006 if (mapping->mode & MODE_DIRECTORY) {
3007 int begin = cluster2sector(s, i);
3008 int end = begin + s->sectors_per_cluster, k;
3009 int dir_index;
3010 const direntry_t* direntries;
3011 long_file_name lfn;
3013 lfn_init(&lfn);
3015 if (begin < sector_num)
3016 begin = sector_num;
3017 if (end > sector_num + nb_sectors)
3018 end = sector_num + nb_sectors;
3019 dir_index = mapping->dir_index +
3020 0x10 * (begin - mapping->begin * s->sectors_per_cluster);
3021 direntries = (direntry_t*)(buf + 0x200 * (begin - sector_num));
3023 for (k = 0; k < (end - begin) * 0x10; k++) {
3024 /* no access to the direntry of a read-only file */
3025 if (is_short_name(direntries + k) &&
3026 (direntries[k].attributes & 1)) {
3027 if (memcmp(direntries + k,
3028 array_get(&(s->directory), dir_index + k),
3029 sizeof(direntry_t))) {
3030 fprintf(stderr, "Warning: tried to write to write-protected file\n");
3031 return -1;
3036 i = mapping->end;
3037 } else
3038 i++;
3042 * Use qcow backend. Commit later.
3044 DLOG(fprintf(stderr, "Write to qcow backend: %d + %d\n", (int)sector_num, nb_sectors));
3045 ret = bdrv_write(s->qcow, sector_num, buf, nb_sectors);
3046 if (ret < 0) {
3047 fprintf(stderr, "Error writing to qcow backend\n");
3048 return ret;
3051 for (i = sector2cluster(s, sector_num);
3052 i <= sector2cluster(s, sector_num + nb_sectors - 1); i++)
3053 if (i >= 0)
3054 s->used_clusters[i] |= USED_ALLOCATED;
3056 DLOG(checkpoint());
3057 /* TODO: add timeout */
3058 try_commit(s);
3060 DLOG(checkpoint());
3061 return 0;
3064 static int coroutine_fn
3065 vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3066 QEMUIOVector *qiov, int flags)
3068 int ret;
3069 BDRVVVFATState *s = bs->opaque;
3070 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
3071 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3072 void *buf;
3074 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3075 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3077 buf = g_try_malloc(bytes);
3078 if (bytes && buf == NULL) {
3079 return -ENOMEM;
3081 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3083 qemu_co_mutex_lock(&s->lock);
3084 ret = vvfat_write(bs, sector_num, buf, nb_sectors);
3085 qemu_co_mutex_unlock(&s->lock);
3087 g_free(buf);
3089 return ret;
3092 static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,
3093 int64_t sector_num, int nb_sectors, int *n, BlockDriverState **file)
3095 *n = bs->total_sectors - sector_num;
3096 if (*n > nb_sectors) {
3097 *n = nb_sectors;
3098 } else if (*n < 0) {
3099 return 0;
3101 return BDRV_BLOCK_DATA;
3104 static int coroutine_fn
3105 write_target_commit(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3106 QEMUIOVector *qiov, int flags)
3108 int ret;
3110 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
3111 qemu_co_mutex_lock(&s->lock);
3112 ret = try_commit(s);
3113 qemu_co_mutex_unlock(&s->lock);
3115 return ret;
3118 static void write_target_close(BlockDriverState *bs) {
3119 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
3120 bdrv_unref_child(s->bs, s->qcow);
3121 g_free(s->qcow_filename);
3124 static BlockDriver vvfat_write_target = {
3125 .format_name = "vvfat_write_target",
3126 .instance_size = sizeof(void*),
3127 .bdrv_co_pwritev = write_target_commit,
3128 .bdrv_close = write_target_close,
3131 static void vvfat_qcow_options(int *child_flags, QDict *child_options,
3132 int parent_flags, QDict *parent_options)
3134 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "off");
3135 *child_flags = BDRV_O_NO_FLUSH;
3138 static const BdrvChildRole child_vvfat_qcow = {
3139 .inherit_options = vvfat_qcow_options,
3142 static int enable_write_target(BlockDriverState *bs, Error **errp)
3144 BDRVVVFATState *s = bs->opaque;
3145 BlockDriver *bdrv_qcow = NULL;
3146 BlockDriverState *backing;
3147 QemuOpts *opts = NULL;
3148 int ret;
3149 int size = sector2cluster(s, s->sector_count);
3150 QDict *options;
3152 s->used_clusters = calloc(size, 1);
3154 array_init(&(s->commits), sizeof(commit_t));
3156 s->qcow_filename = g_malloc(PATH_MAX);
3157 ret = get_tmp_filename(s->qcow_filename, PATH_MAX);
3158 if (ret < 0) {
3159 error_setg_errno(errp, -ret, "can't create temporary file");
3160 goto err;
3163 bdrv_qcow = bdrv_find_format("qcow");
3164 if (!bdrv_qcow) {
3165 error_setg(errp, "Failed to locate qcow driver");
3166 ret = -ENOENT;
3167 goto err;
3170 opts = qemu_opts_create(bdrv_qcow->create_opts, NULL, 0, &error_abort);
3171 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s->sector_count * 512,
3172 &error_abort);
3173 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, "fat:", &error_abort);
3175 ret = bdrv_create(bdrv_qcow, s->qcow_filename, opts, errp);
3176 qemu_opts_del(opts);
3177 if (ret < 0) {
3178 goto err;
3181 options = qdict_new();
3182 qdict_put_str(options, "write-target.driver", "qcow");
3183 s->qcow = bdrv_open_child(s->qcow_filename, options, "write-target", bs,
3184 &child_vvfat_qcow, false, errp);
3185 QDECREF(options);
3186 if (!s->qcow) {
3187 ret = -EINVAL;
3188 goto err;
3191 #ifndef _WIN32
3192 unlink(s->qcow_filename);
3193 #endif
3195 backing = bdrv_new_open_driver(&vvfat_write_target, NULL, BDRV_O_ALLOW_RDWR,
3196 &error_abort);
3197 *(void**) backing->opaque = s;
3199 bdrv_set_backing_hd(s->bs, backing, &error_abort);
3200 bdrv_unref(backing);
3202 return 0;
3204 err:
3205 g_free(s->qcow_filename);
3206 s->qcow_filename = NULL;
3207 return ret;
3210 static void vvfat_child_perm(BlockDriverState *bs, BdrvChild *c,
3211 const BdrvChildRole *role,
3212 uint64_t perm, uint64_t shared,
3213 uint64_t *nperm, uint64_t *nshared)
3215 BDRVVVFATState *s = bs->opaque;
3217 assert(c == s->qcow || role == &child_backing);
3219 if (c == s->qcow) {
3220 /* This is a private node, nobody should try to attach to it */
3221 *nperm = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
3222 *nshared = BLK_PERM_WRITE_UNCHANGED;
3223 } else {
3224 /* The backing file is there so 'commit' can use it. vvfat doesn't
3225 * access it in any way. */
3226 *nperm = 0;
3227 *nshared = BLK_PERM_ALL;
3231 static void vvfat_close(BlockDriverState *bs)
3233 BDRVVVFATState *s = bs->opaque;
3235 vvfat_close_current_file(s);
3236 array_free(&(s->fat));
3237 array_free(&(s->directory));
3238 array_free(&(s->mapping));
3239 g_free(s->cluster_buffer);
3241 if (s->qcow) {
3242 migrate_del_blocker(s->migration_blocker);
3243 error_free(s->migration_blocker);
3247 static BlockDriver bdrv_vvfat = {
3248 .format_name = "vvfat",
3249 .protocol_name = "fat",
3250 .instance_size = sizeof(BDRVVVFATState),
3252 .bdrv_parse_filename = vvfat_parse_filename,
3253 .bdrv_file_open = vvfat_open,
3254 .bdrv_refresh_limits = vvfat_refresh_limits,
3255 .bdrv_close = vvfat_close,
3256 .bdrv_child_perm = vvfat_child_perm,
3258 .bdrv_co_preadv = vvfat_co_preadv,
3259 .bdrv_co_pwritev = vvfat_co_pwritev,
3260 .bdrv_co_get_block_status = vvfat_co_get_block_status,
3263 static void bdrv_vvfat_init(void)
3265 bdrv_register(&bdrv_vvfat);
3268 block_init(bdrv_vvfat_init);
3270 #ifdef DEBUG
3271 static void checkpoint(void) {
3272 assert(((mapping_t*)array_get(&(vvv->mapping), 0))->end == 2);
3273 check1(vvv);
3274 check2(vvv);
3275 assert(!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode & MODE_DIRECTORY));
3276 #if 0
3277 if (((direntry_t*)vvv->directory.pointer)[1].attributes != 0xf)
3278 fprintf(stderr, "Nonono!\n");
3279 mapping_t* mapping;
3280 direntry_t* direntry;
3281 assert(vvv->mapping.size >= vvv->mapping.item_size * vvv->mapping.next);
3282 assert(vvv->directory.size >= vvv->directory.item_size * vvv->directory.next);
3283 if (vvv->mapping.next<47)
3284 return;
3285 assert((mapping = array_get(&(vvv->mapping), 47)));
3286 assert(mapping->dir_index < vvv->directory.next);
3287 direntry = array_get(&(vvv->directory), mapping->dir_index);
3288 assert(!memcmp(direntry->name, "USB H ", 11) || direntry->name[0]==0);
3289 #endif
3291 #endif