]> git.ipfire.org Git - thirdparty/qemu.git/blame - block/vvfat.c
vvfat: initialize memory after allocating it
[thirdparty/qemu.git] / block / vvfat.c
CommitLineData
7ad9be64 1/* vim:set shiftwidth=4 ts=4: */
de167e41
FB
2/*
3 * QEMU Block driver for virtual VFAT (shadows a local directory)
5fafdf24 4 *
a046433a 5 * Copyright (c) 2004,2005 Johannes E. Schindelin
5fafdf24 6 *
de167e41
FB
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:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
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.
24 */
80c71a24 25#include "qemu/osdep.h"
de167e41 26#include <dirent.h>
da34e65c 27#include "qapi/error.h"
737e150e 28#include "block/block_int.h"
1de7afc9 29#include "qemu/module.h"
58369e22 30#include "qemu/bswap.h"
795c40b8 31#include "migration/blocker.h"
7ad9be64 32#include "qapi/qmp/qbool.h"
d49b6836 33#include "qapi/qmp/qstring.h"
f348b6d1 34#include "qemu/cutils.h"
de167e41 35
a046433a
FB
36#ifndef S_IWGRP
37#define S_IWGRP 0
38#endif
39#ifndef S_IWOTH
40#define S_IWOTH 0
41#endif
42
43/* TODO: add ":bootsector=blabla.img:" */
44/* LATER TODO: add automatic boot sector generation from
45 BOOTEASY.ASM and Ranish Partition Manager
5fafdf24 46 Note that DOS assumes the system files to be the first files in the
a046433a
FB
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 */
50
51/* #define DEBUG */
52
53#ifdef DEBUG
54
55#define DLOG(a) a
56
3f47aa8c 57static void checkpoint(void);
de167e41 58
a046433a
FB
59#ifdef __MINGW32__
60void nonono(const char* file, int line, const char* msg) {
61 fprintf(stderr, "Nonono! %s:%d %s\n", file, line, msg);
62 exit(-5);
63}
64#undef assert
6bcb76c3 65#define assert(a) do {if (!(a)) nonono(__FILE__, __LINE__, #a);}while(0)
a046433a
FB
66#endif
67
68#else
69
70#define DLOG(a)
71
72#endif
de167e41 73
63d261cb
HP
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
77 */
78#define BOOTSECTOR_OEM_NAME "MSWIN4.1"
79
8c4517fd
HP
80#define DIR_DELETED 0xe5
81#define DIR_KANJI DIR_DELETED
82#define DIR_KANJI_FAKE 0x05
83#define DIR_FREE 0x00
84
de167e41 85/* dynamic array functions */
c227f099 86typedef struct array_t {
de167e41
FB
87 char* pointer;
88 unsigned int size,next,item_size;
c227f099 89} array_t;
de167e41 90
c227f099 91static inline void array_init(array_t* array,unsigned int item_size)
de167e41 92{
511d2b14 93 array->pointer = NULL;
de167e41
FB
94 array->size=0;
95 array->next=0;
96 array->item_size=item_size;
97}
98
c227f099 99static inline void array_free(array_t* array)
de167e41 100{
ce137829 101 g_free(array->pointer);
de167e41
FB
102 array->size=array->next=0;
103}
104
a046433a 105/* does not automatically grow */
c227f099 106static inline void* array_get(array_t* array,unsigned int index) {
a046433a
FB
107 assert(index < array->next);
108 return array->pointer + index * array->item_size;
109}
110
c227f099 111static inline int array_ensure_allocated(array_t* array, int index)
a046433a
FB
112{
113 if((index + 1) * array->item_size > array->size) {
d6a7e54e
HP
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;
f80256b7 118 memset(array->pointer + array->size, 0, new_size - array->size);
d6a7e54e
HP
119 array->size = new_size;
120 array->next = index + 1;
de167e41 121 }
a046433a
FB
122
123 return 0;
de167e41
FB
124}
125
c227f099 126static inline void* array_get_next(array_t* array) {
a046433a 127 unsigned int next = array->next;
a046433a
FB
128
129 if (array_ensure_allocated(array, next) < 0)
d6a7e54e 130 return NULL;
a046433a
FB
131
132 array->next = next + 1;
9be38598 133 return array_get(array, next);
de167e41
FB
134}
135
c227f099 136static inline void* array_insert(array_t* array,unsigned int index,unsigned int count) {
de167e41 137 if((array->next+count)*array->item_size>array->size) {
d6a7e54e
HP
138 int increment=count*array->item_size;
139 array->pointer=g_realloc(array->pointer,array->size+increment);
140 if(!array->pointer)
511d2b14 141 return NULL;
d6a7e54e 142 array->size+=increment;
de167e41
FB
143 }
144 memmove(array->pointer+(index+count)*array->item_size,
d6a7e54e
HP
145 array->pointer+index*array->item_size,
146 (array->next-index)*array->item_size);
de167e41
FB
147 array->next+=count;
148 return array->pointer+index*array->item_size;
149}
150
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. */
c227f099 153static inline int array_roll(array_t* array,int index_to,int index_from,int count)
de167e41
FB
154{
155 char* buf;
156 char* from;
157 char* to;
158 int is;
159
160 if(!array ||
d6a7e54e
HP
161 index_to<0 || index_to>=array->next ||
162 index_from<0 || index_from>=array->next)
163 return -1;
3b46e624 164
de167e41 165 if(index_to==index_from)
d6a7e54e 166 return 0;
de167e41
FB
167
168 is=array->item_size;
169 from=array->pointer+index_from*is;
170 to=array->pointer+index_to*is;
7267c094 171 buf=g_malloc(is*count);
de167e41
FB
172 memcpy(buf,from,is*count);
173
174 if(index_to<index_from)
d6a7e54e 175 memmove(to+is*count,to,from-to);
de167e41 176 else
d6a7e54e 177 memmove(from,from+is*count,to-from);
3b46e624 178
de167e41
FB
179 memcpy(to,buf,is*count);
180
ce137829 181 g_free(buf);
de167e41
FB
182
183 return 0;
184}
185
c227f099 186static inline int array_remove_slice(array_t* array,int index, int count)
de167e41 187{
a046433a
FB
188 assert(index >=0);
189 assert(count > 0);
190 assert(index + count <= array->next);
191 if(array_roll(array,array->next-1,index,count))
d6a7e54e 192 return -1;
a046433a 193 array->next -= count;
de167e41
FB
194 return 0;
195}
196
c227f099 197static int array_remove(array_t* array,int index)
a046433a
FB
198{
199 return array_remove_slice(array, index, 1);
200}
201
202/* return the index for a given member */
c227f099 203static int array_index(array_t* array, void* pointer)
a046433a
FB
204{
205 size_t offset = (char*)pointer - array->pointer;
a046433a
FB
206 assert((offset % array->item_size) == 0);
207 assert(offset/array->item_size < array->next);
208 return offset/array->item_size;
209}
210
de167e41 211/* These structures are used to fake a disk and the VFAT filesystem.
541dc0d4 212 * For this reason we need to use QEMU_PACKED. */
de167e41 213
c227f099 214typedef struct bootsector_t {
de167e41
FB
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;
a046433a 222 uint16_t total_sectors16;
de167e41
FB
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 {
d6a7e54e 231 uint8_t drive_number;
92e28d82 232 uint8_t reserved1;
d6a7e54e
HP
233 uint8_t signature;
234 uint32_t id;
235 uint8_t volume_label[11];
92e28d82
HP
236 uint8_t fat_type[8];
237 uint8_t ignored[0x1c0];
d6a7e54e
HP
238 } QEMU_PACKED fat16;
239 struct {
240 uint32_t sectors_per_fat;
241 uint16_t flags;
242 uint8_t major,minor;
92e28d82 243 uint32_t first_cluster_of_root_dir;
d6a7e54e
HP
244 uint16_t info_sector;
245 uint16_t backup_boot_sector;
92e28d82
HP
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];
d6a7e54e 254 } QEMU_PACKED fat32;
de167e41 255 } u;
de167e41 256 uint8_t magic[2];
541dc0d4 257} QEMU_PACKED bootsector_t;
de167e41 258
b570094d
TS
259typedef struct {
260 uint8_t head;
261 uint8_t sector;
262 uint8_t cylinder;
c227f099 263} mbr_chs_t;
b570094d 264
c227f099 265typedef struct partition_t {
de167e41 266 uint8_t attributes; /* 0x80 = bootable */
c227f099 267 mbr_chs_t start_CHS;
b570094d 268 uint8_t fs_type; /* 0x1 = FAT12, 0x6 = FAT16, 0xe = FAT16_LBA, 0xb = FAT32, 0xc = FAT32_LBA */
c227f099 269 mbr_chs_t end_CHS;
de167e41 270 uint32_t start_sector_long;
b570094d 271 uint32_t length_sector_long;
541dc0d4 272} QEMU_PACKED partition_t;
de167e41 273
c227f099 274typedef struct mbr_t {
b570094d
TS
275 uint8_t ignored[0x1b8];
276 uint32_t nt_id;
277 uint8_t ignored2[2];
c227f099 278 partition_t partition[4];
de167e41 279 uint8_t magic[2];
541dc0d4 280} QEMU_PACKED mbr_t;
de167e41 281
c227f099 282typedef struct direntry_t {
f671d173 283 uint8_t name[8 + 3];
de167e41
FB
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;
541dc0d4 294} QEMU_PACKED direntry_t;
de167e41
FB
295
296/* this structure are used to transparently access the files */
297
c227f099 298typedef struct mapping_t {
a046433a
FB
299 /* begin is the first cluster, end is the last+1 */
300 uint32_t begin,end;
de167e41
FB
301 /* as s->directory is growable, no pointer may be used here */
302 unsigned int dir_index;
a046433a
FB
303 /* the clusters of a file may be in any order; this points to the first */
304 int first_mapping_index;
305 union {
d6a7e54e
HP
306 /* offset is
307 * - the offset in the file (in clusters) for a file, or
ad05b318 308 * - the next cluster of the directory for a directory
d6a7e54e
HP
309 */
310 struct {
311 uint32_t offset;
312 } file;
313 struct {
314 int parent_mapping_index;
315 int first_dir_index;
316 } dir;
a046433a
FB
317 } info;
318 /* path contains the full path, i.e. it always starts with s->path */
319 char* path;
320
ad05b318
HP
321 enum {
322 MODE_UNDEFINED = 0,
323 MODE_NORMAL = 1,
324 MODE_MODIFIED = 2,
325 MODE_DIRECTORY = 4,
326 MODE_DELETED = 8,
327 } mode;
a046433a 328 int read_only;
c227f099 329} mapping_t;
de167e41 330
a046433a 331#ifdef DEBUG
c227f099
AL
332static void print_direntry(const struct direntry_t*);
333static void print_mapping(const struct mapping_t* mapping);
a046433a 334#endif
de167e41
FB
335
336/* here begins the real VVFAT driver */
337
338typedef struct BDRVVVFATState {
848c66e8 339 CoMutex lock;
a046433a 340 BlockDriverState* bs; /* pointer to parent */
de167e41 341 unsigned char first_sectors[0x40*0x200];
3b46e624 342
de167e41 343 int fat_type; /* 16 or 32 */
c227f099 344 array_t fat,directory,mapping;
d5941dda 345 char volume_label[11];
3b46e624 346
4dc705dc
HP
347 uint32_t offset_to_bootsector; /* 0 for floppy, 0x3f for disk */
348
de167e41
FB
349 unsigned int cluster_size;
350 unsigned int sectors_per_cluster;
351 unsigned int sectors_per_fat;
a046433a 352 uint32_t last_cluster_of_root_directory;
6817efea
HP
353 /* how many entries are available in root directory (0 for FAT32) */
354 uint16_t root_entries;
de167e41
FB
355 uint32_t sector_count; /* total number of sectors of the partition */
356 uint32_t cluster_count; /* total number of clusters of this partition */
de167e41 357 uint32_t max_fat_value;
4dc705dc
HP
358 uint32_t offset_to_fat;
359 uint32_t offset_to_root_dir;
3b46e624 360
de167e41 361 int current_fd;
c227f099 362 mapping_t* current_mapping;
a046433a
FB
363 unsigned char* cluster; /* points to current cluster */
364 unsigned char* cluster_buffer; /* points to a buffer to hold temp data */
de167e41
FB
365 unsigned int current_cluster;
366
367 /* write support */
a046433a 368 char* qcow_filename;
eecc7747 369 BdrvChild* qcow;
a046433a
FB
370 void* fat2;
371 char* used_clusters;
c227f099 372 array_t commits;
a046433a
FB
373 const char* path;
374 int downcase_short_names;
3397f0cb
KW
375
376 Error *migration_blocker;
de167e41
FB
377} BDRVVVFATState;
378
b570094d
TS
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.
382 */
4480e0f9
MA
383static int sector2CHS(mbr_chs_t *chs, int spos, int cyls, int heads, int secs)
384{
b570094d 385 int head,sector;
4480e0f9
MA
386 sector = spos % secs; spos /= secs;
387 head = spos % heads; spos /= heads;
388 if (spos >= cyls) {
b570094d
TS
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;
396 }
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;
401}
de167e41 402
4480e0f9 403static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)
de167e41
FB
404{
405 /* TODO: if the files mbr.img and bootsect.img exist, use them */
c227f099
AL
406 mbr_t* real_mbr=(mbr_t*)s->first_sectors;
407 partition_t* partition = &(real_mbr->partition[0]);
b570094d 408 int lba;
de167e41
FB
409
410 memset(s->first_sectors,0,512);
3b46e624 411
b570094d
TS
412 /* Win NT Disk Signature */
413 real_mbr->nt_id= cpu_to_le32(0xbe1afdfa);
414
de167e41 415 partition->attributes=0x80; /* bootable */
b570094d
TS
416
417 /* LBA is used when partition is outside the CHS geometry */
4dc705dc 418 lba = sector2CHS(&partition->start_CHS, s->offset_to_bootsector,
4480e0f9
MA
419 cyls, heads, secs);
420 lba |= sector2CHS(&partition->end_CHS, s->bs->total_sectors - 1,
421 cyls, heads, secs);
b570094d
TS
422
423 /*LBA partitions are identified only by start/length_sector_long not by CHS*/
4dc705dc 424 partition->start_sector_long = cpu_to_le32(s->offset_to_bootsector);
f91cbefe 425 partition->length_sector_long = cpu_to_le32(s->bs->total_sectors
4dc705dc 426 - s->offset_to_bootsector);
b570094d 427
a046433a 428 /* FAT12/FAT16/FAT32 */
b570094d
TS
429 /* DOS uses different types when partition is LBA,
430 probably to prevent older versions from using CHS on them */
5f5b29df
HP
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);
de167e41
FB
434
435 real_mbr->magic[0]=0x55; real_mbr->magic[1]=0xaa;
436}
437
a046433a
FB
438/* direntry functions */
439
09ec4119 440static direntry_t *create_long_filename(BDRVVVFATState *s, const char *filename)
de167e41 441{
09ec4119
HP
442 int number_of_entries, i;
443 glong length;
444 direntry_t *entry;
445
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;
de167e41 450 }
de167e41 451
09ec4119 452 number_of_entries = (length * 2 + 25) / 26;
de167e41
FB
453
454 for(i=0;i<number_of_entries;i++) {
d6a7e54e
HP
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);
de167e41 460 }
1e080d5d 461 for(i=0;i<26*number_of_entries;i++) {
d6a7e54e
HP
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));
09ec4119
HP
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;
473 }
de167e41 474 }
09ec4119 475 g_free(longname);
de167e41
FB
476 return array_get(&(s->directory),s->directory.next-number_of_entries);
477}
478
c227f099 479static char is_free(const direntry_t* direntry)
a046433a 480{
8c4517fd 481 return direntry->name[0] == DIR_DELETED || direntry->name[0] == DIR_FREE;
a046433a
FB
482}
483
c227f099 484static char is_volume_label(const direntry_t* direntry)
a046433a
FB
485{
486 return direntry->attributes == 0x28;
487}
488
c227f099 489static char is_long_name(const direntry_t* direntry)
a046433a
FB
490{
491 return direntry->attributes == 0xf;
492}
493
c227f099 494static char is_short_name(const direntry_t* direntry)
a046433a
FB
495{
496 return !is_volume_label(direntry) && !is_long_name(direntry)
d6a7e54e 497 && !is_free(direntry);
a046433a
FB
498}
499
c227f099 500static char is_directory(const direntry_t* direntry)
a046433a 501{
8c4517fd 502 return direntry->attributes & 0x10 && direntry->name[0] != DIR_DELETED;
a046433a
FB
503}
504
c227f099 505static inline char is_dot(const direntry_t* direntry)
a046433a
FB
506{
507 return is_short_name(direntry) && direntry->name[0] == '.';
508}
509
c227f099 510static char is_file(const direntry_t* direntry)
a046433a
FB
511{
512 return is_short_name(direntry) && !is_directory(direntry);
513}
514
c227f099 515static inline uint32_t begin_of_direntry(const direntry_t* direntry)
a046433a
FB
516{
517 return le16_to_cpu(direntry->begin)|(le16_to_cpu(direntry->begin_hi)<<16);
518}
519
c227f099 520static inline uint32_t filesize_of_direntry(const direntry_t* direntry)
a046433a
FB
521{
522 return le32_to_cpu(direntry->size);
523}
524
c227f099 525static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin)
a046433a
FB
526{
527 direntry->begin = cpu_to_le16(begin & 0xffff);
528 direntry->begin_hi = cpu_to_le16((begin >> 16) & 0xffff);
529}
530
0c36111f
HP
531static uint8_t to_valid_short_char(gunichar c)
532{
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;
540 }
541}
542
543static direntry_t *create_short_filename(BDRVVVFATState *s,
339cebcc
HP
544 const char *filename,
545 unsigned int directory_start)
0c36111f 546{
339cebcc 547 int i, j = 0;
0c36111f
HP
548 direntry_t *entry = array_get_next(&(s->directory));
549 const gchar *p, *last_dot = NULL;
550 gunichar c;
551 bool lossy_conversion = false;
339cebcc 552 char tail[11];
0c36111f
HP
553
554 if (!entry) {
555 return NULL;
556 }
557 memset(entry->name, 0x20, sizeof(entry->name));
558
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;
571 }
572 last_dot = p;
573 }
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;
581 }
582 }
583 }
584
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;
599 }
600 }
601 }
602 }
339cebcc 603
8c4517fd
HP
604 if (entry->name[0] == DIR_KANJI) {
605 entry->name[0] = DIR_KANJI_FAKE;
78f002c9
HP
606 }
607
339cebcc
HP
608 /* numeric-tail generation */
609 for (j = 0; j < 8; j++) {
610 if (entry->name[j] == ' ') {
611 break;
612 }
613 }
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);
619 }
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 */
625 }
626 }
627 if (entry1 == entry) {
628 /* no dupe found */
629 return entry;
630 }
631 }
632 return NULL;
0c36111f
HP
633}
634
de167e41
FB
635/* fat functions */
636
c227f099 637static inline uint8_t fat_chksum(const direntry_t* entry)
de167e41
FB
638{
639 uint8_t chksum=0;
640 int i;
641
f671d173
SW
642 for (i = 0; i < ARRAY_SIZE(entry->name); i++) {
643 chksum = (((chksum & 0xfe) >> 1) |
644 ((chksum & 0x01) ? 0x80 : 0)) + entry->name[i];
5606c220 645 }
3b46e624 646
de167e41
FB
647 return chksum;
648}
649
650/* if return_time==0, this returns the fat_date, else the fat_time */
651static uint16_t fat_datetime(time_t time,int return_time) {
652 struct tm* t;
de167e41 653 struct tm t1;
6ab00cee 654 t = &t1;
de167e41 655 localtime_r(&time,t);
de167e41 656 if(return_time)
d6a7e54e 657 return cpu_to_le16((t->tm_sec/2)|(t->tm_min<<5)|(t->tm_hour<<11));
de167e41
FB
658 return cpu_to_le16((t->tm_mday)|((t->tm_mon+1)<<5)|((t->tm_year-80)<<9));
659}
660
661static inline void fat_set(BDRVVVFATState* s,unsigned int cluster,uint32_t value)
662{
a046433a 663 if(s->fat_type==32) {
d6a7e54e
HP
664 uint32_t* entry=array_get(&(s->fat),cluster);
665 *entry=cpu_to_le32(value);
de167e41 666 } else if(s->fat_type==16) {
d6a7e54e
HP
667 uint16_t* entry=array_get(&(s->fat),cluster);
668 *entry=cpu_to_le16(value&0xffff);
de167e41 669 } else {
d6a7e54e
HP
670 int offset = (cluster*3/2);
671 unsigned char* p = array_get(&(s->fat), offset);
a046433a 672 switch (cluster&1) {
d6a7e54e
HP
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;
681 }
de167e41
FB
682 }
683}
684
685static inline uint32_t fat_get(BDRVVVFATState* s,unsigned int cluster)
686{
a046433a 687 if(s->fat_type==32) {
d6a7e54e
HP
688 uint32_t* entry=array_get(&(s->fat),cluster);
689 return le32_to_cpu(*entry);
de167e41 690 } else if(s->fat_type==16) {
d6a7e54e
HP
691 uint16_t* entry=array_get(&(s->fat),cluster);
692 return le16_to_cpu(*entry);
de167e41 693 } else {
d6a7e54e
HP
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;
de167e41
FB
696 }
697}
698
699static inline int fat_eof(BDRVVVFATState* s,uint32_t fat_entry)
700{
701 if(fat_entry>s->max_fat_value-8)
d6a7e54e 702 return -1;
de167e41
FB
703 return 0;
704}
705
706static inline void init_fat(BDRVVVFATState* s)
707{
a046433a 708 if (s->fat_type == 12) {
d6a7e54e
HP
709 array_init(&(s->fat),1);
710 array_ensure_allocated(&(s->fat),
711 s->sectors_per_fat * 0x200 * 3 / 2 - 1);
a046433a 712 } else {
d6a7e54e
HP
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);
a046433a 716 }
de167e41 717 memset(s->fat.pointer,0,s->fat.size);
3b46e624 718
de167e41 719 switch(s->fat_type) {
d6a7e54e
HP
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... */
de167e41
FB
724 }
725
726}
727
c227f099 728static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,
d6a7e54e 729 unsigned int directory_start, const char* filename, int is_dot)
de167e41 730{
0c36111f 731 int long_index = s->directory.next;
c227f099
AL
732 direntry_t* entry = NULL;
733 direntry_t* entry_long = NULL;
de167e41
FB
734
735 if(is_dot) {
d6a7e54e 736 entry=array_get_next(&(s->directory));
f671d173 737 memset(entry->name, 0x20, sizeof(entry->name));
d6a7e54e
HP
738 memcpy(entry->name,filename,strlen(filename));
739 return entry;
de167e41 740 }
3b46e624 741
de167e41 742 entry_long=create_long_filename(s,filename);
339cebcc 743 entry = create_short_filename(s, filename, directory_start);
de167e41
FB
744
745 /* calculate checksum; propagate to long name */
746 if(entry_long) {
747 uint8_t chksum=fat_chksum(entry);
748
d6a7e54e
HP
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++;
754 }
de167e41
FB
755 }
756
757 return entry;
758}
759
a046433a
FB
760/*
761 * Read a directory. (the index of the corresponding mapping must be passed).
762 */
763static int read_directory(BDRVVVFATState* s, int mapping_index)
de167e41 764{
c227f099
AL
765 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
766 direntry_t* direntry;
a046433a
FB
767 const char* dirname = mapping->path;
768 int first_cluster = mapping->begin;
769 int parent_index = mapping->info.dir.parent_mapping_index;
c227f099 770 mapping_t* parent_mapping = (mapping_t*)
511d2b14 771 (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);
a046433a 772 int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;
de167e41
FB
773
774 DIR* dir=opendir(dirname);
775 struct dirent* entry;
de167e41
FB
776 int i;
777
a046433a
FB
778 assert(mapping->mode & MODE_DIRECTORY);
779
780 if(!dir) {
d6a7e54e
HP
781 mapping->end = mapping->begin;
782 return -1;
a046433a 783 }
3b46e624 784
a046433a 785 i = mapping->info.dir.first_dir_index =
d6a7e54e 786 first_cluster == 0 ? 0 : s->directory.next;
a046433a 787
f82d92bb
HP
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);
792 }
793
5fafdf24 794 /* actually read the directory, and allocate the mappings */
de167e41 795 while((entry=readdir(dir))) {
d6a7e54e 796 unsigned int length=strlen(dirname)+2+strlen(entry->d_name);
de167e41 797 char* buffer;
d6a7e54e 798 direntry_t* direntry;
a046433a 799 struct stat st;
d6a7e54e
HP
800 int is_dot=!strcmp(entry->d_name,".");
801 int is_dotdot=!strcmp(entry->d_name,"..");
de167e41 802
6817efea
HP
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;
807 }
808
d6a7e54e
HP
809 if(first_cluster == 0 && (is_dotdot || is_dot))
810 continue;
5fafdf24 811
d6a7e54e
HP
812 buffer = g_malloc(length);
813 snprintf(buffer,length,"%s/%s",dirname,entry->d_name);
de167e41 814
d6a7e54e 815 if(stat(buffer,&st)<0) {
ce137829 816 g_free(buffer);
de167e41 817 continue;
d6a7e54e
HP
818 }
819
820 /* create directory entry for this file */
f82d92bb
HP
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);
825 }
d6a7e54e
HP
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 */
a046433a 840 if (st.st_size > 0x7fffffff) {
d6a7e54e 841 fprintf(stderr, "File %s is larger than 2GB\n", buffer);
ce137829 842 g_free(buffer);
08089edc 843 closedir(dir);
d6a7e54e 844 return -2;
a046433a 845 }
d6a7e54e
HP
846 direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);
847
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;
853 /*
854 * we get the direntry of the most recent direntry, which
855 * contains the short name and all the relevant information.
856 */
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;
866 }
867 s->current_mapping->path=buffer;
868 s->current_mapping->read_only =
869 (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0;
b122c3b6
MA
870 } else {
871 g_free(buffer);
872 }
de167e41
FB
873 }
874 closedir(dir);
875
876 /* fill with zeroes up to the end of the cluster */
877 while(s->directory.next%(0x10*s->sectors_per_cluster)) {
d6a7e54e
HP
878 direntry_t* direntry=array_get_next(&(s->directory));
879 memset(direntry,0,sizeof(direntry_t));
de167e41
FB
880 }
881
6817efea
HP
882 if (s->fat_type != 32 &&
883 mapping_index == 0 &&
884 s->directory.next < s->root_entries) {
d6a7e54e
HP
885 /* root directory */
886 int cur = s->directory.next;
6817efea
HP
887 array_ensure_allocated(&(s->directory), s->root_entries - 1);
888 s->directory.next = s->root_entries;
d6a7e54e 889 memset(array_get(&(s->directory), cur), 0,
6817efea 890 (s->root_entries - cur) * sizeof(direntry_t));
de167e41 891 }
5fafdf24 892
5f5b29df 893 /* re-get the mapping, since s->mapping was possibly realloc()ed */
d4df3dbc 894 mapping = array_get(&(s->mapping), mapping_index);
a046433a 895 first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)
d6a7e54e 896 * 0x20 / s->cluster_size;
a046433a
FB
897 mapping->end = first_cluster;
898
d4df3dbc 899 direntry = array_get(&(s->directory), mapping->dir_index);
a046433a 900 set_begin_of_direntry(direntry, mapping->begin);
3b46e624 901
a046433a
FB
902 return 0;
903}
de167e41 904
a046433a
FB
905static inline uint32_t sector2cluster(BDRVVVFATState* s,off_t sector_num)
906{
4dc705dc 907 return (sector_num - s->offset_to_root_dir) / s->sectors_per_cluster;
a046433a 908}
de167e41 909
a046433a
FB
910static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
911{
4dc705dc 912 return s->offset_to_root_dir + s->sectors_per_cluster * cluster_num;
a046433a 913}
de167e41 914
a046433a 915static int init_directories(BDRVVVFATState* s,
d11c8917
MA
916 const char *dirname, int heads, int secs,
917 Error **errp)
de167e41 918{
c227f099
AL
919 bootsector_t* bootsector;
920 mapping_t* mapping;
de167e41
FB
921 unsigned int i;
922 unsigned int cluster;
923
924 memset(&(s->first_sectors[0]),0,0x40*0x200);
925
de167e41 926 s->cluster_size=s->sectors_per_cluster*0x200;
7267c094 927 s->cluster_buffer=g_malloc(s->cluster_size);
a046433a
FB
928
929 /*
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.
935 */
936 i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;
937 s->sectors_per_fat=(s->sector_count+i)/i; /* round up */
3b46e624 938
4dc705dc
HP
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;
941
c227f099
AL
942 array_init(&(s->mapping),sizeof(mapping_t));
943 array_init(&(s->directory),sizeof(direntry_t));
de167e41
FB
944
945 /* add volume label */
946 {
d6a7e54e
HP
947 direntry_t* entry=array_get_next(&(s->directory));
948 entry->attributes=0x28; /* archive | volume label */
d5941dda 949 memcpy(entry->name, s->volume_label, sizeof(entry->name));
de167e41
FB
950 }
951
de167e41
FB
952 /* Now build FAT, and write back information into directory */
953 init_fat(s);
954
6817efea
HP
955 /* TODO: if there are more entries, bootsector has to be adjusted! */
956 s->root_entries = 0x02 * 0x10 * s->sectors_per_cluster;
a046433a
FB
957 s->cluster_count=sector2cluster(s, s->sector_count);
958
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;
7267c094 964 mapping->path = g_strdup(dirname);
a046433a
FB
965 i = strlen(mapping->path);
966 if (i > 0 && mapping->path[i - 1] == '/')
d6a7e54e 967 mapping->path[i - 1] = '\0';
a046433a
FB
968 mapping->mode = MODE_DIRECTORY;
969 mapping->read_only = 0;
970 s->path = mapping->path;
971
972 for (i = 0, cluster = 0; i < s->mapping.next; i++) {
d6a7e54e
HP
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);
a046433a
FB
978
979 if (mapping->mode & MODE_DIRECTORY) {
d6a7e54e
HP
980 mapping->begin = cluster;
981 if(read_directory(s, i)) {
d11c8917
MA
982 error_setg(errp, "Could not read directory %s",
983 mapping->path);
d6a7e54e
HP
984 return -1;
985 }
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);
994
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;
1000 }
1001 }
1002
1003 assert(mapping->begin < mapping->end);
1004
1005 /* next free cluster */
1006 cluster = mapping->end;
1007
1008 if(cluster > s->cluster_count) {
d11c8917
MA
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;
d6a7e54e 1013 }
8ce0f869 1014
d6a7e54e
HP
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);
1021 }
de167e41
FB
1022 }
1023
a046433a 1024 mapping = array_get(&(s->mapping), 0);
a046433a
FB
1025 s->last_cluster_of_root_directory = mapping->end;
1026
1027 /* the FAT signature */
1028 fat_set(s,0,s->max_fat_value);
1029 fat_set(s,1,s->max_fat_value);
de167e41 1030
a046433a
FB
1031 s->current_mapping = NULL;
1032
4dc705dc
HP
1033 bootsector = (bootsector_t *)(s->first_sectors
1034 + s->offset_to_bootsector * 0x200);
de167e41
FB
1035 bootsector->jump[0]=0xeb;
1036 bootsector->jump[1]=0x3e;
1037 bootsector->jump[2]=0x90;
63d261cb 1038 memcpy(bootsector->name, BOOTSECTOR_OEM_NAME, 8);
de167e41
FB
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 */
6817efea 1043 bootsector->root_entries = cpu_to_le16(s->root_entries);
a046433a 1044 bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
4dc705dc
HP
1045 /* media descriptor: hard disk=0xf8, floppy=0xf0 */
1046 bootsector->media_type = (s->offset_to_bootsector > 0 ? 0xf8 : 0xf0);
a046433a 1047 s->fat.pointer[0] = bootsector->media_type;
de167e41 1048 bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
4480e0f9
MA
1049 bootsector->sectors_per_track = cpu_to_le16(secs);
1050 bootsector->number_of_heads = cpu_to_le16(heads);
4dc705dc 1051 bootsector->hidden_sectors = cpu_to_le32(s->offset_to_bootsector);
a046433a 1052 bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
de167e41 1053
a046433a 1054 /* LATER TODO: if FAT32, this is wrong */
4dc705dc
HP
1055 /* drive_number: fda=0, hda=0x80 */
1056 bootsector->u.fat16.drive_number = s->offset_to_bootsector == 0 ? 0 : 0x80;
de167e41
FB
1057 bootsector->u.fat16.signature=0x29;
1058 bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);
1059
d5941dda
WB
1060 memcpy(bootsector->u.fat16.volume_label, s->volume_label,
1061 sizeof(bootsector->u.fat16.volume_label));
92e28d82
HP
1062 memcpy(bootsector->u.fat16.fat_type,
1063 s->fat_type == 12 ? "FAT12 " : "FAT16 ", 8);
de167e41
FB
1064 bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;
1065
1066 return 0;
1067}
1068
83f64091 1069#ifdef DEBUG
a046433a 1070static BDRVVVFATState *vvv = NULL;
83f64091 1071#endif
a046433a 1072
eecc7747 1073static int enable_write_target(BlockDriverState *bs, Error **errp);
a046433a
FB
1074static int is_consistent(BDRVVVFATState *s);
1075
7ad9be64
KW
1076static QemuOptsList runtime_opts = {
1077 .name = "vvfat",
1078 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1079 .desc = {
1080 {
1081 .name = "dir",
1082 .type = QEMU_OPT_STRING,
1083 .help = "Host directory to map to the vvfat device",
1084 },
1085 {
1086 .name = "fat-type",
1087 .type = QEMU_OPT_NUMBER,
1088 .help = "FAT type (12, 16 or 32)",
1089 },
1090 {
1091 .name = "floppy",
1092 .type = QEMU_OPT_BOOL,
1093 .help = "Create a floppy rather than a hard disk image",
1094 },
d5941dda
WB
1095 {
1096 .name = "label",
1097 .type = QEMU_OPT_STRING,
1098 .help = "Use a volume label other than QEMU VVFAT",
1099 },
7ad9be64
KW
1100 {
1101 .name = "rw",
1102 .type = QEMU_OPT_BOOL,
1103 .help = "Make the image writable",
1104 },
1105 { /* end of list */ }
1106 },
1107};
1108
1109static void vvfat_parse_filename(const char *filename, QDict *options,
1110 Error **errp)
1111{
1112 int fat_type = 0;
1113 bool floppy = false;
1114 bool rw = false;
1115 int i;
1116
1117 if (!strstart(filename, "fat:", NULL)) {
1118 error_setg(errp, "File name string must start with 'fat:'");
1119 return;
1120 }
1121
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;
1129 }
1130
1131 if (strstr(filename, ":floppy:")) {
1132 floppy = true;
1133 }
1134
1135 if (strstr(filename, ":rw:")) {
1136 rw = true;
1137 }
1138
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;
1147 }
1148
1149 /* Fill in the options QDict */
46f5ac20
EB
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);
7ad9be64
KW
1154}
1155
015a1036
HR
1156static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
1157 Error **errp)
de167e41
FB
1158{
1159 BDRVVVFATState *s = bs->opaque;
7ad9be64
KW
1160 int cyls, heads, secs;
1161 bool floppy;
d5941dda 1162 const char *dirname, *label;
7ad9be64
KW
1163 QemuOpts *opts;
1164 Error *local_err = NULL;
1165 int ret;
de167e41 1166
83f64091 1167#ifdef DEBUG
a046433a 1168 vvv = s;
83f64091 1169#endif
a046433a 1170
87ea75d5 1171 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
7ad9be64 1172 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 1173 if (local_err) {
c0f92b52 1174 error_propagate(errp, local_err);
7ad9be64
KW
1175 ret = -EINVAL;
1176 goto fail;
1177 }
1178
1179 dirname = qemu_opt_get(opts, "dir");
1180 if (!dirname) {
c0f92b52 1181 error_setg(errp, "vvfat block driver requires a 'dir' option");
7ad9be64
KW
1182 ret = -EINVAL;
1183 goto fail;
1184 }
1185
1186 s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
1187 floppy = qemu_opt_get_bool(opts, "floppy", false);
1188
d5941dda
WB
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;
1197 }
1198 memcpy(s->volume_label, label, label_length);
d208c50d
KW
1199 } else {
1200 memcpy(s->volume_label, "QEMU VVFAT", 10);
d5941dda
WB
1201 }
1202
7ad9be64
KW
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;
1212 }
7ad9be64
KW
1213 cyls = 80;
1214 heads = 2;
1215 } else {
1216 /* 32MB or 504MB disk*/
1217 if (!s->fat_type) {
1218 s->fat_type = 16;
1219 }
4dc705dc 1220 s->offset_to_bootsector = 0x3f;
7ad9be64
KW
1221 cyls = s->fat_type == 12 ? 64 : 1024;
1222 heads = 16;
1223 secs = 63;
1224 }
1225
1226 switch (s->fat_type) {
1227 case 32:
d6a7e54e 1228 fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "
7ad9be64
KW
1229 "You are welcome to do so!\n");
1230 break;
1231 case 16:
1232 case 12:
1233 break;
1234 default:
c0f92b52 1235 error_setg(errp, "Valid FAT types are only 12, 16 and 32");
7ad9be64
KW
1236 ret = -EINVAL;
1237 goto fail;
1238 }
1239
1240
a046433a
FB
1241 s->bs = bs;
1242
a046433a 1243 /* LATER TODO: if FAT32, adjust */
a046433a 1244 s->sectors_per_cluster=0x10;
de167e41
FB
1245
1246 s->current_cluster=0xffffffff;
de167e41 1247
eecc7747 1248 s->qcow = NULL;
a046433a
FB
1249 s->qcow_filename = NULL;
1250 s->fat2 = NULL;
1251 s->downcase_short_names = 1;
3b46e624 1252
4480e0f9
MA
1253 fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
1254 dirname, cyls, heads, secs);
a046433a 1255
4dc705dc 1256 s->sector_count = cyls * heads * secs - s->offset_to_bootsector;
5a742b55 1257
7ad9be64 1258 if (qemu_opt_get_bool(opts, "rw", false)) {
e2b8247a
JC
1259 if (!bdrv_is_read_only(bs)) {
1260 ret = enable_write_target(bs, errp);
1261 if (ret < 0) {
1262 goto fail;
1263 }
1264 } else {
1265 ret = -EPERM;
1266 error_setg(errp,
1267 "Unable to set VVFAT to 'rw' when drive is read-only");
1268 goto fail;
1269 }
1270 } else {
1271 /* read only is the default for safety */
1272 ret = bdrv_set_read_only(bs, true, &local_err);
78f27bd0 1273 if (ret < 0) {
e2b8247a 1274 error_propagate(errp, local_err);
7ad9be64
KW
1275 goto fail;
1276 }
b570094d
TS
1277 }
1278
4480e0f9 1279 bs->total_sectors = cyls * heads * secs;
b570094d 1280
d11c8917 1281 if (init_directories(s, dirname, heads, secs, errp)) {
7ad9be64
KW
1282 ret = -EIO;
1283 goto fail;
4480e0f9 1284 }
de167e41 1285
4dc705dc
HP
1286 s->sector_count = s->offset_to_root_dir
1287 + s->sectors_per_cluster * s->cluster_count;
b570094d 1288
3397f0cb
KW
1289 /* Disable migration when vvfat is used rw */
1290 if (s->qcow) {
81e5f78a
AG
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));
fe44dc91
AA
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;
1300 }
3397f0cb
KW
1301 }
1302
4dc705dc 1303 if (s->offset_to_bootsector > 0) {
fe44dc91
AA
1304 init_mbr(s, cyls, heads, secs);
1305 }
1306
1307 qemu_co_mutex_init(&s->lock);
1308
7ad9be64
KW
1309 ret = 0;
1310fail:
1311 qemu_opts_del(opts);
1312 return ret;
de167e41
FB
1313}
1314
a6506481
EB
1315static void vvfat_refresh_limits(BlockDriverState *bs, Error **errp)
1316{
a5b8dd2c 1317 bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
a6506481
EB
1318}
1319
de167e41
FB
1320static inline void vvfat_close_current_file(BDRVVVFATState *s)
1321{
1322 if(s->current_mapping) {
d6a7e54e
HP
1323 s->current_mapping = NULL;
1324 if (s->current_fd) {
1325 qemu_close(s->current_fd);
1326 s->current_fd = 0;
1327 }
de167e41 1328 }
a046433a 1329 s->current_cluster = -1;
de167e41
FB
1330}
1331
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
1334 */
1335static inline int find_mapping_for_cluster_aux(BDRVVVFATState* s,int cluster_num,int index1,int index2)
1336{
de167e41 1337 while(1) {
88bf7950 1338 int index3;
d6a7e54e
HP
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;
1352 }
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)));
de167e41
FB
1359 }
1360}
1361
c227f099 1362static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_num)
de167e41
FB
1363{
1364 int index=find_mapping_for_cluster_aux(s,cluster_num,0,s->mapping.next);
c227f099 1365 mapping_t* mapping;
de167e41 1366 if(index>=s->mapping.next)
511d2b14 1367 return NULL;
de167e41
FB
1368 mapping=array_get(&(s->mapping),index);
1369 if(mapping->begin>cluster_num)
511d2b14 1370 return NULL;
a046433a 1371 assert(mapping->begin<=cluster_num && mapping->end>cluster_num);
de167e41
FB
1372 return mapping;
1373}
1374
c227f099 1375static int open_file(BDRVVVFATState* s,mapping_t* mapping)
de167e41
FB
1376{
1377 if(!mapping)
d6a7e54e 1378 return -1;
de167e41 1379 if(!s->current_mapping ||
d6a7e54e
HP
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;
de167e41
FB
1388 }
1389 return 0;
1390}
1391
1392static inline int read_cluster(BDRVVVFATState *s,int cluster_num)
1393{
1394 if(s->current_cluster != cluster_num) {
d6a7e54e
HP
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);
1403
1404 assert(!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end));
1405
1406 if (mapping && mapping->mode & MODE_DIRECTORY) {
1407 vvfat_close_current_file(s);
1408 s->current_mapping = mapping;
a046433a 1409read_cluster_directory:
d6a7e54e
HP
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;
1417 }
1418
1419 if(open_file(s,mapping))
1420 return -2;
1421 } else if (s->current_mapping->mode & MODE_DIRECTORY)
1422 goto read_cluster_directory;
1423
1424 assert(s->current_fd);
1425
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;
1434 }
1435 s->current_cluster = cluster_num;
de167e41
FB
1436 }
1437 return 0;
1438}
1439
a046433a 1440#ifdef DEBUG
c227f099 1441static void print_direntry(const direntry_t* direntry)
de167e41 1442{
a046433a
FB
1443 int j = 0;
1444 char buffer[1024];
1445
3e89cb04 1446 fprintf(stderr, "direntry %p: ", direntry);
de167e41 1447 if(!direntry)
d6a7e54e 1448 return;
a046433a 1449 if(is_long_name(direntry)) {
d6a7e54e
HP
1450 unsigned char* c=(unsigned char*)direntry;
1451 int i;
1452 for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)
3891b370 1453#define ADD_CHAR(c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;}
d6a7e54e
HP
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);
de167e41 1461 } else {
d6a7e54e
HP
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));
de167e41
FB
1470 }
1471}
1472
c227f099 1473static void print_mapping(const mapping_t* mapping)
de167e41 1474{
3e89cb04
KW
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);
1479
a046433a 1480 if (mapping->mode & MODE_DIRECTORY)
d6a7e54e 1481 fprintf(stderr, "parent_mapping_index = %d, first_dir_index = %d\n", mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);
a046433a 1482 else
d6a7e54e 1483 fprintf(stderr, "offset = %d\n", mapping->info.file.offset);
de167e41 1484}
a046433a 1485#endif
de167e41 1486
5fafdf24 1487static int vvfat_read(BlockDriverState *bs, int64_t sector_num,
a046433a 1488 uint8_t *buf, int nb_sectors)
de167e41 1489{
a046433a 1490 BDRVVVFATState *s = bs->opaque;
de167e41 1491 int i;
de167e41 1492
a046433a 1493 for(i=0;i<nb_sectors;i++,sector_num++) {
d6a7e54e
HP
1494 if (sector_num >= bs->total_sectors)
1495 return -1;
1496 if (s->qcow) {
d6a644bb 1497 int64_t n;
6f712ee0 1498 int ret;
d6a644bb
EB
1499 ret = bdrv_is_allocated(s->qcow->bs, sector_num * BDRV_SECTOR_SIZE,
1500 (nb_sectors - i) * BDRV_SECTOR_SIZE, &n);
6f712ee0
EB
1501 if (ret < 0) {
1502 return ret;
1503 }
1504 if (ret) {
d6a644bb
EB
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)) {
7704df98
KW
1510 return -1;
1511 }
d6a644bb
EB
1512 i += (n >> BDRV_SECTOR_BITS) - 1;
1513 sector_num += (n >> BDRV_SECTOR_BITS) - 1;
7704df98
KW
1514 continue;
1515 }
d6a644bb
EB
1516 DLOG(fprintf(stderr, "sector %" PRId64 " not allocated\n",
1517 sector_num));
d6a7e54e 1518 }
4dc705dc
HP
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);
1534 }
d6a7e54e 1535 } else {
4dc705dc 1536 uint32_t sector = sector_num - s->offset_to_root_dir,
d6a7e54e
HP
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;
1543 }
1544 memcpy(buf+i*0x200,s->cluster+sector_offset_in_cluster*0x200,0x200);
1545 }
de167e41 1546 }
de167e41
FB
1547 return 0;
1548}
1549
4575eb49
KW
1550static int coroutine_fn
1551vvfat_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1552 QEMUIOVector *qiov, int flags)
2914caa0
PB
1553{
1554 int ret;
1555 BDRVVVFATState *s = bs->opaque;
4575eb49
KW
1556 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
1557 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1558 void *buf;
1559
1560 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1561 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1562
1563 buf = g_try_malloc(bytes);
1564 if (bytes && buf == NULL) {
1565 return -ENOMEM;
1566 }
1567
2914caa0
PB
1568 qemu_co_mutex_lock(&s->lock);
1569 ret = vvfat_read(bs, sector_num, buf, nb_sectors);
1570 qemu_co_mutex_unlock(&s->lock);
4575eb49
KW
1571
1572 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1573 g_free(buf);
1574
2914caa0
PB
1575 return ret;
1576}
1577
a046433a 1578/* LATER TODO: statify all functions */
de167e41 1579
a046433a
FB
1580/*
1581 * Idea of the write support (use snapshot):
de167e41 1582 *
a046433a
FB
1583 * 1. check if all data is consistent, recording renames, modifications,
1584 * new files and directories (in s->commits).
de167e41 1585 *
a046433a 1586 * 2. if the data is not consistent, stop committing
de167e41 1587 *
a046433a
FB
1588 * 3. handle renames, and create new files and directories (do not yet
1589 * write their contents)
de167e41 1590 *
a046433a
FB
1591 * 4. walk the directories, fixing the mapping and direntries, and marking
1592 * the handled mappings as not deleted
de167e41 1593 *
a046433a 1594 * 5. commit the contents of the files
de167e41 1595 *
a046433a 1596 * 6. handle deleted files and directories
de167e41
FB
1597 *
1598 */
1599
c227f099 1600typedef struct commit_t {
a046433a
FB
1601 char* path;
1602 union {
d6a7e54e
HP
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;
a046433a
FB
1607 } param;
1608 /* DELETEs and RMDIRs are handled differently: see handle_deletes() */
1609 enum {
d6a7e54e 1610 ACTION_RENAME, ACTION_WRITEOUT, ACTION_NEW_FILE, ACTION_MKDIR
a046433a 1611 } action;
c227f099 1612} commit_t;
de167e41 1613
a046433a 1614static void clear_commits(BDRVVVFATState* s)
de167e41
FB
1615{
1616 int i;
a046433a
FB
1617DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));
1618 for (i = 0; i < s->commits.next; i++) {
d6a7e54e
HP
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);
ce137829 1623 g_free(commit->path);
d6a7e54e
HP
1624 } else
1625 assert(commit->path == NULL);
de167e41 1626 }
a046433a 1627 s->commits.next = 0;
de167e41
FB
1628}
1629
a046433a 1630static void schedule_rename(BDRVVVFATState* s,
d6a7e54e 1631 uint32_t cluster, char* new_path)
de167e41 1632{
c227f099 1633 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1634 commit->path = new_path;
1635 commit->param.rename.cluster = cluster;
1636 commit->action = ACTION_RENAME;
de167e41
FB
1637}
1638
a046433a 1639static void schedule_writeout(BDRVVVFATState* s,
d6a7e54e 1640 int dir_index, uint32_t modified_offset)
de167e41 1641{
c227f099 1642 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
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;
de167e41
FB
1647}
1648
a046433a 1649static void schedule_new_file(BDRVVVFATState* s,
d6a7e54e 1650 char* path, uint32_t first_cluster)
de167e41 1651{
c227f099 1652 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1653 commit->path = path;
1654 commit->param.new_file.first_cluster = first_cluster;
1655 commit->action = ACTION_NEW_FILE;
1656}
1657
1658static void schedule_mkdir(BDRVVVFATState* s, uint32_t cluster, char* path)
1659{
c227f099 1660 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1661 commit->path = path;
1662 commit->param.mkdir.cluster = cluster;
1663 commit->action = ACTION_MKDIR;
1664}
1665
1666typedef struct {
64eaabda
TS
1667 /*
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.
1671 */
1672 unsigned char name[0x3f * 13 + 1];
e03da26b 1673 gunichar2 name2[0x3f * 13 + 1];
a046433a
FB
1674 int checksum, len;
1675 int sequence_number;
1676} long_file_name;
1677
1678static void lfn_init(long_file_name* lfn)
1679{
1680 lfn->sequence_number = lfn->len = 0;
1681 lfn->checksum = 0x100;
1682}
1683
1684/* return 0 if parsed successfully, > 0 if no long name, < 0 if error */
1685static int parse_long_name(long_file_name* lfn,
d6a7e54e 1686 const direntry_t* direntry)
a046433a
FB
1687{
1688 int i, j, offset;
1689 const unsigned char* pointer = (const unsigned char*)direntry;
1690
1691 if (!is_long_name(direntry))
d6a7e54e 1692 return 1;
a046433a
FB
1693
1694 if (pointer[0] & 0x40) {
e03da26b 1695 /* first entry; do some initialization */
d6a7e54e
HP
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;
e03da26b
HP
1700 } else if ((pointer[0] & 0x3f) != --lfn->sequence_number) {
1701 /* not the expected sequence number */
d6a7e54e 1702 return -1;
e03da26b
HP
1703 } else if (pointer[13] != lfn->checksum) {
1704 /* not the expected checksum */
d6a7e54e 1705 return -2;
e03da26b
HP
1706 } else if (pointer[12] || pointer[26] || pointer[27]) {
1707 /* invalid zero fields */
d6a7e54e 1708 return -3;
e03da26b 1709 }
a046433a
FB
1710
1711 offset = 13 * (lfn->sequence_number - 1);
1712 for (i = 0, j = 1; i < 13; i++, j+=2) {
d6a7e54e
HP
1713 if (j == 11)
1714 j = 14;
1715 else if (j == 26)
1716 j = 28;
a046433a 1717
e03da26b
HP
1718 if (pointer[j] == 0 && pointer[j + 1] == 0) {
1719 /* end of long file name */
1720 break;
1721 }
1722 gunichar2 c = (pointer[j + 1] << 8) + pointer[j];
1723 lfn->name2[offset + i] = c;
de167e41 1724 }
a046433a 1725
e03da26b
HP
1726 if (pointer[0] & 0x40) {
1727 /* first entry; set len */
1728 lfn->len = offset + i;
1729 }
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;
1736 }
1737 lfn->len = olen;
1738 memcpy(lfn->name, utf8, olen + 1);
1739 g_free(utf8);
1740 }
a046433a 1741
de167e41
FB
1742 return 0;
1743}
1744
a046433a
FB
1745/* returns 0 if successful, >0 if no short_name, and <0 on error */
1746static int parse_short_name(BDRVVVFATState* s,
d6a7e54e 1747 long_file_name* lfn, direntry_t* direntry)
de167e41 1748{
a046433a 1749 int i, j;
de167e41 1750
a046433a 1751 if (!is_short_name(direntry))
d6a7e54e 1752 return 1;
a046433a
FB
1753
1754 for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);
1755 for (i = 0; i <= j; i++) {
e03da26b
HP
1756 uint8_t c = direntry->name[i];
1757 if (c != to_valid_short_char(c)) {
d6a7e54e 1758 return -1;
e03da26b 1759 } else if (s->downcase_short_names) {
d6a7e54e 1760 lfn->name[i] = qemu_tolower(direntry->name[i]);
e03da26b 1761 } else {
d6a7e54e 1762 lfn->name[i] = direntry->name[i];
e03da26b 1763 }
de167e41
FB
1764 }
1765
f671d173
SW
1766 for (j = 2; j >= 0 && direntry->name[8 + j] == ' '; j--) {
1767 }
a046433a 1768 if (j >= 0) {
d6a7e54e
HP
1769 lfn->name[i++] = '.';
1770 lfn->name[i + j + 1] = '\0';
1771 for (;j >= 0; j--) {
f671d173 1772 uint8_t c = direntry->name[8 + j];
e03da26b 1773 if (c != to_valid_short_char(c)) {
f671d173
SW
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;
1779 }
d6a7e54e 1780 }
a046433a 1781 } else
d6a7e54e 1782 lfn->name[i + j + 1] = '\0';
a046433a 1783
8c4517fd
HP
1784 if (lfn->name[0] == DIR_KANJI_FAKE) {
1785 lfn->name[0] = DIR_KANJI;
78f002c9 1786 }
ffe8ab83 1787 lfn->len = strlen((char*)lfn->name);
a046433a
FB
1788
1789 return 0;
de167e41
FB
1790}
1791
a046433a 1792static inline uint32_t modified_fat_get(BDRVVVFATState* s,
d6a7e54e 1793 unsigned int cluster)
de167e41 1794{
a046433a 1795 if (cluster < s->last_cluster_of_root_directory) {
d6a7e54e
HP
1796 if (cluster + 1 == s->last_cluster_of_root_directory)
1797 return s->max_fat_value;
1798 else
1799 return cluster + 1;
a046433a
FB
1800 }
1801
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;
1811 }
1812}
1813
6f712ee0
EB
1814static inline bool cluster_was_modified(BDRVVVFATState *s,
1815 uint32_t cluster_num)
a046433a
FB
1816{
1817 int was_modified = 0;
d6a644bb 1818 int i;
a046433a 1819
eecc7747
KW
1820 if (s->qcow == NULL) {
1821 return 0;
1822 }
a046433a 1823
eecc7747
KW
1824 for (i = 0; !was_modified && i < s->sectors_per_cluster; i++) {
1825 was_modified = bdrv_is_allocated(s->qcow->bs,
d6a644bb
EB
1826 (cluster2sector(s, cluster_num) +
1827 i) * BDRV_SECTOR_SIZE,
1828 BDRV_SECTOR_SIZE, NULL);
eecc7747 1829 }
a046433a 1830
6f712ee0
EB
1831 /*
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.
1836 */
1837 return !!was_modified;
de167e41
FB
1838}
1839
a046433a 1840static const char* get_basename(const char* path)
de167e41 1841{
a046433a
FB
1842 char* basename = strrchr(path, '/');
1843 if (basename == NULL)
d6a7e54e 1844 return path;
a046433a 1845 else
d6a7e54e 1846 return basename + 1; /* strip '/' */
de167e41
FB
1847}
1848
a046433a
FB
1849/*
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.
1855 */
1856typedef enum {
1857 USED_DIRECTORY = 1, USED_FILE = 2, USED_ANY = 3, USED_ALLOCATED = 4
c227f099 1858} used_t;
de167e41 1859
a046433a
FB
1860/*
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.
1863 *
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.
1866 *
1867 * Further, the files/directories handled by this function are
1868 * assumed to be *not* deleted (and *only* those).
1869 */
1870static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,
d6a7e54e 1871 direntry_t* direntry, const char* path)
de167e41 1872{
a046433a
FB
1873 /*
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:
1878 *
1879 * - do_commit will write the cluster into the file at the given
1880 * offset, but
1881 *
1882 * - the cluster which is overwritten should be moved to a later
1883 * position in the file.
1884 *
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.
1889 */
1890 int copy_it = 0;
1891 int was_modified = 0;
1892 int32_t ret = 0;
1893
1894 uint32_t cluster_num = begin_of_direntry(direntry);
1895 uint32_t offset = 0;
1896 int first_mapping_index = -1;
c227f099 1897 mapping_t* mapping = NULL;
a046433a 1898 const char* basename2 = NULL;
de167e41 1899
a046433a 1900 vvfat_close_current_file(s);
de167e41 1901
a046433a
FB
1902 /* the root directory */
1903 if (cluster_num == 0)
d6a7e54e 1904 return 0;
de167e41 1905
a046433a
FB
1906 /* write support */
1907 if (s->qcow) {
d6a7e54e 1908 basename2 = get_basename(path);
de167e41 1909
d6a7e54e 1910 mapping = find_mapping_for_cluster(s, cluster_num);
a046433a 1911
d6a7e54e
HP
1912 if (mapping) {
1913 const char* basename;
da2414e9 1914
d6a7e54e
HP
1915 assert(mapping->mode & MODE_DELETED);
1916 mapping->mode &= ~MODE_DELETED;
a046433a 1917
d6a7e54e 1918 basename = get_basename(mapping->path);
a046433a 1919
d6a7e54e 1920 assert(mapping->mode & MODE_NORMAL);
a046433a 1921
d6a7e54e
HP
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 {
43dc2a64 1929 abort();
d6a7e54e
HP
1930 return 0;
1931 }
de167e41
FB
1932 }
1933
a046433a 1934 while(1) {
d6a7e54e
HP
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);
de167e41 1941
a046433a 1942
d6a7e54e
HP
1943 if (mapping &&
1944 (mapping->mode & MODE_DIRECTORY) == 0) {
a046433a 1945
d6a7e54e
HP
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 */
43dc2a64 1950 abort();
d6a7e54e
HP
1951 copy_it = 1;
1952 } else if (offset == 0) {
1953 const char* basename = get_basename(mapping->path);
a046433a 1954
d6a7e54e
HP
1955 if (strcmp(basename, basename2))
1956 copy_it = 1;
1957 first_mapping_index = array_index(&(s->mapping), mapping);
1958 }
a046433a 1959
d6a7e54e
HP
1960 if (mapping->first_mapping_index != first_mapping_index
1961 && mapping->info.file.offset > 0) {
43dc2a64 1962 abort();
d6a7e54e
HP
1963 copy_it = 1;
1964 }
1965
1966 /* need to write out? */
1967 if (!was_modified && is_file(direntry)) {
1968 was_modified = 1;
1969 schedule_writeout(s, mapping->dir_index, offset);
1970 }
1971 }
1972 }
1973
1974 if (copy_it) {
d6a644bb 1975 int i;
d6a7e54e
HP
1976 /*
1977 * This is horribly inefficient, but that is okay, since
1978 * it is rarely executed, if at all.
1979 */
1980 int64_t offset = cluster2sector(s, cluster_num);
1981
1982 vvfat_close_current_file(s);
7704df98 1983 for (i = 0; i < s->sectors_per_cluster; i++) {
eecc7747
KW
1984 int res;
1985
d6a644bb
EB
1986 res = bdrv_is_allocated(s->qcow->bs,
1987 (offset + i) * BDRV_SECTOR_SIZE,
1988 BDRV_SECTOR_SIZE, NULL);
6f712ee0
EB
1989 if (res < 0) {
1990 return -1;
1991 }
eecc7747
KW
1992 if (!res) {
1993 res = vvfat_read(s->bs, offset, s->cluster_buffer, 1);
1994 if (res) {
7704df98
KW
1995 return -1;
1996 }
18d51c4b 1997 res = bdrv_write(s->qcow, offset, s->cluster_buffer, 1);
eecc7747 1998 if (res) {
7704df98
KW
1999 return -2;
2000 }
2001 }
2002 }
d6a7e54e
HP
2003 }
2004 }
a046433a 2005
d6a7e54e
HP
2006 ret++;
2007 if (s->used_clusters[cluster_num] & USED_ANY)
2008 return 0;
2009 s->used_clusters[cluster_num] = USED_FILE;
a046433a 2010
d6a7e54e 2011 cluster_num = modified_fat_get(s, cluster_num);
a046433a 2012
d6a7e54e
HP
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;
a046433a 2017
d6a7e54e 2018 offset += s->cluster_size;
a046433a 2019 }
de167e41
FB
2020}
2021
a046433a 2022/*
5fafdf24 2023 * This function looks at the modified data (qcow).
a046433a
FB
2024 * It returns 0 upon inconsistency or error, and the number of clusters
2025 * used by the directory, its subdirectories and their files.
2026 */
2027static int check_directory_consistency(BDRVVVFATState *s,
d6a7e54e 2028 int cluster_num, const char* path)
de167e41 2029{
a046433a 2030 int ret = 0;
7267c094 2031 unsigned char* cluster = g_malloc(s->cluster_size);
c227f099
AL
2032 direntry_t* direntries = (direntry_t*)cluster;
2033 mapping_t* mapping = find_mapping_for_cluster(s, cluster_num);
a046433a
FB
2034
2035 long_file_name lfn;
2036 int path_len = strlen(path);
0d460d6f 2037 char path2[PATH_MAX + 1];
a046433a
FB
2038
2039 assert(path_len < PATH_MAX); /* len was tested before! */
363a37d5 2040 pstrcpy(path2, sizeof(path2), path);
a046433a
FB
2041 path2[path_len] = '/';
2042 path2[path_len + 1] = '\0';
2043
2044 if (mapping) {
d6a7e54e
HP
2045 const char* basename = get_basename(mapping->path);
2046 const char* basename2 = get_basename(path);
a046433a 2047
d6a7e54e 2048 assert(mapping->mode & MODE_DIRECTORY);
a046433a 2049
d6a7e54e
HP
2050 assert(mapping->mode & MODE_DELETED);
2051 mapping->mode &= ~MODE_DELETED;
a046433a 2052
d6a7e54e
HP
2053 if (strcmp(basename, basename2))
2054 schedule_rename(s, cluster_num, g_strdup(path));
a046433a 2055 } else
d6a7e54e
HP
2056 /* new directory */
2057 schedule_mkdir(s, cluster_num, g_strdup(path));
3b46e624 2058
a046433a
FB
2059 lfn_init(&lfn);
2060 do {
d6a7e54e
HP
2061 int i;
2062 int subret = 0;
a046433a 2063
d6a7e54e 2064 ret++;
a046433a 2065
d6a7e54e
HP
2066 if (s->used_clusters[cluster_num] & USED_ANY) {
2067 fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num);
6262bbd3 2068 goto fail;
d6a7e54e
HP
2069 }
2070 s->used_clusters[cluster_num] = USED_DIRECTORY;
a046433a
FB
2071
2072DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num)));
d6a7e54e
HP
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:
ce137829 2078 g_free(cluster);
d6a7e54e
HP
2079 return 0;
2080 }
a046433a 2081
d6a7e54e
HP
2082 for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) {
2083 int cluster_count = 0;
a046433a 2084
b2bedb21 2085DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i));
d6a7e54e
HP
2086 if (is_volume_label(direntries + i) || is_dot(direntries + i) ||
2087 is_free(direntries + i))
2088 continue;
2089
2090 subret = parse_long_name(&lfn, direntries + i);
2091 if (subret < 0) {
2092 fprintf(stderr, "Error in long name\n");
2093 goto fail;
2094 }
2095 if (subret == 0 || is_free(direntries + i))
2096 continue;
2097
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;
2103 }
2104 if (subret > 0 || !strcmp((char*)lfn.name, ".")
2105 || !strcmp((char*)lfn.name, ".."))
2106 continue;
2107 }
2108 lfn.checksum = 0x100; /* cannot use long name twice */
2109
2110 if (path_len + 1 + lfn.len >= PATH_MAX) {
2111 fprintf(stderr, "Name too long: %s/%s\n", path, lfn.name);
2112 goto fail;
2113 }
363a37d5
BS
2114 pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1,
2115 (char*)lfn.name);
a046433a 2116
d6a7e54e
HP
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;
2121 }
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;
2127 }
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 !=
13385ae1 2132 DIV_ROUND_UP(le32_to_cpu(direntries[i].size), s->cluster_size)) {
d6a7e54e
HP
2133 DLOG(fprintf(stderr, "Cluster count mismatch\n"));
2134 goto fail;
2135 }
2136 } else
43dc2a64 2137 abort(); /* cluster_count = 0; */
a046433a 2138
d6a7e54e
HP
2139 ret += cluster_count;
2140 }
de167e41 2141
d6a7e54e 2142 cluster_num = modified_fat_get(s, cluster_num);
a046433a 2143 } while(!fat_eof(s, cluster_num));
de167e41 2144
ce137829 2145 g_free(cluster);
a046433a
FB
2146 return ret;
2147}
2148
2149/* returns 1 on success */
2150static int is_consistent(BDRVVVFATState* s)
2151{
2152 int i, check;
2153 int used_clusters_count = 0;
2154
2155DLOG(checkpoint());
2156 /*
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
2168 */
2169 if (s->fat2 == NULL) {
d6a7e54e
HP
2170 int size = 0x200 * s->sectors_per_fat;
2171 s->fat2 = g_malloc(size);
2172 memcpy(s->fat2, s->fat.pointer, size);
a046433a
FB
2173 }
2174 check = vvfat_read(s->bs,
4dc705dc 2175 s->offset_to_fat, s->fat2, s->sectors_per_fat);
a046433a 2176 if (check) {
d6a7e54e
HP
2177 fprintf(stderr, "Could not copy fat\n");
2178 return 0;
a046433a
FB
2179 }
2180 assert (s->used_clusters);
2181 for (i = 0; i < sector2cluster(s, s->sector_count); i++)
d6a7e54e 2182 s->used_clusters[i] &= ~USED_ANY;
a046433a
FB
2183
2184 clear_commits(s);
2185
2186 /* mark every mapped file/directory as deleted.
2187 * (check_directory_consistency() will unmark those still present). */
2188 if (s->qcow)
d6a7e54e
HP
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;
2193 }
a046433a
FB
2194
2195 used_clusters_count = check_directory_consistency(s, 0, s->path);
2196 if (used_clusters_count <= 0) {
d6a7e54e
HP
2197 DLOG(fprintf(stderr, "problem in directory\n"));
2198 return 0;
de167e41
FB
2199 }
2200
a046433a
FB
2201 check = s->last_cluster_of_root_directory;
2202 for (i = check; i < sector2cluster(s, s->sector_count); i++) {
d6a7e54e
HP
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;
2207 }
2208 check++;
2209 }
a046433a 2210
d6a7e54e
HP
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;
2215 }
a046433a
FB
2216 }
2217
2218 if (check != used_clusters_count)
d6a7e54e 2219 return 0;
a046433a
FB
2220
2221 return used_clusters_count;
2222}
2223
2224static inline void adjust_mapping_indices(BDRVVVFATState* s,
d6a7e54e 2225 int offset, int adjust)
a046433a
FB
2226{
2227 int i;
2228
2229 for (i = 0; i < s->mapping.next; i++) {
d6a7e54e 2230 mapping_t* mapping = array_get(&(s->mapping), i);
a046433a
FB
2231
2232#define ADJUST_MAPPING_INDEX(name) \
d6a7e54e
HP
2233 if (mapping->name >= offset) \
2234 mapping->name += adjust
a046433a 2235
d6a7e54e
HP
2236 ADJUST_MAPPING_INDEX(first_mapping_index);
2237 if (mapping->mode & MODE_DIRECTORY)
2238 ADJUST_MAPPING_INDEX(info.dir.parent_mapping_index);
de167e41 2239 }
a046433a
FB
2240}
2241
2242/* insert or update mapping */
c227f099 2243static mapping_t* insert_mapping(BDRVVVFATState* s,
d6a7e54e 2244 uint32_t begin, uint32_t end)
a046433a
FB
2245{
2246 /*
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
2252 */
2253 int index = find_mapping_for_cluster_aux(s, begin, 0, s->mapping.next);
c227f099
AL
2254 mapping_t* mapping = NULL;
2255 mapping_t* first_mapping = array_get(&(s->mapping), 0);
a046433a
FB
2256
2257 if (index < s->mapping.next && (mapping = array_get(&(s->mapping), index))
d6a7e54e
HP
2258 && mapping->begin < begin) {
2259 mapping->end = begin;
2260 index++;
2261 mapping = array_get(&(s->mapping), index);
a046433a
FB
2262 }
2263 if (index >= s->mapping.next || mapping->begin > begin) {
d6a7e54e
HP
2264 mapping = array_insert(&(s->mapping), index, 1);
2265 mapping->path = NULL;
2266 adjust_mapping_indices(s, index, +1);
a046433a
FB
2267 }
2268
2269 mapping->begin = begin;
2270 mapping->end = end;
de167e41 2271
c227f099 2272DLOG(mapping_t* next_mapping;
a046433a
FB
2273assert(index + 1 >= s->mapping.next ||
2274((next_mapping = array_get(&(s->mapping), index + 1)) &&
2275 next_mapping->begin >= end)));
2276
c227f099 2277 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
d6a7e54e
HP
2278 s->current_mapping = array_get(&(s->mapping),
2279 s->current_mapping - first_mapping);
a046433a
FB
2280
2281 return mapping;
2282}
2283
2284static int remove_mapping(BDRVVVFATState* s, int mapping_index)
2285{
c227f099
AL
2286 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
2287 mapping_t* first_mapping = array_get(&(s->mapping), 0);
a046433a
FB
2288
2289 /* free mapping */
ce137829
SW
2290 if (mapping->first_mapping_index < 0) {
2291 g_free(mapping->path);
2292 }
a046433a
FB
2293
2294 /* remove from s->mapping */
2295 array_remove(&(s->mapping), mapping_index);
2296
2297 /* adjust all references to mappings */
2298 adjust_mapping_indices(s, mapping_index, -1);
2299
c227f099 2300 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
d6a7e54e
HP
2301 s->current_mapping = array_get(&(s->mapping),
2302 s->current_mapping - first_mapping);
de167e41 2303
de167e41
FB
2304 return 0;
2305}
2306
a046433a
FB
2307static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust)
2308{
2309 int i;
2310 for (i = 0; i < s->mapping.next; i++) {
d6a7e54e
HP
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;
a046433a
FB
2317 }
2318}
de167e41 2319
c227f099 2320static direntry_t* insert_direntries(BDRVVVFATState* s,
d6a7e54e 2321 int dir_index, int count)
de167e41 2322{
a046433a
FB
2323 /*
2324 * make room in s->directory,
2325 * adjust_dirindices
2326 */
c227f099 2327 direntry_t* result = array_insert(&(s->directory), dir_index, count);
a046433a 2328 if (result == NULL)
d6a7e54e 2329 return NULL;
a046433a 2330 adjust_dirindices(s, dir_index, count);
de167e41
FB
2331 return result;
2332}
2333
a046433a
FB
2334static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)
2335{
2336 int ret = array_remove_slice(&(s->directory), dir_index, count);
2337 if (ret)
d6a7e54e 2338 return ret;
a046433a
FB
2339 adjust_dirindices(s, dir_index, -count);
2340 return 0;
2341}
de167e41 2342
a046433a
FB
2343/*
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)
2348 */
2349static int commit_mappings(BDRVVVFATState* s,
d6a7e54e 2350 uint32_t first_cluster, int dir_index)
de167e41 2351{
c227f099
AL
2352 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2353 direntry_t* direntry = array_get(&(s->directory), dir_index);
a046433a
FB
2354 uint32_t cluster = first_cluster;
2355
2356 vvfat_close_current_file(s);
2357
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)) ?
d6a7e54e 2363 MODE_DIRECTORY : MODE_NORMAL;
a046433a
FB
2364
2365 while (!fat_eof(s, cluster)) {
d6a7e54e
HP
2366 uint32_t c, c1;
2367
2368 for (c = cluster, c1 = modified_fat_get(s, c); c + 1 == c1;
2369 c = c1, c1 = modified_fat_get(s, c1));
2370
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);
2378 }
2379 assert(mapping == array_get(&(s->mapping), s->mapping.next - 1)
2380 || mapping[1].begin >= c);
2381 mapping->end = c;
2382
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);
2387
2388 if (next_mapping == NULL || next_mapping->begin > c1) {
2389 int i1 = array_index(&(s->mapping), mapping);
2390
2391 next_mapping = insert_mapping(s, c1, c1+1);
2392
2393 if (c1 < c)
2394 i1++;
2395 mapping = array_get(&(s->mapping), i1);
2396 }
2397
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;
2416
2417 mapping = next_mapping;
2418 }
2419
2420 cluster = c1;
a046433a 2421 }
de167e41 2422
de167e41
FB
2423 return 0;
2424}
2425
a046433a 2426static int commit_direntries(BDRVVVFATState* s,
d6a7e54e 2427 int dir_index, int parent_mapping_index)
de167e41 2428{
c227f099 2429 direntry_t* direntry = array_get(&(s->directory), dir_index);
a046433a 2430 uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);
c227f099 2431 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
a046433a
FB
2432
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;
2439
2440DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapping->path, parent_mapping_index));
2441
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));
2448
2449 mapping->info.dir.parent_mapping_index = parent_mapping_index;
2450
2451 if (first_cluster == 0) {
d6a7e54e
HP
2452 old_cluster_count = new_cluster_count =
2453 s->last_cluster_of_root_directory;
a046433a 2454 } else {
d6a7e54e
HP
2455 for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2456 c = fat_get(s, c))
2457 old_cluster_count++;
de167e41 2458
d6a7e54e
HP
2459 for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2460 c = modified_fat_get(s, c))
2461 new_cluster_count++;
a046433a 2462 }
de167e41 2463
a046433a 2464 if (new_cluster_count > old_cluster_count) {
d6a7e54e
HP
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;
a046433a 2469 } else if (new_cluster_count < old_cluster_count)
d6a7e54e
HP
2470 remove_direntries(s,
2471 current_dir_index + factor * new_cluster_count,
2472 factor * (old_cluster_count - new_cluster_count));
a046433a
FB
2473
2474 for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {
ebb72c9f 2475 direntry_t *first_direntry;
d6a7e54e
HP
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;
ebb72c9f
KW
2481
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));
2485
d6a7e54e 2486 current_dir_index += factor;
a046433a 2487 }
de167e41 2488
a046433a
FB
2489 ret = commit_mappings(s, first_cluster, dir_index);
2490 if (ret)
d6a7e54e 2491 return ret;
a046433a
FB
2492
2493 /* recurse */
2494 for (i = 0; i < factor * new_cluster_count; i++) {
d6a7e54e
HP
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;
2503 }
a046433a 2504 }
de167e41 2505
a046433a
FB
2506 return 0;
2507}
de167e41 2508
a046433a
FB
2509/* commit one file (adjust contents, adjust mapping),
2510 return first_mapping_index */
2511static int commit_one_file(BDRVVVFATState* s,
d6a7e54e 2512 int dir_index, uint32_t offset)
a046433a 2513{
c227f099 2514 direntry_t* direntry = array_get(&(s->directory), dir_index);
a046433a
FB
2515 uint32_t c = begin_of_direntry(direntry);
2516 uint32_t first_cluster = c;
c227f099 2517 mapping_t* mapping = find_mapping_for_cluster(s, c);
a046433a 2518 uint32_t size = filesize_of_direntry(direntry);
7267c094 2519 char* cluster = g_malloc(s->cluster_size);
a046433a
FB
2520 uint32_t i;
2521 int fd = 0;
2522
2523 assert(offset < size);
2524 assert((offset % s->cluster_size) == 0);
2525
2526 for (i = s->cluster_size; i < offset; i += s->cluster_size)
d6a7e54e 2527 c = modified_fat_get(s, c);
a046433a 2528
6165f4d8 2529 fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
a046433a 2530 if (fd < 0) {
d6a7e54e
HP
2531 fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
2532 strerror(errno), errno);
ce137829 2533 g_free(cluster);
d6a7e54e 2534 return fd;
de167e41 2535 }
ce137829
SW
2536 if (offset > 0) {
2537 if (lseek(fd, offset, SEEK_SET) != offset) {
2e1e79da 2538 qemu_close(fd);
ce137829
SW
2539 g_free(cluster);
2540 return -3;
2541 }
2542 }
a046433a
FB
2543
2544 while (offset < size) {
d6a7e54e
HP
2545 uint32_t c1;
2546 int rest_size = (size - offset > s->cluster_size ?
2547 s->cluster_size : size - offset);
2548 int ret;
a046433a 2549
d6a7e54e 2550 c1 = modified_fat_get(s, c);
a046433a 2551
d6a7e54e
HP
2552 assert((size - offset == 0 && fat_eof(s, c)) ||
2553 (size > offset && c >=2 && !fat_eof(s, c)));
a046433a 2554
d6a7e54e
HP
2555 ret = vvfat_read(s->bs, cluster2sector(s, c),
2556 (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
a046433a 2557
ce137829 2558 if (ret < 0) {
2e1e79da 2559 qemu_close(fd);
ce137829
SW
2560 g_free(cluster);
2561 return ret;
2562 }
a046433a 2563
ce137829 2564 if (write(fd, cluster, rest_size) < 0) {
2e1e79da 2565 qemu_close(fd);
ce137829
SW
2566 g_free(cluster);
2567 return -2;
2568 }
a046433a 2569
d6a7e54e
HP
2570 offset += rest_size;
2571 c = c1;
a046433a
FB
2572 }
2573
2dedf83e
KS
2574 if (ftruncate(fd, size)) {
2575 perror("ftruncate()");
2e1e79da 2576 qemu_close(fd);
ce137829 2577 g_free(cluster);
2dedf83e
KS
2578 return -4;
2579 }
2e1e79da 2580 qemu_close(fd);
ce137829 2581 g_free(cluster);
a046433a
FB
2582
2583 return commit_mappings(s, first_cluster, dir_index);
2584}
2585
2586#ifdef DEBUG
2587/* test, if all mappings point to valid direntries */
2588static void check1(BDRVVVFATState* s)
2589{
2590 int i;
2591 for (i = 0; i < s->mapping.next; i++) {
d6a7e54e
HP
2592 mapping_t* mapping = array_get(&(s->mapping), i);
2593 if (mapping->mode & MODE_DELETED) {
2594 fprintf(stderr, "deleted\n");
2595 continue;
2596 }
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);
2603 }
de167e41 2604 }
de167e41
FB
2605}
2606
a046433a
FB
2607/* test, if all direntries have mappings */
2608static void check2(BDRVVVFATState* s)
de167e41 2609{
de167e41 2610 int i;
a046433a 2611 int first_mapping = -1;
de167e41 2612
a046433a 2613 for (i = 0; i < s->directory.next; i++) {
d6a7e54e
HP
2614 direntry_t* direntry = array_get(&(s->directory), i);
2615
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));
2621 }
2622
2623 if ((i % (0x10 * s->sectors_per_cluster)) == 0) {
2624 /* cluster start */
2625 int j, count = 0;
2626
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);
2644 }
2645 }
2646 }
2647 }
2648 if (count == 0)
2649 first_mapping = -1;
2650 }
a046433a
FB
2651 }
2652}
2653#endif
de167e41 2654
a046433a
FB
2655static int handle_renames_and_mkdirs(BDRVVVFATState* s)
2656{
2657 int i;
de167e41 2658
a046433a
FB
2659#ifdef DEBUG
2660 fprintf(stderr, "handle_renames\n");
2661 for (i = 0; i < s->commits.next; i++) {
d6a7e54e
HP
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);
a046433a
FB
2664 }
2665#endif
2666
2667 for (i = 0; i < s->commits.next;) {
d6a7e54e
HP
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;
2673
2674 assert(commit->path);
2675 mapping->path = commit->path;
2676 if (rename(old_path, mapping->path))
2677 return -2;
2678
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;
2687
2688 /* recurse */
2689 while (!fat_eof(s, c)) {
2690 do {
2691 direntry_t* d = direntry + i;
2692
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);
2698
2699 assert(!strncmp(m->path, mapping->path, l2));
a046433a 2700
363a37d5
BS
2701 pstrcpy(new_path, l + diff + 1, mapping->path);
2702 pstrcpy(new_path + l1, l + diff + 1 - l1,
2703 m->path + l2);
a046433a 2704
d6a7e54e
HP
2705 schedule_rename(s, m->begin, new_path);
2706 }
2707 i++;
2708 } while((i % (0x10 * s->sectors_per_cluster)) != 0);
2709 c = fat_get(s, c);
2710 }
2711 }
de167e41 2712
ce137829 2713 g_free(old_path);
d6a7e54e
HP
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;
a046433a 2719
48c2f068
FB
2720#ifdef __MINGW32__
2721 if (mkdir(commit->path))
2722 return -5;
2723#else
2724 if (mkdir(commit->path, 0755))
2725 return -5;
2726#endif
a046433a 2727
d6a7e54e
HP
2728 mapping = insert_mapping(s, commit->param.mkdir.cluster,
2729 commit->param.mkdir.cluster + 1);
2730 if (mapping == NULL)
2731 return -6;
2732
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;
2741
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;
2750 }
2751 assert(j < s->mapping.next);
2752 mapping->info.dir.parent_mapping_index = j;
2753
2754 array_remove(&(s->commits), i);
2755 continue;
2756 }
2757
2758 i++;
a046433a
FB
2759 }
2760 return 0;
2761}
2762
2763/*
2764 * TODO: make sure that the short name is not matching *another* file
2765 */
2766static int handle_commits(BDRVVVFATState* s)
2767{
2768 int i, fail = 0;
2769
2770 vvfat_close_current_file(s);
2771
2772 for (i = 0; !fail && i < s->commits.next; i++) {
d6a7e54e
HP
2773 commit_t* commit = array_get(&(s->commits), i);
2774 switch(commit->action) {
2775 case ACTION_RENAME: case ACTION_MKDIR:
43dc2a64 2776 abort();
d6a7e54e
HP
2777 fail = -2;
2778 break;
2779 case ACTION_WRITEOUT: {
a6c6f76c
BS
2780#ifndef NDEBUG
2781 /* these variables are only used by assert() below */
d6a7e54e
HP
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);
a6c6f76c 2786#endif
a046433a 2787
d6a7e54e
HP
2788 assert(mapping);
2789 assert(mapping->begin == begin);
2790 assert(commit->path == NULL);
2791
2792 if (commit_one_file(s, commit->param.writeout.dir_index,
2793 commit->param.writeout.modified_offset))
2794 fail = -3;
2795
2796 break;
2797 }
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;
2803
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;
2809 }
2810
2811 if (i >= s->directory.next) {
2812 fail = -6;
2813 continue;
2814 }
2815
2816 /* make sure there exists an initial mapping */
2817 if (mapping && mapping->begin != begin) {
2818 mapping->end = begin;
2819 mapping = NULL;
2820 }
2821 if (mapping == NULL) {
2822 mapping = insert_mapping(s, begin, begin+1);
2823 }
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;
2830
2831 if (commit_one_file(s, i, 0))
2832 fail = -7;
2833
2834 break;
2835 }
2836 default:
43dc2a64 2837 abort();
d6a7e54e 2838 }
a046433a
FB
2839 }
2840 if (i > 0 && array_remove_slice(&(s->commits), 0, i))
d6a7e54e 2841 return -1;
a046433a
FB
2842 return fail;
2843}
2844
2845static int handle_deletes(BDRVVVFATState* s)
2846{
2847 int i, deferred = 1, deleted = 1;
2848
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) {
d6a7e54e
HP
2852 deferred = 0;
2853 deleted = 0;
2854
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);
2860
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;
2866
2867 if (rmdir(mapping->path) < 0) {
2868 if (errno == ENOTEMPTY) {
2869 deferred++;
2870 continue;
2871 } else
2872 return -5;
2873 }
2874
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;
2884 }
2885 remove_direntries(s, first_dir_index,
2886 next_dir_index - first_dir_index);
2887
2888 deleted++;
2889 }
2890 } else {
2891 if (unlink(mapping->path))
2892 return -4;
2893 deleted++;
2894 }
2895 DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry));
2896 remove_mapping(s, i);
2897 }
2898 }
de167e41 2899 }
a046433a
FB
2900
2901 return 0;
2902}
2903
2904/*
2905 * synchronize mapping with new state:
2906 *
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
2911 */
2912static int do_commit(BDRVVVFATState* s)
2913{
2914 int ret = 0;
2915
2916 /* the real meat are the commits. Nothing to do? Move along! */
2917 if (s->commits.next == 0)
d6a7e54e 2918 return 0;
a046433a
FB
2919
2920 vvfat_close_current_file(s);
2921
2922 ret = handle_renames_and_mkdirs(s);
2923 if (ret) {
d6a7e54e 2924 fprintf(stderr, "Error handling renames (%d)\n", ret);
43dc2a64 2925 abort();
d6a7e54e 2926 return ret;
a046433a
FB
2927 }
2928
5fafdf24 2929 /* copy FAT (with bdrv_read) */
a046433a
FB
2930 memcpy(s->fat.pointer, s->fat2, 0x200 * s->sectors_per_fat);
2931
2932 /* recurse direntries from root (using bs->bdrv_read) */
2933 ret = commit_direntries(s, 0, -1);
2934 if (ret) {
d6a7e54e 2935 fprintf(stderr, "Fatal: error while committing (%d)\n", ret);
43dc2a64 2936 abort();
d6a7e54e 2937 return ret;
a046433a
FB
2938 }
2939
2940 ret = handle_commits(s);
2941 if (ret) {
d6a7e54e 2942 fprintf(stderr, "Error handling commits (%d)\n", ret);
43dc2a64 2943 abort();
d6a7e54e 2944 return ret;
a046433a
FB
2945 }
2946
2947 ret = handle_deletes(s);
2948 if (ret) {
d6a7e54e 2949 fprintf(stderr, "Error deleting\n");
43dc2a64 2950 abort();
d6a7e54e 2951 return ret;
a046433a
FB
2952 }
2953
eecc7747
KW
2954 if (s->qcow->bs->drv->bdrv_make_empty) {
2955 s->qcow->bs->drv->bdrv_make_empty(s->qcow->bs);
7704df98 2956 }
a046433a
FB
2957
2958 memset(s->used_clusters, 0, sector2cluster(s, s->sector_count));
2959
2960DLOG(checkpoint());
2961 return 0;
2962}
2963
2964static int try_commit(BDRVVVFATState* s)
2965{
2966 vvfat_close_current_file(s);
2967DLOG(checkpoint());
2968 if(!is_consistent(s))
d6a7e54e 2969 return -1;
a046433a
FB
2970 return do_commit(s);
2971}
2972
5fafdf24 2973static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
a046433a
FB
2974 const uint8_t *buf, int nb_sectors)
2975{
5fafdf24 2976 BDRVVVFATState *s = bs->opaque;
a046433a
FB
2977 int i, ret;
2978
2979DLOG(checkpoint());
2980
ac48e389
KW
2981 /* Check if we're operating in read-only mode */
2982 if (s->qcow == NULL) {
2983 return -EACCES;
2984 }
2985
a046433a
FB
2986 vvfat_close_current_file(s);
2987
2988 /*
2989 * Some sanity checks:
2990 * - do not allow writing to the boot sector
a046433a
FB
2991 */
2992
4dc705dc 2993 if (sector_num < s->offset_to_fat)
d6a7e54e 2994 return -1;
a046433a
FB
2995
2996 for (i = sector2cluster(s, sector_num);
d6a7e54e
HP
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;
3004 }
3005
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;
3012
3013 lfn_init(&lfn);
3014
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));
3022
3023 for (k = 0; k < (end - begin) * 0x10; k++) {
d6a7e54e 3024 /* no access to the direntry of a read-only file */
e03da26b 3025 if (is_short_name(direntries + k) &&
d6a7e54e
HP
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;
3032 }
3033 }
3034 }
3035 }
3036 i = mapping->end;
3037 } else
3038 i++;
a046433a
FB
3039 }
3040
3041 /*
3042 * Use qcow backend. Commit later.
3043 */
3044DLOG(fprintf(stderr, "Write to qcow backend: %d + %d\n", (int)sector_num, nb_sectors));
18d51c4b 3045 ret = bdrv_write(s->qcow, sector_num, buf, nb_sectors);
a046433a 3046 if (ret < 0) {
d6a7e54e
HP
3047 fprintf(stderr, "Error writing to qcow backend\n");
3048 return ret;
a046433a
FB
3049 }
3050
3051 for (i = sector2cluster(s, sector_num);
d6a7e54e
HP
3052 i <= sector2cluster(s, sector_num + nb_sectors - 1); i++)
3053 if (i >= 0)
3054 s->used_clusters[i] |= USED_ALLOCATED;
a046433a
FB
3055
3056DLOG(checkpoint());
3057 /* TODO: add timeout */
3058 try_commit(s);
3059
3060DLOG(checkpoint());
3061 return 0;
3062}
3063
4575eb49
KW
3064static int coroutine_fn
3065vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3066 QEMUIOVector *qiov, int flags)
e183ef75
PB
3067{
3068 int ret;
3069 BDRVVVFATState *s = bs->opaque;
4575eb49
KW
3070 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
3071 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3072 void *buf;
3073
3074 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3075 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
3076
3077 buf = g_try_malloc(bytes);
3078 if (bytes && buf == NULL) {
3079 return -ENOMEM;
3080 }
3081 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3082
e183ef75
PB
3083 qemu_co_mutex_lock(&s->lock);
3084 ret = vvfat_write(bs, sector_num, buf, nb_sectors);
3085 qemu_co_mutex_unlock(&s->lock);
4575eb49
KW
3086
3087 g_free(buf);
3088
e183ef75
PB
3089 return ret;
3090}
3091
b6b8a333 3092static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,
d6a7e54e 3093 int64_t sector_num, int nb_sectors, int *n, BlockDriverState **file)
a046433a 3094{
139921aa 3095 *n = bs->total_sectors - sector_num;
4bc74be9
PB
3096 if (*n > nb_sectors) {
3097 *n = nb_sectors;
3098 } else if (*n < 0) {
3099 return 0;
3100 }
3101 return BDRV_BLOCK_DATA;
a046433a
FB
3102}
3103
4575eb49
KW
3104static int coroutine_fn
3105write_target_commit(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3106 QEMUIOVector *qiov, int flags)
3107{
254aee4d
PB
3108 int ret;
3109
9217e26f 3110 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
254aee4d
PB
3111 qemu_co_mutex_lock(&s->lock);
3112 ret = try_commit(s);
3113 qemu_co_mutex_unlock(&s->lock);
3114
3115 return ret;
a046433a
FB
3116}
3117
3118static void write_target_close(BlockDriverState *bs) {
9217e26f 3119 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
eecc7747 3120 bdrv_unref_child(s->bs, s->qcow);
ce137829 3121 g_free(s->qcow_filename);
a046433a
FB
3122}
3123
3124static BlockDriver vvfat_write_target = {
f9e96436 3125 .format_name = "vvfat_write_target",
a8a4d15c 3126 .instance_size = sizeof(void*),
4575eb49 3127 .bdrv_co_pwritev = write_target_commit,
f9e96436 3128 .bdrv_close = write_target_close,
a046433a
FB
3129};
3130
eecc7747
KW
3131static void vvfat_qcow_options(int *child_flags, QDict *child_options,
3132 int parent_flags, QDict *parent_options)
a046433a 3133{
f87a0e29
AG
3134 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "off");
3135 *child_flags = BDRV_O_NO_FLUSH;
eecc7747
KW
3136}
3137
3138static const BdrvChildRole child_vvfat_qcow = {
3139 .inherit_options = vvfat_qcow_options,
3140};
3141
3142static int enable_write_target(BlockDriverState *bs, Error **errp)
3143{
3144 BDRVVVFATState *s = bs->opaque;
facdbb02 3145 BlockDriver *bdrv_qcow = NULL;
5db15a57 3146 BlockDriverState *backing;
facdbb02 3147 QemuOpts *opts = NULL;
a655211a 3148 int ret;
a046433a 3149 int size = sector2cluster(s, s->sector_count);
e6641719
HR
3150 QDict *options;
3151
a046433a
FB
3152 s->used_clusters = calloc(size, 1);
3153
c227f099 3154 array_init(&(s->commits), sizeof(commit_t));
a046433a 3155
9a29e18f
JC
3156 s->qcow_filename = g_malloc(PATH_MAX);
3157 ret = get_tmp_filename(s->qcow_filename, PATH_MAX);
eba25057 3158 if (ret < 0) {
68c70af1 3159 error_setg_errno(errp, -ret, "can't create temporary file");
78f27bd0 3160 goto err;
eba25057 3161 }
91a073a9
KW
3162
3163 bdrv_qcow = bdrv_find_format("qcow");
1bcb15cf
HR
3164 if (!bdrv_qcow) {
3165 error_setg(errp, "Failed to locate qcow driver");
3166 ret = -ENOENT;
3167 goto err;
3168 }
3169
c282e1fd 3170 opts = qemu_opts_create(bdrv_qcow->create_opts, NULL, 0, &error_abort);
39101f25
MA
3171 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s->sector_count * 512,
3172 &error_abort);
f43e47db 3173 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, "fat:", &error_abort);
91a073a9 3174
c282e1fd 3175 ret = bdrv_create(bdrv_qcow, s->qcow_filename, opts, errp);
facdbb02 3176 qemu_opts_del(opts);
78f27bd0
FZ
3177 if (ret < 0) {
3178 goto err;
3179 }
a655211a 3180
e6641719 3181 options = qdict_new();
46f5ac20 3182 qdict_put_str(options, "write-target.driver", "qcow");
eecc7747
KW
3183 s->qcow = bdrv_open_child(s->qcow_filename, options, "write-target", bs,
3184 &child_vvfat_qcow, false, errp);
c4b48bfd 3185 QDECREF(options);
5b363937
HR
3186 if (!s->qcow) {
3187 ret = -EINVAL;
78f27bd0 3188 goto err;
d6e9098e 3189 }
a046433a
FB
3190
3191#ifndef _WIN32
3192 unlink(s->qcow_filename);
3193#endif
3194
a8a4d15c
KW
3195 backing = bdrv_new_open_driver(&vvfat_write_target, NULL, BDRV_O_ALLOW_RDWR,
3196 &error_abort);
3197 *(void**) backing->opaque = s;
3198
12fa4af6 3199 bdrv_set_backing_hd(s->bs, backing, &error_abort);
5db15a57
KW
3200 bdrv_unref(backing);
3201
de167e41 3202 return 0;
78f27bd0
FZ
3203
3204err:
3205 g_free(s->qcow_filename);
3206 s->qcow_filename = NULL;
3207 return ret;
de167e41
FB
3208}
3209
91ef3825
KW
3210static 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)
3214{
3215 BDRVVVFATState *s = bs->opaque;
3216
3217 assert(c == s->qcow || role == &child_backing);
3218
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;
3228 }
3229}
3230
de167e41
FB
3231static void vvfat_close(BlockDriverState *bs)
3232{
3233 BDRVVVFATState *s = bs->opaque;
3234
3235 vvfat_close_current_file(s);
3236 array_free(&(s->fat));
3237 array_free(&(s->directory));
3238 array_free(&(s->mapping));
ce137829 3239 g_free(s->cluster_buffer);
3397f0cb
KW
3240
3241 if (s->qcow) {
3242 migrate_del_blocker(s->migration_blocker);
3243 error_free(s->migration_blocker);
3244 }
de167e41
FB
3245}
3246
5efa9d5a 3247static BlockDriver bdrv_vvfat = {
7ad9be64
KW
3248 .format_name = "vvfat",
3249 .protocol_name = "fat",
3250 .instance_size = sizeof(BDRVVVFATState),
3251
3252 .bdrv_parse_filename = vvfat_parse_filename,
3253 .bdrv_file_open = vvfat_open,
a6506481 3254 .bdrv_refresh_limits = vvfat_refresh_limits,
7ad9be64 3255 .bdrv_close = vvfat_close,
91ef3825 3256 .bdrv_child_perm = vvfat_child_perm,
7ad9be64 3257
4575eb49
KW
3258 .bdrv_co_preadv = vvfat_co_preadv,
3259 .bdrv_co_pwritev = vvfat_co_pwritev,
b6b8a333 3260 .bdrv_co_get_block_status = vvfat_co_get_block_status,
de167e41
FB
3261};
3262
5efa9d5a
AL
3263static void bdrv_vvfat_init(void)
3264{
3265 bdrv_register(&bdrv_vvfat);
3266}
3267
3268block_init(bdrv_vvfat_init);
3269
a046433a 3270#ifdef DEBUG
3f47aa8c 3271static void checkpoint(void) {
c227f099 3272 assert(((mapping_t*)array_get(&(vvv->mapping), 0))->end == 2);
a046433a
FB
3273 check1(vvv);
3274 check2(vvv);
3275 assert(!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode & MODE_DIRECTORY));
3276#if 0
c227f099 3277 if (((direntry_t*)vvv->directory.pointer)[1].attributes != 0xf)
d6a7e54e 3278 fprintf(stderr, "Nonono!\n");
c227f099
AL
3279 mapping_t* mapping;
3280 direntry_t* direntry;
a046433a
FB
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)
d6a7e54e 3284 return;
a046433a
FB
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
a046433a
FB
3290}
3291#endif