]> git.proxmox.com Git - mirror_qemu.git/blame - block/vvfat.c
vvfat: fix field names in FAT12/FAT16 and FAT32 boot sectors
[mirror_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
FB
73
74/* dynamic array functions */
c227f099 75typedef struct array_t {
de167e41
FB
76 char* pointer;
77 unsigned int size,next,item_size;
c227f099 78} array_t;
de167e41 79
c227f099 80static inline void array_init(array_t* array,unsigned int item_size)
de167e41 81{
511d2b14 82 array->pointer = NULL;
de167e41
FB
83 array->size=0;
84 array->next=0;
85 array->item_size=item_size;
86}
87
c227f099 88static inline void array_free(array_t* array)
de167e41 89{
ce137829 90 g_free(array->pointer);
de167e41
FB
91 array->size=array->next=0;
92}
93
a046433a 94/* does not automatically grow */
c227f099 95static inline void* array_get(array_t* array,unsigned int index) {
a046433a
FB
96 assert(index < array->next);
97 return array->pointer + index * array->item_size;
98}
99
c227f099 100static inline int array_ensure_allocated(array_t* array, int index)
a046433a
FB
101{
102 if((index + 1) * array->item_size > array->size) {
d6a7e54e
HP
103 int new_size = (index + 32) * array->item_size;
104 array->pointer = g_realloc(array->pointer, new_size);
105 if (!array->pointer)
106 return -1;
107 array->size = new_size;
108 array->next = index + 1;
de167e41 109 }
a046433a
FB
110
111 return 0;
de167e41
FB
112}
113
c227f099 114static inline void* array_get_next(array_t* array) {
a046433a 115 unsigned int next = array->next;
a046433a
FB
116
117 if (array_ensure_allocated(array, next) < 0)
d6a7e54e 118 return NULL;
a046433a
FB
119
120 array->next = next + 1;
9be38598 121 return array_get(array, next);
de167e41
FB
122}
123
c227f099 124static inline void* array_insert(array_t* array,unsigned int index,unsigned int count) {
de167e41 125 if((array->next+count)*array->item_size>array->size) {
d6a7e54e
HP
126 int increment=count*array->item_size;
127 array->pointer=g_realloc(array->pointer,array->size+increment);
128 if(!array->pointer)
511d2b14 129 return NULL;
d6a7e54e 130 array->size+=increment;
de167e41
FB
131 }
132 memmove(array->pointer+(index+count)*array->item_size,
d6a7e54e
HP
133 array->pointer+index*array->item_size,
134 (array->next-index)*array->item_size);
de167e41
FB
135 array->next+=count;
136 return array->pointer+index*array->item_size;
137}
138
139/* this performs a "roll", so that the element which was at index_from becomes
140 * index_to, but the order of all other elements is preserved. */
c227f099 141static inline int array_roll(array_t* array,int index_to,int index_from,int count)
de167e41
FB
142{
143 char* buf;
144 char* from;
145 char* to;
146 int is;
147
148 if(!array ||
d6a7e54e
HP
149 index_to<0 || index_to>=array->next ||
150 index_from<0 || index_from>=array->next)
151 return -1;
3b46e624 152
de167e41 153 if(index_to==index_from)
d6a7e54e 154 return 0;
de167e41
FB
155
156 is=array->item_size;
157 from=array->pointer+index_from*is;
158 to=array->pointer+index_to*is;
7267c094 159 buf=g_malloc(is*count);
de167e41
FB
160 memcpy(buf,from,is*count);
161
162 if(index_to<index_from)
d6a7e54e 163 memmove(to+is*count,to,from-to);
de167e41 164 else
d6a7e54e 165 memmove(from,from+is*count,to-from);
3b46e624 166
de167e41
FB
167 memcpy(to,buf,is*count);
168
ce137829 169 g_free(buf);
de167e41
FB
170
171 return 0;
172}
173
c227f099 174static inline int array_remove_slice(array_t* array,int index, int count)
de167e41 175{
a046433a
FB
176 assert(index >=0);
177 assert(count > 0);
178 assert(index + count <= array->next);
179 if(array_roll(array,array->next-1,index,count))
d6a7e54e 180 return -1;
a046433a 181 array->next -= count;
de167e41
FB
182 return 0;
183}
184
c227f099 185static int array_remove(array_t* array,int index)
a046433a
FB
186{
187 return array_remove_slice(array, index, 1);
188}
189
190/* return the index for a given member */
c227f099 191static int array_index(array_t* array, void* pointer)
a046433a
FB
192{
193 size_t offset = (char*)pointer - array->pointer;
a046433a
FB
194 assert((offset % array->item_size) == 0);
195 assert(offset/array->item_size < array->next);
196 return offset/array->item_size;
197}
198
de167e41 199/* These structures are used to fake a disk and the VFAT filesystem.
541dc0d4 200 * For this reason we need to use QEMU_PACKED. */
de167e41 201
c227f099 202typedef struct bootsector_t {
de167e41
FB
203 uint8_t jump[3];
204 uint8_t name[8];
205 uint16_t sector_size;
206 uint8_t sectors_per_cluster;
207 uint16_t reserved_sectors;
208 uint8_t number_of_fats;
209 uint16_t root_entries;
a046433a 210 uint16_t total_sectors16;
de167e41
FB
211 uint8_t media_type;
212 uint16_t sectors_per_fat;
213 uint16_t sectors_per_track;
214 uint16_t number_of_heads;
215 uint32_t hidden_sectors;
216 uint32_t total_sectors;
217 union {
218 struct {
d6a7e54e 219 uint8_t drive_number;
92e28d82 220 uint8_t reserved1;
d6a7e54e
HP
221 uint8_t signature;
222 uint32_t id;
223 uint8_t volume_label[11];
92e28d82
HP
224 uint8_t fat_type[8];
225 uint8_t ignored[0x1c0];
d6a7e54e
HP
226 } QEMU_PACKED fat16;
227 struct {
228 uint32_t sectors_per_fat;
229 uint16_t flags;
230 uint8_t major,minor;
92e28d82 231 uint32_t first_cluster_of_root_dir;
d6a7e54e
HP
232 uint16_t info_sector;
233 uint16_t backup_boot_sector;
92e28d82
HP
234 uint8_t reserved[12];
235 uint8_t drive_number;
236 uint8_t reserved1;
237 uint8_t signature;
238 uint32_t id;
239 uint8_t volume_label[11];
240 uint8_t fat_type[8];
241 uint8_t ignored[0x1a4];
d6a7e54e 242 } QEMU_PACKED fat32;
de167e41 243 } u;
de167e41 244 uint8_t magic[2];
541dc0d4 245} QEMU_PACKED bootsector_t;
de167e41 246
b570094d
TS
247typedef struct {
248 uint8_t head;
249 uint8_t sector;
250 uint8_t cylinder;
c227f099 251} mbr_chs_t;
b570094d 252
c227f099 253typedef struct partition_t {
de167e41 254 uint8_t attributes; /* 0x80 = bootable */
c227f099 255 mbr_chs_t start_CHS;
b570094d 256 uint8_t fs_type; /* 0x1 = FAT12, 0x6 = FAT16, 0xe = FAT16_LBA, 0xb = FAT32, 0xc = FAT32_LBA */
c227f099 257 mbr_chs_t end_CHS;
de167e41 258 uint32_t start_sector_long;
b570094d 259 uint32_t length_sector_long;
541dc0d4 260} QEMU_PACKED partition_t;
de167e41 261
c227f099 262typedef struct mbr_t {
b570094d
TS
263 uint8_t ignored[0x1b8];
264 uint32_t nt_id;
265 uint8_t ignored2[2];
c227f099 266 partition_t partition[4];
de167e41 267 uint8_t magic[2];
541dc0d4 268} QEMU_PACKED mbr_t;
de167e41 269
c227f099 270typedef struct direntry_t {
f671d173 271 uint8_t name[8 + 3];
de167e41
FB
272 uint8_t attributes;
273 uint8_t reserved[2];
274 uint16_t ctime;
275 uint16_t cdate;
276 uint16_t adate;
277 uint16_t begin_hi;
278 uint16_t mtime;
279 uint16_t mdate;
280 uint16_t begin;
281 uint32_t size;
541dc0d4 282} QEMU_PACKED direntry_t;
de167e41
FB
283
284/* this structure are used to transparently access the files */
285
c227f099 286typedef struct mapping_t {
a046433a
FB
287 /* begin is the first cluster, end is the last+1 */
288 uint32_t begin,end;
de167e41
FB
289 /* as s->directory is growable, no pointer may be used here */
290 unsigned int dir_index;
a046433a
FB
291 /* the clusters of a file may be in any order; this points to the first */
292 int first_mapping_index;
293 union {
d6a7e54e
HP
294 /* offset is
295 * - the offset in the file (in clusters) for a file, or
ad05b318 296 * - the next cluster of the directory for a directory
d6a7e54e
HP
297 */
298 struct {
299 uint32_t offset;
300 } file;
301 struct {
302 int parent_mapping_index;
303 int first_dir_index;
304 } dir;
a046433a
FB
305 } info;
306 /* path contains the full path, i.e. it always starts with s->path */
307 char* path;
308
ad05b318
HP
309 enum {
310 MODE_UNDEFINED = 0,
311 MODE_NORMAL = 1,
312 MODE_MODIFIED = 2,
313 MODE_DIRECTORY = 4,
314 MODE_DELETED = 8,
315 } mode;
a046433a 316 int read_only;
c227f099 317} mapping_t;
de167e41 318
a046433a 319#ifdef DEBUG
c227f099
AL
320static void print_direntry(const struct direntry_t*);
321static void print_mapping(const struct mapping_t* mapping);
a046433a 322#endif
de167e41
FB
323
324/* here begins the real VVFAT driver */
325
326typedef struct BDRVVVFATState {
848c66e8 327 CoMutex lock;
a046433a 328 BlockDriverState* bs; /* pointer to parent */
de167e41 329 unsigned char first_sectors[0x40*0x200];
3b46e624 330
de167e41 331 int fat_type; /* 16 or 32 */
c227f099 332 array_t fat,directory,mapping;
d5941dda 333 char volume_label[11];
3b46e624 334
4dc705dc
HP
335 uint32_t offset_to_bootsector; /* 0 for floppy, 0x3f for disk */
336
de167e41
FB
337 unsigned int cluster_size;
338 unsigned int sectors_per_cluster;
339 unsigned int sectors_per_fat;
340 unsigned int sectors_of_root_directory;
a046433a 341 uint32_t last_cluster_of_root_directory;
de167e41
FB
342 uint32_t sector_count; /* total number of sectors of the partition */
343 uint32_t cluster_count; /* total number of clusters of this partition */
de167e41 344 uint32_t max_fat_value;
4dc705dc
HP
345 uint32_t offset_to_fat;
346 uint32_t offset_to_root_dir;
3b46e624 347
de167e41 348 int current_fd;
c227f099 349 mapping_t* current_mapping;
a046433a
FB
350 unsigned char* cluster; /* points to current cluster */
351 unsigned char* cluster_buffer; /* points to a buffer to hold temp data */
de167e41
FB
352 unsigned int current_cluster;
353
354 /* write support */
a046433a 355 char* qcow_filename;
eecc7747 356 BdrvChild* qcow;
a046433a
FB
357 void* fat2;
358 char* used_clusters;
c227f099 359 array_t commits;
a046433a
FB
360 const char* path;
361 int downcase_short_names;
3397f0cb
KW
362
363 Error *migration_blocker;
de167e41
FB
364} BDRVVVFATState;
365
b570094d
TS
366/* take the sector position spos and convert it to Cylinder/Head/Sector position
367 * if the position is outside the specified geometry, fill maximum value for CHS
368 * and return 1 to signal overflow.
369 */
4480e0f9
MA
370static int sector2CHS(mbr_chs_t *chs, int spos, int cyls, int heads, int secs)
371{
b570094d 372 int head,sector;
4480e0f9
MA
373 sector = spos % secs; spos /= secs;
374 head = spos % heads; spos /= heads;
375 if (spos >= cyls) {
b570094d
TS
376 /* Overflow,
377 it happens if 32bit sector positions are used, while CHS is only 24bit.
378 Windows/Dos is said to take 1023/255/63 as nonrepresentable CHS */
379 chs->head = 0xFF;
380 chs->sector = 0xFF;
381 chs->cylinder = 0xFF;
382 return 1;
383 }
384 chs->head = (uint8_t)head;
385 chs->sector = (uint8_t)( (sector+1) | ((spos>>8)<<6) );
386 chs->cylinder = (uint8_t)spos;
387 return 0;
388}
de167e41 389
4480e0f9 390static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)
de167e41
FB
391{
392 /* TODO: if the files mbr.img and bootsect.img exist, use them */
c227f099
AL
393 mbr_t* real_mbr=(mbr_t*)s->first_sectors;
394 partition_t* partition = &(real_mbr->partition[0]);
b570094d 395 int lba;
de167e41
FB
396
397 memset(s->first_sectors,0,512);
3b46e624 398
b570094d
TS
399 /* Win NT Disk Signature */
400 real_mbr->nt_id= cpu_to_le32(0xbe1afdfa);
401
de167e41 402 partition->attributes=0x80; /* bootable */
b570094d
TS
403
404 /* LBA is used when partition is outside the CHS geometry */
4dc705dc 405 lba = sector2CHS(&partition->start_CHS, s->offset_to_bootsector,
4480e0f9
MA
406 cyls, heads, secs);
407 lba |= sector2CHS(&partition->end_CHS, s->bs->total_sectors - 1,
408 cyls, heads, secs);
b570094d
TS
409
410 /*LBA partitions are identified only by start/length_sector_long not by CHS*/
4dc705dc 411 partition->start_sector_long = cpu_to_le32(s->offset_to_bootsector);
f91cbefe 412 partition->length_sector_long = cpu_to_le32(s->bs->total_sectors
4dc705dc 413 - s->offset_to_bootsector);
b570094d 414
a046433a 415 /* FAT12/FAT16/FAT32 */
b570094d
TS
416 /* DOS uses different types when partition is LBA,
417 probably to prevent older versions from using CHS on them */
5f5b29df
HP
418 partition->fs_type = s->fat_type == 12 ? 0x1 :
419 s->fat_type == 16 ? (lba ? 0xe : 0x06) :
420 /*s->fat_type == 32*/ (lba ? 0xc : 0x0b);
de167e41
FB
421
422 real_mbr->magic[0]=0x55; real_mbr->magic[1]=0xaa;
423}
424
a046433a
FB
425/* direntry functions */
426
de167e41 427/* dest is assumed to hold 258 bytes, and pads with 0xffff up to next multiple of 26 */
60fe76f3 428static inline int short2long_name(char* dest,const char* src)
de167e41
FB
429{
430 int i;
1e080d5d 431 int len;
de167e41
FB
432 for(i=0;i<129 && src[i];i++) {
433 dest[2*i]=src[i];
d6a7e54e 434 dest[2*i+1]=0;
de167e41 435 }
1e080d5d 436 len=2*i;
de167e41
FB
437 dest[2*i]=dest[2*i+1]=0;
438 for(i=2*i+2;(i%26);i++)
d6a7e54e 439 dest[i]=0xff;
1e080d5d 440 return len;
de167e41
FB
441}
442
c227f099 443static inline direntry_t* create_long_filename(BDRVVVFATState* s,const char* filename)
de167e41
FB
444{
445 char buffer[258];
446 int length=short2long_name(buffer,filename),
447 number_of_entries=(length+25)/26,i;
c227f099 448 direntry_t* entry;
de167e41
FB
449
450 for(i=0;i<number_of_entries;i++) {
d6a7e54e
HP
451 entry=array_get_next(&(s->directory));
452 entry->attributes=0xf;
453 entry->reserved[0]=0;
454 entry->begin=0;
455 entry->name[0]=(number_of_entries-i)|(i==0?0x40:0);
de167e41 456 }
1e080d5d 457 for(i=0;i<26*number_of_entries;i++) {
d6a7e54e
HP
458 int offset=(i%26);
459 if(offset<10) offset=1+offset;
460 else if(offset<22) offset=14+offset-10;
461 else offset=28+offset-22;
462 entry=array_get(&(s->directory),s->directory.next-1-(i/26));
463 entry->name[offset]=buffer[i];
de167e41
FB
464 }
465 return array_get(&(s->directory),s->directory.next-number_of_entries);
466}
467
c227f099 468static char is_free(const direntry_t* direntry)
a046433a 469{
ad1a897e 470 return direntry->name[0]==0xe5 || direntry->name[0]==0x00;
a046433a
FB
471}
472
c227f099 473static char is_volume_label(const direntry_t* direntry)
a046433a
FB
474{
475 return direntry->attributes == 0x28;
476}
477
c227f099 478static char is_long_name(const direntry_t* direntry)
a046433a
FB
479{
480 return direntry->attributes == 0xf;
481}
482
c227f099 483static char is_short_name(const direntry_t* direntry)
a046433a
FB
484{
485 return !is_volume_label(direntry) && !is_long_name(direntry)
d6a7e54e 486 && !is_free(direntry);
a046433a
FB
487}
488
c227f099 489static char is_directory(const direntry_t* direntry)
a046433a
FB
490{
491 return direntry->attributes & 0x10 && direntry->name[0] != 0xe5;
492}
493
c227f099 494static inline char is_dot(const direntry_t* direntry)
a046433a
FB
495{
496 return is_short_name(direntry) && direntry->name[0] == '.';
497}
498
c227f099 499static char is_file(const direntry_t* direntry)
a046433a
FB
500{
501 return is_short_name(direntry) && !is_directory(direntry);
502}
503
c227f099 504static inline uint32_t begin_of_direntry(const direntry_t* direntry)
a046433a
FB
505{
506 return le16_to_cpu(direntry->begin)|(le16_to_cpu(direntry->begin_hi)<<16);
507}
508
c227f099 509static inline uint32_t filesize_of_direntry(const direntry_t* direntry)
a046433a
FB
510{
511 return le32_to_cpu(direntry->size);
512}
513
c227f099 514static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin)
a046433a
FB
515{
516 direntry->begin = cpu_to_le16(begin & 0xffff);
517 direntry->begin_hi = cpu_to_le16((begin >> 16) & 0xffff);
518}
519
de167e41
FB
520/* fat functions */
521
c227f099 522static inline uint8_t fat_chksum(const direntry_t* entry)
de167e41
FB
523{
524 uint8_t chksum=0;
525 int i;
526
f671d173
SW
527 for (i = 0; i < ARRAY_SIZE(entry->name); i++) {
528 chksum = (((chksum & 0xfe) >> 1) |
529 ((chksum & 0x01) ? 0x80 : 0)) + entry->name[i];
5606c220 530 }
3b46e624 531
de167e41
FB
532 return chksum;
533}
534
535/* if return_time==0, this returns the fat_date, else the fat_time */
536static uint16_t fat_datetime(time_t time,int return_time) {
537 struct tm* t;
de167e41 538 struct tm t1;
6ab00cee 539 t = &t1;
de167e41 540 localtime_r(&time,t);
de167e41 541 if(return_time)
d6a7e54e 542 return cpu_to_le16((t->tm_sec/2)|(t->tm_min<<5)|(t->tm_hour<<11));
de167e41
FB
543 return cpu_to_le16((t->tm_mday)|((t->tm_mon+1)<<5)|((t->tm_year-80)<<9));
544}
545
546static inline void fat_set(BDRVVVFATState* s,unsigned int cluster,uint32_t value)
547{
a046433a 548 if(s->fat_type==32) {
d6a7e54e
HP
549 uint32_t* entry=array_get(&(s->fat),cluster);
550 *entry=cpu_to_le32(value);
de167e41 551 } else if(s->fat_type==16) {
d6a7e54e
HP
552 uint16_t* entry=array_get(&(s->fat),cluster);
553 *entry=cpu_to_le16(value&0xffff);
de167e41 554 } else {
d6a7e54e
HP
555 int offset = (cluster*3/2);
556 unsigned char* p = array_get(&(s->fat), offset);
a046433a 557 switch (cluster&1) {
d6a7e54e
HP
558 case 0:
559 p[0] = value&0xff;
560 p[1] = (p[1]&0xf0) | ((value>>8)&0xf);
561 break;
562 case 1:
563 p[0] = (p[0]&0xf) | ((value&0xf)<<4);
564 p[1] = (value>>4);
565 break;
566 }
de167e41
FB
567 }
568}
569
570static inline uint32_t fat_get(BDRVVVFATState* s,unsigned int cluster)
571{
a046433a 572 if(s->fat_type==32) {
d6a7e54e
HP
573 uint32_t* entry=array_get(&(s->fat),cluster);
574 return le32_to_cpu(*entry);
de167e41 575 } else if(s->fat_type==16) {
d6a7e54e
HP
576 uint16_t* entry=array_get(&(s->fat),cluster);
577 return le16_to_cpu(*entry);
de167e41 578 } else {
d6a7e54e
HP
579 const uint8_t* x=(uint8_t*)(s->fat.pointer)+cluster*3/2;
580 return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
de167e41
FB
581 }
582}
583
584static inline int fat_eof(BDRVVVFATState* s,uint32_t fat_entry)
585{
586 if(fat_entry>s->max_fat_value-8)
d6a7e54e 587 return -1;
de167e41
FB
588 return 0;
589}
590
591static inline void init_fat(BDRVVVFATState* s)
592{
a046433a 593 if (s->fat_type == 12) {
d6a7e54e
HP
594 array_init(&(s->fat),1);
595 array_ensure_allocated(&(s->fat),
596 s->sectors_per_fat * 0x200 * 3 / 2 - 1);
a046433a 597 } else {
d6a7e54e
HP
598 array_init(&(s->fat),(s->fat_type==32?4:2));
599 array_ensure_allocated(&(s->fat),
600 s->sectors_per_fat * 0x200 / s->fat.item_size - 1);
a046433a 601 }
de167e41 602 memset(s->fat.pointer,0,s->fat.size);
3b46e624 603
de167e41 604 switch(s->fat_type) {
d6a7e54e
HP
605 case 12: s->max_fat_value=0xfff; break;
606 case 16: s->max_fat_value=0xffff; break;
607 case 32: s->max_fat_value=0x0fffffff; break;
608 default: s->max_fat_value=0; /* error... */
de167e41
FB
609 }
610
611}
612
a046433a
FB
613/* TODO: in create_short_filename, 0xe5->0x05 is not yet handled! */
614/* TODO: in parse_short_filename, 0x05->0xe5 is not yet handled! */
c227f099 615static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,
d6a7e54e 616 unsigned int directory_start, const char* filename, int is_dot)
de167e41 617{
a046433a 618 int i,j,long_index=s->directory.next;
c227f099
AL
619 direntry_t* entry = NULL;
620 direntry_t* entry_long = NULL;
de167e41
FB
621
622 if(is_dot) {
d6a7e54e 623 entry=array_get_next(&(s->directory));
f671d173 624 memset(entry->name, 0x20, sizeof(entry->name));
d6a7e54e
HP
625 memcpy(entry->name,filename,strlen(filename));
626 return entry;
de167e41 627 }
3b46e624 628
de167e41 629 entry_long=create_long_filename(s,filename);
3b46e624 630
5fafdf24 631 i = strlen(filename);
a046433a
FB
632 for(j = i - 1; j>0 && filename[j]!='.';j--);
633 if (j > 0)
d6a7e54e 634 i = (j > 8 ? 8 : j);
a046433a 635 else if (i > 8)
d6a7e54e 636 i = 8;
a046433a 637
de167e41 638 entry=array_get_next(&(s->directory));
f671d173 639 memset(entry->name, 0x20, sizeof(entry->name));
51a0f568 640 memcpy(entry->name, filename, i);
3b46e624 641
f671d173
SW
642 if (j > 0) {
643 for (i = 0; i < 3 && filename[j + 1 + i]; i++) {
644 entry->name[8 + i] = filename[j + 1 + i];
645 }
646 }
de167e41
FB
647
648 /* upcase & remove unwanted characters */
649 for(i=10;i>=0;i--) {
d6a7e54e
HP
650 if(i==10 || i==7) for(;i>0 && entry->name[i]==' ';i--);
651 if(entry->name[i]<=' ' || entry->name[i]>0x7f
652 || strchr(".*?<>|\":/\\[];,+='",entry->name[i]))
653 entry->name[i]='_';
de167e41
FB
654 else if(entry->name[i]>='a' && entry->name[i]<='z')
655 entry->name[i]+='A'-'a';
656 }
657
658 /* mangle duplicates */
659 while(1) {
d6a7e54e
HP
660 direntry_t* entry1=array_get(&(s->directory),directory_start);
661 int j;
662
663 for(;entry1<entry;entry1++)
664 if(!is_long_name(entry1) && !memcmp(entry1->name,entry->name,11))
665 break; /* found dupe */
666 if(entry1==entry) /* no dupe found */
667 break;
668
669 /* use all 8 characters of name */
670 if(entry->name[7]==' ') {
671 int j;
672 for(j=6;j>0 && entry->name[j]==' ';j--)
673 entry->name[j]='~';
674 }
675
676 /* increment number */
677 for(j=7;j>0 && entry->name[j]=='9';j--)
678 entry->name[j]='0';
679 if(j>0) {
680 if(entry->name[j]<'0' || entry->name[j]>'9')
681 entry->name[j]='0';
682 else
683 entry->name[j]++;
684 }
de167e41
FB
685 }
686
687 /* calculate checksum; propagate to long name */
688 if(entry_long) {
689 uint8_t chksum=fat_chksum(entry);
690
d6a7e54e
HP
691 /* calculate anew, because realloc could have taken place */
692 entry_long=array_get(&(s->directory),long_index);
693 while(entry_long<entry && is_long_name(entry_long)) {
694 entry_long->reserved[1]=chksum;
695 entry_long++;
696 }
de167e41
FB
697 }
698
699 return entry;
700}
701
a046433a
FB
702/*
703 * Read a directory. (the index of the corresponding mapping must be passed).
704 */
705static int read_directory(BDRVVVFATState* s, int mapping_index)
de167e41 706{
c227f099
AL
707 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
708 direntry_t* direntry;
a046433a
FB
709 const char* dirname = mapping->path;
710 int first_cluster = mapping->begin;
711 int parent_index = mapping->info.dir.parent_mapping_index;
c227f099 712 mapping_t* parent_mapping = (mapping_t*)
511d2b14 713 (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);
a046433a 714 int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;
de167e41
FB
715
716 DIR* dir=opendir(dirname);
717 struct dirent* entry;
de167e41
FB
718 int i;
719
a046433a
FB
720 assert(mapping->mode & MODE_DIRECTORY);
721
722 if(!dir) {
d6a7e54e
HP
723 mapping->end = mapping->begin;
724 return -1;
a046433a 725 }
3b46e624 726
a046433a 727 i = mapping->info.dir.first_dir_index =
d6a7e54e 728 first_cluster == 0 ? 0 : s->directory.next;
a046433a 729
5fafdf24 730 /* actually read the directory, and allocate the mappings */
de167e41 731 while((entry=readdir(dir))) {
d6a7e54e 732 unsigned int length=strlen(dirname)+2+strlen(entry->d_name);
de167e41 733 char* buffer;
d6a7e54e 734 direntry_t* direntry;
a046433a 735 struct stat st;
d6a7e54e
HP
736 int is_dot=!strcmp(entry->d_name,".");
737 int is_dotdot=!strcmp(entry->d_name,"..");
de167e41 738
d6a7e54e
HP
739 if(first_cluster == 0 && (is_dotdot || is_dot))
740 continue;
5fafdf24 741
d6a7e54e
HP
742 buffer = g_malloc(length);
743 snprintf(buffer,length,"%s/%s",dirname,entry->d_name);
de167e41 744
d6a7e54e 745 if(stat(buffer,&st)<0) {
ce137829 746 g_free(buffer);
de167e41 747 continue;
d6a7e54e
HP
748 }
749
750 /* create directory entry for this file */
751 direntry=create_short_and_long_name(s, i, entry->d_name,
752 is_dot || is_dotdot);
753 direntry->attributes=(S_ISDIR(st.st_mode)?0x10:0x20);
754 direntry->reserved[0]=direntry->reserved[1]=0;
755 direntry->ctime=fat_datetime(st.st_ctime,1);
756 direntry->cdate=fat_datetime(st.st_ctime,0);
757 direntry->adate=fat_datetime(st.st_atime,0);
758 direntry->begin_hi=0;
759 direntry->mtime=fat_datetime(st.st_mtime,1);
760 direntry->mdate=fat_datetime(st.st_mtime,0);
761 if(is_dotdot)
762 set_begin_of_direntry(direntry, first_cluster_of_parent);
763 else if(is_dot)
764 set_begin_of_direntry(direntry, first_cluster);
765 else
766 direntry->begin=0; /* do that later */
a046433a 767 if (st.st_size > 0x7fffffff) {
d6a7e54e 768 fprintf(stderr, "File %s is larger than 2GB\n", buffer);
ce137829 769 g_free(buffer);
08089edc 770 closedir(dir);
d6a7e54e 771 return -2;
a046433a 772 }
d6a7e54e
HP
773 direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);
774
775 /* create mapping for this file */
776 if(!is_dot && !is_dotdot && (S_ISDIR(st.st_mode) || st.st_size)) {
777 s->current_mapping = array_get_next(&(s->mapping));
778 s->current_mapping->begin=0;
779 s->current_mapping->end=st.st_size;
780 /*
781 * we get the direntry of the most recent direntry, which
782 * contains the short name and all the relevant information.
783 */
784 s->current_mapping->dir_index=s->directory.next-1;
785 s->current_mapping->first_mapping_index = -1;
786 if (S_ISDIR(st.st_mode)) {
787 s->current_mapping->mode = MODE_DIRECTORY;
788 s->current_mapping->info.dir.parent_mapping_index =
789 mapping_index;
790 } else {
791 s->current_mapping->mode = MODE_UNDEFINED;
792 s->current_mapping->info.file.offset = 0;
793 }
794 s->current_mapping->path=buffer;
795 s->current_mapping->read_only =
796 (st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0;
b122c3b6
MA
797 } else {
798 g_free(buffer);
799 }
de167e41
FB
800 }
801 closedir(dir);
802
803 /* fill with zeroes up to the end of the cluster */
804 while(s->directory.next%(0x10*s->sectors_per_cluster)) {
d6a7e54e
HP
805 direntry_t* direntry=array_get_next(&(s->directory));
806 memset(direntry,0,sizeof(direntry_t));
de167e41
FB
807 }
808
a046433a
FB
809/* TODO: if there are more entries, bootsector has to be adjusted! */
810#define ROOT_ENTRIES (0x02 * 0x10 * s->sectors_per_cluster)
811 if (mapping_index == 0 && s->directory.next < ROOT_ENTRIES) {
d6a7e54e
HP
812 /* root directory */
813 int cur = s->directory.next;
814 array_ensure_allocated(&(s->directory), ROOT_ENTRIES - 1);
815 s->directory.next = ROOT_ENTRIES;
816 memset(array_get(&(s->directory), cur), 0,
817 (ROOT_ENTRIES - cur) * sizeof(direntry_t));
de167e41 818 }
5fafdf24 819
5f5b29df 820 /* re-get the mapping, since s->mapping was possibly realloc()ed */
d4df3dbc 821 mapping = array_get(&(s->mapping), mapping_index);
a046433a 822 first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)
d6a7e54e 823 * 0x20 / s->cluster_size;
a046433a
FB
824 mapping->end = first_cluster;
825
d4df3dbc 826 direntry = array_get(&(s->directory), mapping->dir_index);
a046433a 827 set_begin_of_direntry(direntry, mapping->begin);
3b46e624 828
a046433a
FB
829 return 0;
830}
de167e41 831
a046433a
FB
832static inline uint32_t sector2cluster(BDRVVVFATState* s,off_t sector_num)
833{
4dc705dc 834 return (sector_num - s->offset_to_root_dir) / s->sectors_per_cluster;
a046433a 835}
de167e41 836
a046433a
FB
837static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
838{
4dc705dc 839 return s->offset_to_root_dir + s->sectors_per_cluster * cluster_num;
a046433a 840}
de167e41 841
a046433a 842static int init_directories(BDRVVVFATState* s,
d11c8917
MA
843 const char *dirname, int heads, int secs,
844 Error **errp)
de167e41 845{
c227f099
AL
846 bootsector_t* bootsector;
847 mapping_t* mapping;
de167e41
FB
848 unsigned int i;
849 unsigned int cluster;
850
851 memset(&(s->first_sectors[0]),0,0x40*0x200);
852
de167e41 853 s->cluster_size=s->sectors_per_cluster*0x200;
7267c094 854 s->cluster_buffer=g_malloc(s->cluster_size);
a046433a
FB
855
856 /*
857 * The formula: sc = spf+1+spf*spc*(512*8/fat_type),
858 * where sc is sector_count,
859 * spf is sectors_per_fat,
860 * spc is sectors_per_clusters, and
861 * fat_type = 12, 16 or 32.
862 */
863 i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;
864 s->sectors_per_fat=(s->sector_count+i)/i; /* round up */
3b46e624 865
4dc705dc
HP
866 s->offset_to_fat = s->offset_to_bootsector + 1;
867 s->offset_to_root_dir = s->offset_to_fat + s->sectors_per_fat * 2;
868
c227f099
AL
869 array_init(&(s->mapping),sizeof(mapping_t));
870 array_init(&(s->directory),sizeof(direntry_t));
de167e41
FB
871
872 /* add volume label */
873 {
d6a7e54e
HP
874 direntry_t* entry=array_get_next(&(s->directory));
875 entry->attributes=0x28; /* archive | volume label */
d5941dda 876 memcpy(entry->name, s->volume_label, sizeof(entry->name));
de167e41
FB
877 }
878
de167e41
FB
879 /* Now build FAT, and write back information into directory */
880 init_fat(s);
881
a046433a
FB
882 s->cluster_count=sector2cluster(s, s->sector_count);
883
884 mapping = array_get_next(&(s->mapping));
885 mapping->begin = 0;
886 mapping->dir_index = 0;
887 mapping->info.dir.parent_mapping_index = -1;
888 mapping->first_mapping_index = -1;
7267c094 889 mapping->path = g_strdup(dirname);
a046433a
FB
890 i = strlen(mapping->path);
891 if (i > 0 && mapping->path[i - 1] == '/')
d6a7e54e 892 mapping->path[i - 1] = '\0';
a046433a
FB
893 mapping->mode = MODE_DIRECTORY;
894 mapping->read_only = 0;
895 s->path = mapping->path;
896
897 for (i = 0, cluster = 0; i < s->mapping.next; i++) {
d6a7e54e
HP
898 /* MS-DOS expects the FAT to be 0 for the root directory
899 * (except for the media byte). */
900 /* LATER TODO: still true for FAT32? */
901 int fix_fat = (i != 0);
902 mapping = array_get(&(s->mapping), i);
a046433a
FB
903
904 if (mapping->mode & MODE_DIRECTORY) {
d6a7e54e
HP
905 mapping->begin = cluster;
906 if(read_directory(s, i)) {
d11c8917
MA
907 error_setg(errp, "Could not read directory %s",
908 mapping->path);
d6a7e54e
HP
909 return -1;
910 }
911 mapping = array_get(&(s->mapping), i);
912 } else {
913 assert(mapping->mode == MODE_UNDEFINED);
914 mapping->mode=MODE_NORMAL;
915 mapping->begin = cluster;
916 if (mapping->end > 0) {
917 direntry_t* direntry = array_get(&(s->directory),
918 mapping->dir_index);
919
920 mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;
921 set_begin_of_direntry(direntry, mapping->begin);
922 } else {
923 mapping->end = cluster + 1;
924 fix_fat = 0;
925 }
926 }
927
928 assert(mapping->begin < mapping->end);
929
930 /* next free cluster */
931 cluster = mapping->end;
932
933 if(cluster > s->cluster_count) {
d11c8917
MA
934 error_setg(errp,
935 "Directory does not fit in FAT%d (capacity %.2f MB)",
936 s->fat_type, s->sector_count / 2000.0);
937 return -1;
d6a7e54e 938 }
8ce0f869 939
d6a7e54e
HP
940 /* fix fat for entry */
941 if (fix_fat) {
942 int j;
943 for(j = mapping->begin; j < mapping->end - 1; j++)
944 fat_set(s, j, j+1);
945 fat_set(s, mapping->end - 1, s->max_fat_value);
946 }
de167e41
FB
947 }
948
a046433a
FB
949 mapping = array_get(&(s->mapping), 0);
950 s->sectors_of_root_directory = mapping->end * s->sectors_per_cluster;
951 s->last_cluster_of_root_directory = mapping->end;
952
953 /* the FAT signature */
954 fat_set(s,0,s->max_fat_value);
955 fat_set(s,1,s->max_fat_value);
de167e41 956
a046433a
FB
957 s->current_mapping = NULL;
958
4dc705dc
HP
959 bootsector = (bootsector_t *)(s->first_sectors
960 + s->offset_to_bootsector * 0x200);
de167e41
FB
961 bootsector->jump[0]=0xeb;
962 bootsector->jump[1]=0x3e;
963 bootsector->jump[2]=0x90;
964 memcpy(bootsector->name,"QEMU ",8);
965 bootsector->sector_size=cpu_to_le16(0x200);
966 bootsector->sectors_per_cluster=s->sectors_per_cluster;
967 bootsector->reserved_sectors=cpu_to_le16(1);
968 bootsector->number_of_fats=0x2; /* number of FATs */
969 bootsector->root_entries=cpu_to_le16(s->sectors_of_root_directory*0x10);
a046433a 970 bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
4dc705dc
HP
971 /* media descriptor: hard disk=0xf8, floppy=0xf0 */
972 bootsector->media_type = (s->offset_to_bootsector > 0 ? 0xf8 : 0xf0);
a046433a 973 s->fat.pointer[0] = bootsector->media_type;
de167e41 974 bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
4480e0f9
MA
975 bootsector->sectors_per_track = cpu_to_le16(secs);
976 bootsector->number_of_heads = cpu_to_le16(heads);
4dc705dc 977 bootsector->hidden_sectors = cpu_to_le32(s->offset_to_bootsector);
a046433a 978 bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
de167e41 979
a046433a 980 /* LATER TODO: if FAT32, this is wrong */
4dc705dc
HP
981 /* drive_number: fda=0, hda=0x80 */
982 bootsector->u.fat16.drive_number = s->offset_to_bootsector == 0 ? 0 : 0x80;
de167e41
FB
983 bootsector->u.fat16.signature=0x29;
984 bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);
985
d5941dda
WB
986 memcpy(bootsector->u.fat16.volume_label, s->volume_label,
987 sizeof(bootsector->u.fat16.volume_label));
92e28d82
HP
988 memcpy(bootsector->u.fat16.fat_type,
989 s->fat_type == 12 ? "FAT12 " : "FAT16 ", 8);
de167e41
FB
990 bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;
991
992 return 0;
993}
994
83f64091 995#ifdef DEBUG
a046433a 996static BDRVVVFATState *vvv = NULL;
83f64091 997#endif
a046433a 998
eecc7747 999static int enable_write_target(BlockDriverState *bs, Error **errp);
a046433a
FB
1000static int is_consistent(BDRVVVFATState *s);
1001
7ad9be64
KW
1002static QemuOptsList runtime_opts = {
1003 .name = "vvfat",
1004 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1005 .desc = {
1006 {
1007 .name = "dir",
1008 .type = QEMU_OPT_STRING,
1009 .help = "Host directory to map to the vvfat device",
1010 },
1011 {
1012 .name = "fat-type",
1013 .type = QEMU_OPT_NUMBER,
1014 .help = "FAT type (12, 16 or 32)",
1015 },
1016 {
1017 .name = "floppy",
1018 .type = QEMU_OPT_BOOL,
1019 .help = "Create a floppy rather than a hard disk image",
1020 },
d5941dda
WB
1021 {
1022 .name = "label",
1023 .type = QEMU_OPT_STRING,
1024 .help = "Use a volume label other than QEMU VVFAT",
1025 },
7ad9be64
KW
1026 {
1027 .name = "rw",
1028 .type = QEMU_OPT_BOOL,
1029 .help = "Make the image writable",
1030 },
1031 { /* end of list */ }
1032 },
1033};
1034
1035static void vvfat_parse_filename(const char *filename, QDict *options,
1036 Error **errp)
1037{
1038 int fat_type = 0;
1039 bool floppy = false;
1040 bool rw = false;
1041 int i;
1042
1043 if (!strstart(filename, "fat:", NULL)) {
1044 error_setg(errp, "File name string must start with 'fat:'");
1045 return;
1046 }
1047
1048 /* Parse options */
1049 if (strstr(filename, ":32:")) {
1050 fat_type = 32;
1051 } else if (strstr(filename, ":16:")) {
1052 fat_type = 16;
1053 } else if (strstr(filename, ":12:")) {
1054 fat_type = 12;
1055 }
1056
1057 if (strstr(filename, ":floppy:")) {
1058 floppy = true;
1059 }
1060
1061 if (strstr(filename, ":rw:")) {
1062 rw = true;
1063 }
1064
1065 /* Get the directory name without options */
1066 i = strrchr(filename, ':') - filename;
1067 assert(i >= 3);
1068 if (filename[i - 2] == ':' && qemu_isalpha(filename[i - 1])) {
1069 /* workaround for DOS drive names */
1070 filename += i - 1;
1071 } else {
1072 filename += i + 1;
1073 }
1074
1075 /* Fill in the options QDict */
46f5ac20
EB
1076 qdict_put_str(options, "dir", filename);
1077 qdict_put_int(options, "fat-type", fat_type);
1078 qdict_put_bool(options, "floppy", floppy);
1079 qdict_put_bool(options, "rw", rw);
7ad9be64
KW
1080}
1081
015a1036
HR
1082static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
1083 Error **errp)
de167e41
FB
1084{
1085 BDRVVVFATState *s = bs->opaque;
7ad9be64
KW
1086 int cyls, heads, secs;
1087 bool floppy;
d5941dda 1088 const char *dirname, *label;
7ad9be64
KW
1089 QemuOpts *opts;
1090 Error *local_err = NULL;
1091 int ret;
de167e41 1092
83f64091 1093#ifdef DEBUG
a046433a 1094 vvv = s;
83f64091 1095#endif
a046433a 1096
87ea75d5 1097 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
7ad9be64 1098 qemu_opts_absorb_qdict(opts, options, &local_err);
84d18f06 1099 if (local_err) {
c0f92b52 1100 error_propagate(errp, local_err);
7ad9be64
KW
1101 ret = -EINVAL;
1102 goto fail;
1103 }
1104
1105 dirname = qemu_opt_get(opts, "dir");
1106 if (!dirname) {
c0f92b52 1107 error_setg(errp, "vvfat block driver requires a 'dir' option");
7ad9be64
KW
1108 ret = -EINVAL;
1109 goto fail;
1110 }
1111
1112 s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
1113 floppy = qemu_opt_get_bool(opts, "floppy", false);
1114
d5941dda
WB
1115 memset(s->volume_label, ' ', sizeof(s->volume_label));
1116 label = qemu_opt_get(opts, "label");
1117 if (label) {
1118 size_t label_length = strlen(label);
1119 if (label_length > 11) {
1120 error_setg(errp, "vvfat label cannot be longer than 11 bytes");
1121 ret = -EINVAL;
1122 goto fail;
1123 }
1124 memcpy(s->volume_label, label, label_length);
d208c50d
KW
1125 } else {
1126 memcpy(s->volume_label, "QEMU VVFAT", 10);
d5941dda
WB
1127 }
1128
7ad9be64
KW
1129 if (floppy) {
1130 /* 1.44MB or 2.88MB floppy. 2.88MB can be FAT12 (default) or FAT16. */
1131 if (!s->fat_type) {
1132 s->fat_type = 12;
1133 secs = 36;
1134 s->sectors_per_cluster = 2;
1135 } else {
1136 secs = s->fat_type == 12 ? 18 : 36;
1137 s->sectors_per_cluster = 1;
1138 }
7ad9be64
KW
1139 cyls = 80;
1140 heads = 2;
1141 } else {
1142 /* 32MB or 504MB disk*/
1143 if (!s->fat_type) {
1144 s->fat_type = 16;
1145 }
4dc705dc 1146 s->offset_to_bootsector = 0x3f;
7ad9be64
KW
1147 cyls = s->fat_type == 12 ? 64 : 1024;
1148 heads = 16;
1149 secs = 63;
1150 }
1151
1152 switch (s->fat_type) {
1153 case 32:
d6a7e54e 1154 fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "
7ad9be64
KW
1155 "You are welcome to do so!\n");
1156 break;
1157 case 16:
1158 case 12:
1159 break;
1160 default:
c0f92b52 1161 error_setg(errp, "Valid FAT types are only 12, 16 and 32");
7ad9be64
KW
1162 ret = -EINVAL;
1163 goto fail;
1164 }
1165
1166
a046433a
FB
1167 s->bs = bs;
1168
a046433a 1169 /* LATER TODO: if FAT32, adjust */
a046433a 1170 s->sectors_per_cluster=0x10;
de167e41
FB
1171
1172 s->current_cluster=0xffffffff;
de167e41 1173
eecc7747 1174 s->qcow = NULL;
a046433a
FB
1175 s->qcow_filename = NULL;
1176 s->fat2 = NULL;
1177 s->downcase_short_names = 1;
3b46e624 1178
4480e0f9
MA
1179 fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
1180 dirname, cyls, heads, secs);
a046433a 1181
4dc705dc 1182 s->sector_count = cyls * heads * secs - s->offset_to_bootsector;
5a742b55 1183
7ad9be64 1184 if (qemu_opt_get_bool(opts, "rw", false)) {
e2b8247a
JC
1185 if (!bdrv_is_read_only(bs)) {
1186 ret = enable_write_target(bs, errp);
1187 if (ret < 0) {
1188 goto fail;
1189 }
1190 } else {
1191 ret = -EPERM;
1192 error_setg(errp,
1193 "Unable to set VVFAT to 'rw' when drive is read-only");
1194 goto fail;
1195 }
1196 } else {
1197 /* read only is the default for safety */
1198 ret = bdrv_set_read_only(bs, true, &local_err);
78f27bd0 1199 if (ret < 0) {
e2b8247a 1200 error_propagate(errp, local_err);
7ad9be64
KW
1201 goto fail;
1202 }
b570094d
TS
1203 }
1204
4480e0f9 1205 bs->total_sectors = cyls * heads * secs;
b570094d 1206
d11c8917 1207 if (init_directories(s, dirname, heads, secs, errp)) {
7ad9be64
KW
1208 ret = -EIO;
1209 goto fail;
4480e0f9 1210 }
de167e41 1211
4dc705dc
HP
1212 s->sector_count = s->offset_to_root_dir
1213 + s->sectors_per_cluster * s->cluster_count;
b570094d 1214
3397f0cb
KW
1215 /* Disable migration when vvfat is used rw */
1216 if (s->qcow) {
81e5f78a
AG
1217 error_setg(&s->migration_blocker,
1218 "The vvfat (rw) format used by node '%s' "
1219 "does not support live migration",
1220 bdrv_get_device_or_node_name(bs));
fe44dc91
AA
1221 ret = migrate_add_blocker(s->migration_blocker, &local_err);
1222 if (local_err) {
1223 error_propagate(errp, local_err);
1224 error_free(s->migration_blocker);
1225 goto fail;
1226 }
3397f0cb
KW
1227 }
1228
4dc705dc 1229 if (s->offset_to_bootsector > 0) {
fe44dc91
AA
1230 init_mbr(s, cyls, heads, secs);
1231 }
1232
1233 qemu_co_mutex_init(&s->lock);
1234
7ad9be64
KW
1235 ret = 0;
1236fail:
1237 qemu_opts_del(opts);
1238 return ret;
de167e41
FB
1239}
1240
a6506481
EB
1241static void vvfat_refresh_limits(BlockDriverState *bs, Error **errp)
1242{
a5b8dd2c 1243 bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
a6506481
EB
1244}
1245
de167e41
FB
1246static inline void vvfat_close_current_file(BDRVVVFATState *s)
1247{
1248 if(s->current_mapping) {
d6a7e54e
HP
1249 s->current_mapping = NULL;
1250 if (s->current_fd) {
1251 qemu_close(s->current_fd);
1252 s->current_fd = 0;
1253 }
de167e41 1254 }
a046433a 1255 s->current_cluster = -1;
de167e41
FB
1256}
1257
1258/* mappings between index1 and index2-1 are supposed to be ordered
1259 * return value is the index of the last mapping for which end>cluster_num
1260 */
1261static inline int find_mapping_for_cluster_aux(BDRVVVFATState* s,int cluster_num,int index1,int index2)
1262{
de167e41 1263 while(1) {
88bf7950 1264 int index3;
d6a7e54e
HP
1265 mapping_t* mapping;
1266 index3=(index1+index2)/2;
1267 mapping=array_get(&(s->mapping),index3);
1268 assert(mapping->begin < mapping->end);
1269 if(mapping->begin>=cluster_num) {
1270 assert(index2!=index3 || index2==0);
1271 if(index2==index3)
1272 return index1;
1273 index2=index3;
1274 } else {
1275 if(index1==index3)
1276 return mapping->end<=cluster_num ? index2 : index1;
1277 index1=index3;
1278 }
1279 assert(index1<=index2);
1280 DLOG(mapping=array_get(&(s->mapping),index1);
1281 assert(mapping->begin<=cluster_num);
1282 assert(index2 >= s->mapping.next ||
1283 ((mapping = array_get(&(s->mapping),index2)) &&
1284 mapping->end>cluster_num)));
de167e41
FB
1285 }
1286}
1287
c227f099 1288static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_num)
de167e41
FB
1289{
1290 int index=find_mapping_for_cluster_aux(s,cluster_num,0,s->mapping.next);
c227f099 1291 mapping_t* mapping;
de167e41 1292 if(index>=s->mapping.next)
511d2b14 1293 return NULL;
de167e41
FB
1294 mapping=array_get(&(s->mapping),index);
1295 if(mapping->begin>cluster_num)
511d2b14 1296 return NULL;
a046433a 1297 assert(mapping->begin<=cluster_num && mapping->end>cluster_num);
de167e41
FB
1298 return mapping;
1299}
1300
c227f099 1301static int open_file(BDRVVVFATState* s,mapping_t* mapping)
de167e41
FB
1302{
1303 if(!mapping)
d6a7e54e 1304 return -1;
de167e41 1305 if(!s->current_mapping ||
d6a7e54e
HP
1306 strcmp(s->current_mapping->path,mapping->path)) {
1307 /* open file */
1308 int fd = qemu_open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
1309 if(fd<0)
1310 return -1;
1311 vvfat_close_current_file(s);
1312 s->current_fd = fd;
1313 s->current_mapping = mapping;
de167e41
FB
1314 }
1315 return 0;
1316}
1317
1318static inline int read_cluster(BDRVVVFATState *s,int cluster_num)
1319{
1320 if(s->current_cluster != cluster_num) {
d6a7e54e
HP
1321 int result=0;
1322 off_t offset;
1323 assert(!s->current_mapping || s->current_fd || (s->current_mapping->mode & MODE_DIRECTORY));
1324 if(!s->current_mapping
1325 || s->current_mapping->begin>cluster_num
1326 || s->current_mapping->end<=cluster_num) {
1327 /* binary search of mappings for file */
1328 mapping_t* mapping=find_mapping_for_cluster(s,cluster_num);
1329
1330 assert(!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end));
1331
1332 if (mapping && mapping->mode & MODE_DIRECTORY) {
1333 vvfat_close_current_file(s);
1334 s->current_mapping = mapping;
a046433a 1335read_cluster_directory:
d6a7e54e
HP
1336 offset = s->cluster_size*(cluster_num-s->current_mapping->begin);
1337 s->cluster = (unsigned char*)s->directory.pointer+offset
1338 + 0x20*s->current_mapping->info.dir.first_dir_index;
1339 assert(((s->cluster-(unsigned char*)s->directory.pointer)%s->cluster_size)==0);
1340 assert((char*)s->cluster+s->cluster_size <= s->directory.pointer+s->directory.next*s->directory.item_size);
1341 s->current_cluster = cluster_num;
1342 return 0;
1343 }
1344
1345 if(open_file(s,mapping))
1346 return -2;
1347 } else if (s->current_mapping->mode & MODE_DIRECTORY)
1348 goto read_cluster_directory;
1349
1350 assert(s->current_fd);
1351
1352 offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset;
1353 if(lseek(s->current_fd, offset, SEEK_SET)!=offset)
1354 return -3;
1355 s->cluster=s->cluster_buffer;
1356 result=read(s->current_fd,s->cluster,s->cluster_size);
1357 if(result<0) {
1358 s->current_cluster = -1;
1359 return -1;
1360 }
1361 s->current_cluster = cluster_num;
de167e41
FB
1362 }
1363 return 0;
1364}
1365
a046433a 1366#ifdef DEBUG
c227f099 1367static void print_direntry(const direntry_t* direntry)
de167e41 1368{
a046433a
FB
1369 int j = 0;
1370 char buffer[1024];
1371
3e89cb04 1372 fprintf(stderr, "direntry %p: ", direntry);
de167e41 1373 if(!direntry)
d6a7e54e 1374 return;
a046433a 1375 if(is_long_name(direntry)) {
d6a7e54e
HP
1376 unsigned char* c=(unsigned char*)direntry;
1377 int i;
1378 for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)
3891b370 1379#define ADD_CHAR(c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;}
d6a7e54e
HP
1380 ADD_CHAR(c[i]);
1381 for(i=14;i<26 && c[i] && c[i]!=0xff;i+=2)
1382 ADD_CHAR(c[i]);
1383 for(i=28;i<32 && c[i] && c[i]!=0xff;i+=2)
1384 ADD_CHAR(c[i]);
1385 buffer[j] = 0;
1386 fprintf(stderr, "%s\n", buffer);
de167e41 1387 } else {
d6a7e54e
HP
1388 int i;
1389 for(i=0;i<11;i++)
1390 ADD_CHAR(direntry->name[i]);
1391 buffer[j] = 0;
1392 fprintf(stderr,"%s attributes=0x%02x begin=%d size=%d\n",
1393 buffer,
1394 direntry->attributes,
1395 begin_of_direntry(direntry),le32_to_cpu(direntry->size));
de167e41
FB
1396 }
1397}
1398
c227f099 1399static void print_mapping(const mapping_t* mapping)
de167e41 1400{
3e89cb04
KW
1401 fprintf(stderr, "mapping (%p): begin, end = %d, %d, dir_index = %d, "
1402 "first_mapping_index = %d, name = %s, mode = 0x%x, " ,
1403 mapping, mapping->begin, mapping->end, mapping->dir_index,
1404 mapping->first_mapping_index, mapping->path, mapping->mode);
1405
a046433a 1406 if (mapping->mode & MODE_DIRECTORY)
d6a7e54e 1407 fprintf(stderr, "parent_mapping_index = %d, first_dir_index = %d\n", mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);
a046433a 1408 else
d6a7e54e 1409 fprintf(stderr, "offset = %d\n", mapping->info.file.offset);
de167e41 1410}
a046433a 1411#endif
de167e41 1412
5fafdf24 1413static int vvfat_read(BlockDriverState *bs, int64_t sector_num,
a046433a 1414 uint8_t *buf, int nb_sectors)
de167e41 1415{
a046433a 1416 BDRVVVFATState *s = bs->opaque;
de167e41 1417 int i;
de167e41 1418
a046433a 1419 for(i=0;i<nb_sectors;i++,sector_num++) {
d6a7e54e
HP
1420 if (sector_num >= bs->total_sectors)
1421 return -1;
1422 if (s->qcow) {
1423 int n;
6f712ee0
EB
1424 int ret;
1425 ret = bdrv_is_allocated(s->qcow->bs, sector_num,
1426 nb_sectors - i, &n);
1427 if (ret < 0) {
1428 return ret;
1429 }
1430 if (ret) {
eecc7747
KW
1431 DLOG(fprintf(stderr, "sectors %d+%d allocated\n",
1432 (int)sector_num, n));
fbcbbf4e 1433 if (bdrv_read(s->qcow, sector_num, buf + i * 0x200, n)) {
7704df98
KW
1434 return -1;
1435 }
1436 i += n - 1;
1437 sector_num += n - 1;
1438 continue;
1439 }
a046433a 1440DLOG(fprintf(stderr, "sector %d not allocated\n", (int)sector_num));
d6a7e54e 1441 }
4dc705dc
HP
1442 if (sector_num < s->offset_to_root_dir) {
1443 if (sector_num < s->offset_to_fat) {
1444 memcpy(buf + i * 0x200,
1445 &(s->first_sectors[sector_num * 0x200]),
1446 0x200);
1447 } else if (sector_num < s->offset_to_fat + s->sectors_per_fat) {
1448 memcpy(buf + i * 0x200,
1449 &(s->fat.pointer[(sector_num
1450 - s->offset_to_fat) * 0x200]),
1451 0x200);
1452 } else if (sector_num < s->offset_to_root_dir) {
1453 memcpy(buf + i * 0x200,
1454 &(s->fat.pointer[(sector_num - s->offset_to_fat
1455 - s->sectors_per_fat) * 0x200]),
1456 0x200);
1457 }
d6a7e54e 1458 } else {
4dc705dc 1459 uint32_t sector = sector_num - s->offset_to_root_dir,
d6a7e54e
HP
1460 sector_offset_in_cluster=(sector%s->sectors_per_cluster),
1461 cluster_num=sector/s->sectors_per_cluster;
1462 if(cluster_num > s->cluster_count || read_cluster(s, cluster_num) != 0) {
1463 /* LATER TODO: strict: return -1; */
1464 memset(buf+i*0x200,0,0x200);
1465 continue;
1466 }
1467 memcpy(buf+i*0x200,s->cluster+sector_offset_in_cluster*0x200,0x200);
1468 }
de167e41 1469 }
de167e41
FB
1470 return 0;
1471}
1472
4575eb49
KW
1473static int coroutine_fn
1474vvfat_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1475 QEMUIOVector *qiov, int flags)
2914caa0
PB
1476{
1477 int ret;
1478 BDRVVVFATState *s = bs->opaque;
4575eb49
KW
1479 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
1480 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1481 void *buf;
1482
1483 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1484 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1485
1486 buf = g_try_malloc(bytes);
1487 if (bytes && buf == NULL) {
1488 return -ENOMEM;
1489 }
1490
2914caa0
PB
1491 qemu_co_mutex_lock(&s->lock);
1492 ret = vvfat_read(bs, sector_num, buf, nb_sectors);
1493 qemu_co_mutex_unlock(&s->lock);
4575eb49
KW
1494
1495 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1496 g_free(buf);
1497
2914caa0
PB
1498 return ret;
1499}
1500
a046433a 1501/* LATER TODO: statify all functions */
de167e41 1502
a046433a
FB
1503/*
1504 * Idea of the write support (use snapshot):
de167e41 1505 *
a046433a
FB
1506 * 1. check if all data is consistent, recording renames, modifications,
1507 * new files and directories (in s->commits).
de167e41 1508 *
a046433a 1509 * 2. if the data is not consistent, stop committing
de167e41 1510 *
a046433a
FB
1511 * 3. handle renames, and create new files and directories (do not yet
1512 * write their contents)
de167e41 1513 *
a046433a
FB
1514 * 4. walk the directories, fixing the mapping and direntries, and marking
1515 * the handled mappings as not deleted
de167e41 1516 *
a046433a 1517 * 5. commit the contents of the files
de167e41 1518 *
a046433a 1519 * 6. handle deleted files and directories
de167e41
FB
1520 *
1521 */
1522
c227f099 1523typedef struct commit_t {
a046433a
FB
1524 char* path;
1525 union {
d6a7e54e
HP
1526 struct { uint32_t cluster; } rename;
1527 struct { int dir_index; uint32_t modified_offset; } writeout;
1528 struct { uint32_t first_cluster; } new_file;
1529 struct { uint32_t cluster; } mkdir;
a046433a
FB
1530 } param;
1531 /* DELETEs and RMDIRs are handled differently: see handle_deletes() */
1532 enum {
d6a7e54e 1533 ACTION_RENAME, ACTION_WRITEOUT, ACTION_NEW_FILE, ACTION_MKDIR
a046433a 1534 } action;
c227f099 1535} commit_t;
de167e41 1536
a046433a 1537static void clear_commits(BDRVVVFATState* s)
de167e41
FB
1538{
1539 int i;
a046433a
FB
1540DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));
1541 for (i = 0; i < s->commits.next; i++) {
d6a7e54e
HP
1542 commit_t* commit = array_get(&(s->commits), i);
1543 assert(commit->path || commit->action == ACTION_WRITEOUT);
1544 if (commit->action != ACTION_WRITEOUT) {
1545 assert(commit->path);
ce137829 1546 g_free(commit->path);
d6a7e54e
HP
1547 } else
1548 assert(commit->path == NULL);
de167e41 1549 }
a046433a 1550 s->commits.next = 0;
de167e41
FB
1551}
1552
a046433a 1553static void schedule_rename(BDRVVVFATState* s,
d6a7e54e 1554 uint32_t cluster, char* new_path)
de167e41 1555{
c227f099 1556 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1557 commit->path = new_path;
1558 commit->param.rename.cluster = cluster;
1559 commit->action = ACTION_RENAME;
de167e41
FB
1560}
1561
a046433a 1562static void schedule_writeout(BDRVVVFATState* s,
d6a7e54e 1563 int dir_index, uint32_t modified_offset)
de167e41 1564{
c227f099 1565 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1566 commit->path = NULL;
1567 commit->param.writeout.dir_index = dir_index;
1568 commit->param.writeout.modified_offset = modified_offset;
1569 commit->action = ACTION_WRITEOUT;
de167e41
FB
1570}
1571
a046433a 1572static void schedule_new_file(BDRVVVFATState* s,
d6a7e54e 1573 char* path, uint32_t first_cluster)
de167e41 1574{
c227f099 1575 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1576 commit->path = path;
1577 commit->param.new_file.first_cluster = first_cluster;
1578 commit->action = ACTION_NEW_FILE;
1579}
1580
1581static void schedule_mkdir(BDRVVVFATState* s, uint32_t cluster, char* path)
1582{
c227f099 1583 commit_t* commit = array_get_next(&(s->commits));
a046433a
FB
1584 commit->path = path;
1585 commit->param.mkdir.cluster = cluster;
1586 commit->action = ACTION_MKDIR;
1587}
1588
1589typedef struct {
64eaabda
TS
1590 /*
1591 * Since the sequence number is at most 0x3f, and the filename
1592 * length is at most 13 times the sequence number, the maximal
1593 * filename length is 0x3f * 13 bytes.
1594 */
1595 unsigned char name[0x3f * 13 + 1];
a046433a
FB
1596 int checksum, len;
1597 int sequence_number;
1598} long_file_name;
1599
1600static void lfn_init(long_file_name* lfn)
1601{
1602 lfn->sequence_number = lfn->len = 0;
1603 lfn->checksum = 0x100;
1604}
1605
1606/* return 0 if parsed successfully, > 0 if no long name, < 0 if error */
1607static int parse_long_name(long_file_name* lfn,
d6a7e54e 1608 const direntry_t* direntry)
a046433a
FB
1609{
1610 int i, j, offset;
1611 const unsigned char* pointer = (const unsigned char*)direntry;
1612
1613 if (!is_long_name(direntry))
d6a7e54e 1614 return 1;
a046433a
FB
1615
1616 if (pointer[0] & 0x40) {
d6a7e54e
HP
1617 lfn->sequence_number = pointer[0] & 0x3f;
1618 lfn->checksum = pointer[13];
1619 lfn->name[0] = 0;
1620 lfn->name[lfn->sequence_number * 13] = 0;
a046433a 1621 } else if ((pointer[0] & 0x3f) != --lfn->sequence_number)
d6a7e54e 1622 return -1;
a046433a 1623 else if (pointer[13] != lfn->checksum)
d6a7e54e 1624 return -2;
a046433a 1625 else if (pointer[12] || pointer[26] || pointer[27])
d6a7e54e 1626 return -3;
a046433a
FB
1627
1628 offset = 13 * (lfn->sequence_number - 1);
1629 for (i = 0, j = 1; i < 13; i++, j+=2) {
d6a7e54e
HP
1630 if (j == 11)
1631 j = 14;
1632 else if (j == 26)
1633 j = 28;
a046433a 1634
d6a7e54e
HP
1635 if (pointer[j+1] == 0)
1636 lfn->name[offset + i] = pointer[j];
1637 else if (pointer[j+1] != 0xff || (pointer[0] & 0x40) == 0)
1638 return -4;
1639 else
1640 lfn->name[offset + i] = 0;
de167e41 1641 }
a046433a
FB
1642
1643 if (pointer[0] & 0x40)
d6a7e54e 1644 lfn->len = offset + strlen((char*)lfn->name + offset);
a046433a 1645
de167e41
FB
1646 return 0;
1647}
1648
a046433a
FB
1649/* returns 0 if successful, >0 if no short_name, and <0 on error */
1650static int parse_short_name(BDRVVVFATState* s,
d6a7e54e 1651 long_file_name* lfn, direntry_t* direntry)
de167e41 1652{
a046433a 1653 int i, j;
de167e41 1654
a046433a 1655 if (!is_short_name(direntry))
d6a7e54e 1656 return 1;
a046433a
FB
1657
1658 for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);
1659 for (i = 0; i <= j; i++) {
d6a7e54e
HP
1660 if (direntry->name[i] <= ' ' || direntry->name[i] > 0x7f)
1661 return -1;
1662 else if (s->downcase_short_names)
1663 lfn->name[i] = qemu_tolower(direntry->name[i]);
1664 else
1665 lfn->name[i] = direntry->name[i];
de167e41
FB
1666 }
1667
f671d173
SW
1668 for (j = 2; j >= 0 && direntry->name[8 + j] == ' '; j--) {
1669 }
a046433a 1670 if (j >= 0) {
d6a7e54e
HP
1671 lfn->name[i++] = '.';
1672 lfn->name[i + j + 1] = '\0';
1673 for (;j >= 0; j--) {
f671d173
SW
1674 uint8_t c = direntry->name[8 + j];
1675 if (c <= ' ' || c > 0x7f) {
1676 return -2;
1677 } else if (s->downcase_short_names) {
1678 lfn->name[i + j] = qemu_tolower(c);
1679 } else {
1680 lfn->name[i + j] = c;
1681 }
d6a7e54e 1682 }
a046433a 1683 } else
d6a7e54e 1684 lfn->name[i + j + 1] = '\0';
a046433a 1685
ffe8ab83 1686 lfn->len = strlen((char*)lfn->name);
a046433a
FB
1687
1688 return 0;
de167e41
FB
1689}
1690
a046433a 1691static inline uint32_t modified_fat_get(BDRVVVFATState* s,
d6a7e54e 1692 unsigned int cluster)
de167e41 1693{
a046433a 1694 if (cluster < s->last_cluster_of_root_directory) {
d6a7e54e
HP
1695 if (cluster + 1 == s->last_cluster_of_root_directory)
1696 return s->max_fat_value;
1697 else
1698 return cluster + 1;
a046433a
FB
1699 }
1700
1701 if (s->fat_type==32) {
1702 uint32_t* entry=((uint32_t*)s->fat2)+cluster;
1703 return le32_to_cpu(*entry);
1704 } else if (s->fat_type==16) {
1705 uint16_t* entry=((uint16_t*)s->fat2)+cluster;
1706 return le16_to_cpu(*entry);
1707 } else {
1708 const uint8_t* x=s->fat2+cluster*3/2;
1709 return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
1710 }
1711}
1712
6f712ee0
EB
1713static inline bool cluster_was_modified(BDRVVVFATState *s,
1714 uint32_t cluster_num)
a046433a
FB
1715{
1716 int was_modified = 0;
1717 int i, dummy;
1718
eecc7747
KW
1719 if (s->qcow == NULL) {
1720 return 0;
1721 }
a046433a 1722
eecc7747
KW
1723 for (i = 0; !was_modified && i < s->sectors_per_cluster; i++) {
1724 was_modified = bdrv_is_allocated(s->qcow->bs,
1725 cluster2sector(s, cluster_num) + i,
1726 1, &dummy);
1727 }
a046433a 1728
6f712ee0
EB
1729 /*
1730 * Note that this treats failures to learn allocation status the
1731 * same as if an allocation has occurred. It's as safe as
1732 * anything else, given that a failure to learn allocation status
1733 * will probably result in more failures.
1734 */
1735 return !!was_modified;
de167e41
FB
1736}
1737
a046433a 1738static const char* get_basename(const char* path)
de167e41 1739{
a046433a
FB
1740 char* basename = strrchr(path, '/');
1741 if (basename == NULL)
d6a7e54e 1742 return path;
a046433a 1743 else
d6a7e54e 1744 return basename + 1; /* strip '/' */
de167e41
FB
1745}
1746
a046433a
FB
1747/*
1748 * The array s->used_clusters holds the states of the clusters. If it is
1749 * part of a file, it has bit 2 set, in case of a directory, bit 1. If it
1750 * was modified, bit 3 is set.
1751 * If any cluster is allocated, but not part of a file or directory, this
1752 * driver refuses to commit.
1753 */
1754typedef enum {
1755 USED_DIRECTORY = 1, USED_FILE = 2, USED_ANY = 3, USED_ALLOCATED = 4
c227f099 1756} used_t;
de167e41 1757
a046433a
FB
1758/*
1759 * get_cluster_count_for_direntry() not only determines how many clusters
1760 * are occupied by direntry, but also if it was renamed or modified.
1761 *
1762 * A file is thought to be renamed *only* if there already was a file with
1763 * exactly the same first cluster, but a different name.
1764 *
1765 * Further, the files/directories handled by this function are
1766 * assumed to be *not* deleted (and *only* those).
1767 */
1768static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,
d6a7e54e 1769 direntry_t* direntry, const char* path)
de167e41 1770{
a046433a
FB
1771 /*
1772 * This is a little bit tricky:
1773 * IF the guest OS just inserts a cluster into the file chain,
1774 * and leaves the rest alone, (i.e. the original file had clusters
1775 * 15 -> 16, but now has 15 -> 32 -> 16), then the following happens:
1776 *
1777 * - do_commit will write the cluster into the file at the given
1778 * offset, but
1779 *
1780 * - the cluster which is overwritten should be moved to a later
1781 * position in the file.
1782 *
1783 * I am not aware that any OS does something as braindead, but this
1784 * situation could happen anyway when not committing for a long time.
1785 * Just to be sure that this does not bite us, detect it, and copy the
1786 * contents of the clusters to-be-overwritten into the qcow.
1787 */
1788 int copy_it = 0;
1789 int was_modified = 0;
1790 int32_t ret = 0;
1791
1792 uint32_t cluster_num = begin_of_direntry(direntry);
1793 uint32_t offset = 0;
1794 int first_mapping_index = -1;
c227f099 1795 mapping_t* mapping = NULL;
a046433a 1796 const char* basename2 = NULL;
de167e41 1797
a046433a 1798 vvfat_close_current_file(s);
de167e41 1799
a046433a
FB
1800 /* the root directory */
1801 if (cluster_num == 0)
d6a7e54e 1802 return 0;
de167e41 1803
a046433a
FB
1804 /* write support */
1805 if (s->qcow) {
d6a7e54e 1806 basename2 = get_basename(path);
de167e41 1807
d6a7e54e 1808 mapping = find_mapping_for_cluster(s, cluster_num);
a046433a 1809
d6a7e54e
HP
1810 if (mapping) {
1811 const char* basename;
da2414e9 1812
d6a7e54e
HP
1813 assert(mapping->mode & MODE_DELETED);
1814 mapping->mode &= ~MODE_DELETED;
a046433a 1815
d6a7e54e 1816 basename = get_basename(mapping->path);
a046433a 1817
d6a7e54e 1818 assert(mapping->mode & MODE_NORMAL);
a046433a 1819
d6a7e54e
HP
1820 /* rename */
1821 if (strcmp(basename, basename2))
1822 schedule_rename(s, cluster_num, g_strdup(path));
1823 } else if (is_file(direntry))
1824 /* new file */
1825 schedule_new_file(s, g_strdup(path), cluster_num);
1826 else {
43dc2a64 1827 abort();
d6a7e54e
HP
1828 return 0;
1829 }
de167e41
FB
1830 }
1831
a046433a 1832 while(1) {
d6a7e54e
HP
1833 if (s->qcow) {
1834 if (!copy_it && cluster_was_modified(s, cluster_num)) {
1835 if (mapping == NULL ||
1836 mapping->begin > cluster_num ||
1837 mapping->end <= cluster_num)
1838 mapping = find_mapping_for_cluster(s, cluster_num);
de167e41 1839
a046433a 1840
d6a7e54e
HP
1841 if (mapping &&
1842 (mapping->mode & MODE_DIRECTORY) == 0) {
a046433a 1843
d6a7e54e
HP
1844 /* was modified in qcow */
1845 if (offset != mapping->info.file.offset + s->cluster_size
1846 * (cluster_num - mapping->begin)) {
1847 /* offset of this cluster in file chain has changed */
43dc2a64 1848 abort();
d6a7e54e
HP
1849 copy_it = 1;
1850 } else if (offset == 0) {
1851 const char* basename = get_basename(mapping->path);
a046433a 1852
d6a7e54e
HP
1853 if (strcmp(basename, basename2))
1854 copy_it = 1;
1855 first_mapping_index = array_index(&(s->mapping), mapping);
1856 }
a046433a 1857
d6a7e54e
HP
1858 if (mapping->first_mapping_index != first_mapping_index
1859 && mapping->info.file.offset > 0) {
43dc2a64 1860 abort();
d6a7e54e
HP
1861 copy_it = 1;
1862 }
1863
1864 /* need to write out? */
1865 if (!was_modified && is_file(direntry)) {
1866 was_modified = 1;
1867 schedule_writeout(s, mapping->dir_index, offset);
1868 }
1869 }
1870 }
1871
1872 if (copy_it) {
1873 int i, dummy;
1874 /*
1875 * This is horribly inefficient, but that is okay, since
1876 * it is rarely executed, if at all.
1877 */
1878 int64_t offset = cluster2sector(s, cluster_num);
1879
1880 vvfat_close_current_file(s);
7704df98 1881 for (i = 0; i < s->sectors_per_cluster; i++) {
eecc7747
KW
1882 int res;
1883
1884 res = bdrv_is_allocated(s->qcow->bs, offset + i, 1, &dummy);
6f712ee0
EB
1885 if (res < 0) {
1886 return -1;
1887 }
eecc7747
KW
1888 if (!res) {
1889 res = vvfat_read(s->bs, offset, s->cluster_buffer, 1);
1890 if (res) {
7704df98
KW
1891 return -1;
1892 }
18d51c4b 1893 res = bdrv_write(s->qcow, offset, s->cluster_buffer, 1);
eecc7747 1894 if (res) {
7704df98
KW
1895 return -2;
1896 }
1897 }
1898 }
d6a7e54e
HP
1899 }
1900 }
a046433a 1901
d6a7e54e
HP
1902 ret++;
1903 if (s->used_clusters[cluster_num] & USED_ANY)
1904 return 0;
1905 s->used_clusters[cluster_num] = USED_FILE;
a046433a 1906
d6a7e54e 1907 cluster_num = modified_fat_get(s, cluster_num);
a046433a 1908
d6a7e54e
HP
1909 if (fat_eof(s, cluster_num))
1910 return ret;
1911 else if (cluster_num < 2 || cluster_num > s->max_fat_value - 16)
1912 return -1;
a046433a 1913
d6a7e54e 1914 offset += s->cluster_size;
a046433a 1915 }
de167e41
FB
1916}
1917
a046433a 1918/*
5fafdf24 1919 * This function looks at the modified data (qcow).
a046433a
FB
1920 * It returns 0 upon inconsistency or error, and the number of clusters
1921 * used by the directory, its subdirectories and their files.
1922 */
1923static int check_directory_consistency(BDRVVVFATState *s,
d6a7e54e 1924 int cluster_num, const char* path)
de167e41 1925{
a046433a 1926 int ret = 0;
7267c094 1927 unsigned char* cluster = g_malloc(s->cluster_size);
c227f099
AL
1928 direntry_t* direntries = (direntry_t*)cluster;
1929 mapping_t* mapping = find_mapping_for_cluster(s, cluster_num);
a046433a
FB
1930
1931 long_file_name lfn;
1932 int path_len = strlen(path);
0d460d6f 1933 char path2[PATH_MAX + 1];
a046433a
FB
1934
1935 assert(path_len < PATH_MAX); /* len was tested before! */
363a37d5 1936 pstrcpy(path2, sizeof(path2), path);
a046433a
FB
1937 path2[path_len] = '/';
1938 path2[path_len + 1] = '\0';
1939
1940 if (mapping) {
d6a7e54e
HP
1941 const char* basename = get_basename(mapping->path);
1942 const char* basename2 = get_basename(path);
a046433a 1943
d6a7e54e 1944 assert(mapping->mode & MODE_DIRECTORY);
a046433a 1945
d6a7e54e
HP
1946 assert(mapping->mode & MODE_DELETED);
1947 mapping->mode &= ~MODE_DELETED;
a046433a 1948
d6a7e54e
HP
1949 if (strcmp(basename, basename2))
1950 schedule_rename(s, cluster_num, g_strdup(path));
a046433a 1951 } else
d6a7e54e
HP
1952 /* new directory */
1953 schedule_mkdir(s, cluster_num, g_strdup(path));
3b46e624 1954
a046433a
FB
1955 lfn_init(&lfn);
1956 do {
d6a7e54e
HP
1957 int i;
1958 int subret = 0;
a046433a 1959
d6a7e54e 1960 ret++;
a046433a 1961
d6a7e54e
HP
1962 if (s->used_clusters[cluster_num] & USED_ANY) {
1963 fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num);
6262bbd3 1964 goto fail;
d6a7e54e
HP
1965 }
1966 s->used_clusters[cluster_num] = USED_DIRECTORY;
a046433a
FB
1967
1968DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num)));
d6a7e54e
HP
1969 subret = vvfat_read(s->bs, cluster2sector(s, cluster_num), cluster,
1970 s->sectors_per_cluster);
1971 if (subret) {
1972 fprintf(stderr, "Error fetching direntries\n");
1973 fail:
ce137829 1974 g_free(cluster);
d6a7e54e
HP
1975 return 0;
1976 }
a046433a 1977
d6a7e54e
HP
1978 for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) {
1979 int cluster_count = 0;
a046433a 1980
b2bedb21 1981DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i));
d6a7e54e
HP
1982 if (is_volume_label(direntries + i) || is_dot(direntries + i) ||
1983 is_free(direntries + i))
1984 continue;
1985
1986 subret = parse_long_name(&lfn, direntries + i);
1987 if (subret < 0) {
1988 fprintf(stderr, "Error in long name\n");
1989 goto fail;
1990 }
1991 if (subret == 0 || is_free(direntries + i))
1992 continue;
1993
1994 if (fat_chksum(direntries+i) != lfn.checksum) {
1995 subret = parse_short_name(s, &lfn, direntries + i);
1996 if (subret < 0) {
1997 fprintf(stderr, "Error in short name (%d)\n", subret);
1998 goto fail;
1999 }
2000 if (subret > 0 || !strcmp((char*)lfn.name, ".")
2001 || !strcmp((char*)lfn.name, ".."))
2002 continue;
2003 }
2004 lfn.checksum = 0x100; /* cannot use long name twice */
2005
2006 if (path_len + 1 + lfn.len >= PATH_MAX) {
2007 fprintf(stderr, "Name too long: %s/%s\n", path, lfn.name);
2008 goto fail;
2009 }
363a37d5
BS
2010 pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1,
2011 (char*)lfn.name);
a046433a 2012
d6a7e54e
HP
2013 if (is_directory(direntries + i)) {
2014 if (begin_of_direntry(direntries + i) == 0) {
2015 DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i));
2016 goto fail;
2017 }
2018 cluster_count = check_directory_consistency(s,
2019 begin_of_direntry(direntries + i), path2);
2020 if (cluster_count == 0) {
2021 DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i));
2022 goto fail;
2023 }
2024 } else if (is_file(direntries + i)) {
2025 /* check file size with FAT */
2026 cluster_count = get_cluster_count_for_direntry(s, direntries + i, path2);
2027 if (cluster_count !=
13385ae1 2028 DIV_ROUND_UP(le32_to_cpu(direntries[i].size), s->cluster_size)) {
d6a7e54e
HP
2029 DLOG(fprintf(stderr, "Cluster count mismatch\n"));
2030 goto fail;
2031 }
2032 } else
43dc2a64 2033 abort(); /* cluster_count = 0; */
a046433a 2034
d6a7e54e
HP
2035 ret += cluster_count;
2036 }
de167e41 2037
d6a7e54e 2038 cluster_num = modified_fat_get(s, cluster_num);
a046433a 2039 } while(!fat_eof(s, cluster_num));
de167e41 2040
ce137829 2041 g_free(cluster);
a046433a
FB
2042 return ret;
2043}
2044
2045/* returns 1 on success */
2046static int is_consistent(BDRVVVFATState* s)
2047{
2048 int i, check;
2049 int used_clusters_count = 0;
2050
2051DLOG(checkpoint());
2052 /*
2053 * - get modified FAT
2054 * - compare the two FATs (TODO)
2055 * - get buffer for marking used clusters
2056 * - recurse direntries from root (using bs->bdrv_read to make
2057 * sure to get the new data)
2058 * - check that the FAT agrees with the size
2059 * - count the number of clusters occupied by this directory and
2060 * its files
2061 * - check that the cumulative used cluster count agrees with the
2062 * FAT
2063 * - if all is fine, return number of used clusters
2064 */
2065 if (s->fat2 == NULL) {
d6a7e54e
HP
2066 int size = 0x200 * s->sectors_per_fat;
2067 s->fat2 = g_malloc(size);
2068 memcpy(s->fat2, s->fat.pointer, size);
a046433a
FB
2069 }
2070 check = vvfat_read(s->bs,
4dc705dc 2071 s->offset_to_fat, s->fat2, s->sectors_per_fat);
a046433a 2072 if (check) {
d6a7e54e
HP
2073 fprintf(stderr, "Could not copy fat\n");
2074 return 0;
a046433a
FB
2075 }
2076 assert (s->used_clusters);
2077 for (i = 0; i < sector2cluster(s, s->sector_count); i++)
d6a7e54e 2078 s->used_clusters[i] &= ~USED_ANY;
a046433a
FB
2079
2080 clear_commits(s);
2081
2082 /* mark every mapped file/directory as deleted.
2083 * (check_directory_consistency() will unmark those still present). */
2084 if (s->qcow)
d6a7e54e
HP
2085 for (i = 0; i < s->mapping.next; i++) {
2086 mapping_t* mapping = array_get(&(s->mapping), i);
2087 if (mapping->first_mapping_index < 0)
2088 mapping->mode |= MODE_DELETED;
2089 }
a046433a
FB
2090
2091 used_clusters_count = check_directory_consistency(s, 0, s->path);
2092 if (used_clusters_count <= 0) {
d6a7e54e
HP
2093 DLOG(fprintf(stderr, "problem in directory\n"));
2094 return 0;
de167e41
FB
2095 }
2096
a046433a
FB
2097 check = s->last_cluster_of_root_directory;
2098 for (i = check; i < sector2cluster(s, s->sector_count); i++) {
d6a7e54e
HP
2099 if (modified_fat_get(s, i)) {
2100 if(!s->used_clusters[i]) {
2101 DLOG(fprintf(stderr, "FAT was modified (%d), but cluster is not used?\n", i));
2102 return 0;
2103 }
2104 check++;
2105 }
a046433a 2106
d6a7e54e
HP
2107 if (s->used_clusters[i] == USED_ALLOCATED) {
2108 /* allocated, but not used... */
2109 DLOG(fprintf(stderr, "unused, modified cluster: %d\n", i));
2110 return 0;
2111 }
a046433a
FB
2112 }
2113
2114 if (check != used_clusters_count)
d6a7e54e 2115 return 0;
a046433a
FB
2116
2117 return used_clusters_count;
2118}
2119
2120static inline void adjust_mapping_indices(BDRVVVFATState* s,
d6a7e54e 2121 int offset, int adjust)
a046433a
FB
2122{
2123 int i;
2124
2125 for (i = 0; i < s->mapping.next; i++) {
d6a7e54e 2126 mapping_t* mapping = array_get(&(s->mapping), i);
a046433a
FB
2127
2128#define ADJUST_MAPPING_INDEX(name) \
d6a7e54e
HP
2129 if (mapping->name >= offset) \
2130 mapping->name += adjust
a046433a 2131
d6a7e54e
HP
2132 ADJUST_MAPPING_INDEX(first_mapping_index);
2133 if (mapping->mode & MODE_DIRECTORY)
2134 ADJUST_MAPPING_INDEX(info.dir.parent_mapping_index);
de167e41 2135 }
a046433a
FB
2136}
2137
2138/* insert or update mapping */
c227f099 2139static mapping_t* insert_mapping(BDRVVVFATState* s,
d6a7e54e 2140 uint32_t begin, uint32_t end)
a046433a
FB
2141{
2142 /*
2143 * - find mapping where mapping->begin >= begin,
2144 * - if mapping->begin > begin: insert
2145 * - adjust all references to mappings!
2146 * - else: adjust
2147 * - replace name
2148 */
2149 int index = find_mapping_for_cluster_aux(s, begin, 0, s->mapping.next);
c227f099
AL
2150 mapping_t* mapping = NULL;
2151 mapping_t* first_mapping = array_get(&(s->mapping), 0);
a046433a
FB
2152
2153 if (index < s->mapping.next && (mapping = array_get(&(s->mapping), index))
d6a7e54e
HP
2154 && mapping->begin < begin) {
2155 mapping->end = begin;
2156 index++;
2157 mapping = array_get(&(s->mapping), index);
a046433a
FB
2158 }
2159 if (index >= s->mapping.next || mapping->begin > begin) {
d6a7e54e
HP
2160 mapping = array_insert(&(s->mapping), index, 1);
2161 mapping->path = NULL;
2162 adjust_mapping_indices(s, index, +1);
a046433a
FB
2163 }
2164
2165 mapping->begin = begin;
2166 mapping->end = end;
de167e41 2167
c227f099 2168DLOG(mapping_t* next_mapping;
a046433a
FB
2169assert(index + 1 >= s->mapping.next ||
2170((next_mapping = array_get(&(s->mapping), index + 1)) &&
2171 next_mapping->begin >= end)));
2172
c227f099 2173 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
d6a7e54e
HP
2174 s->current_mapping = array_get(&(s->mapping),
2175 s->current_mapping - first_mapping);
a046433a
FB
2176
2177 return mapping;
2178}
2179
2180static int remove_mapping(BDRVVVFATState* s, int mapping_index)
2181{
c227f099
AL
2182 mapping_t* mapping = array_get(&(s->mapping), mapping_index);
2183 mapping_t* first_mapping = array_get(&(s->mapping), 0);
a046433a
FB
2184
2185 /* free mapping */
ce137829
SW
2186 if (mapping->first_mapping_index < 0) {
2187 g_free(mapping->path);
2188 }
a046433a
FB
2189
2190 /* remove from s->mapping */
2191 array_remove(&(s->mapping), mapping_index);
2192
2193 /* adjust all references to mappings */
2194 adjust_mapping_indices(s, mapping_index, -1);
2195
c227f099 2196 if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
d6a7e54e
HP
2197 s->current_mapping = array_get(&(s->mapping),
2198 s->current_mapping - first_mapping);
de167e41 2199
de167e41
FB
2200 return 0;
2201}
2202
a046433a
FB
2203static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust)
2204{
2205 int i;
2206 for (i = 0; i < s->mapping.next; i++) {
d6a7e54e
HP
2207 mapping_t* mapping = array_get(&(s->mapping), i);
2208 if (mapping->dir_index >= offset)
2209 mapping->dir_index += adjust;
2210 if ((mapping->mode & MODE_DIRECTORY) &&
2211 mapping->info.dir.first_dir_index >= offset)
2212 mapping->info.dir.first_dir_index += adjust;
a046433a
FB
2213 }
2214}
de167e41 2215
c227f099 2216static direntry_t* insert_direntries(BDRVVVFATState* s,
d6a7e54e 2217 int dir_index, int count)
de167e41 2218{
a046433a
FB
2219 /*
2220 * make room in s->directory,
2221 * adjust_dirindices
2222 */
c227f099 2223 direntry_t* result = array_insert(&(s->directory), dir_index, count);
a046433a 2224 if (result == NULL)
d6a7e54e 2225 return NULL;
a046433a 2226 adjust_dirindices(s, dir_index, count);
de167e41
FB
2227 return result;
2228}
2229
a046433a
FB
2230static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)
2231{
2232 int ret = array_remove_slice(&(s->directory), dir_index, count);
2233 if (ret)
d6a7e54e 2234 return ret;
a046433a
FB
2235 adjust_dirindices(s, dir_index, -count);
2236 return 0;
2237}
de167e41 2238
a046433a
FB
2239/*
2240 * Adapt the mappings of the cluster chain starting at first cluster
2241 * (i.e. if a file starts at first_cluster, the chain is followed according
2242 * to the modified fat, and the corresponding entries in s->mapping are
2243 * adjusted)
2244 */
2245static int commit_mappings(BDRVVVFATState* s,
d6a7e54e 2246 uint32_t first_cluster, int dir_index)
de167e41 2247{
c227f099
AL
2248 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2249 direntry_t* direntry = array_get(&(s->directory), dir_index);
a046433a
FB
2250 uint32_t cluster = first_cluster;
2251
2252 vvfat_close_current_file(s);
2253
2254 assert(mapping);
2255 assert(mapping->begin == first_cluster);
2256 mapping->first_mapping_index = -1;
2257 mapping->dir_index = dir_index;
2258 mapping->mode = (dir_index <= 0 || is_directory(direntry)) ?
d6a7e54e 2259 MODE_DIRECTORY : MODE_NORMAL;
a046433a
FB
2260
2261 while (!fat_eof(s, cluster)) {
d6a7e54e
HP
2262 uint32_t c, c1;
2263
2264 for (c = cluster, c1 = modified_fat_get(s, c); c + 1 == c1;
2265 c = c1, c1 = modified_fat_get(s, c1));
2266
2267 c++;
2268 if (c > mapping->end) {
2269 int index = array_index(&(s->mapping), mapping);
2270 int i, max_i = s->mapping.next - index;
2271 for (i = 1; i < max_i && mapping[i].begin < c; i++);
2272 while (--i > 0)
2273 remove_mapping(s, index + 1);
2274 }
2275 assert(mapping == array_get(&(s->mapping), s->mapping.next - 1)
2276 || mapping[1].begin >= c);
2277 mapping->end = c;
2278
2279 if (!fat_eof(s, c1)) {
2280 int i = find_mapping_for_cluster_aux(s, c1, 0, s->mapping.next);
2281 mapping_t* next_mapping = i >= s->mapping.next ? NULL :
2282 array_get(&(s->mapping), i);
2283
2284 if (next_mapping == NULL || next_mapping->begin > c1) {
2285 int i1 = array_index(&(s->mapping), mapping);
2286
2287 next_mapping = insert_mapping(s, c1, c1+1);
2288
2289 if (c1 < c)
2290 i1++;
2291 mapping = array_get(&(s->mapping), i1);
2292 }
2293
2294 next_mapping->dir_index = mapping->dir_index;
2295 next_mapping->first_mapping_index =
2296 mapping->first_mapping_index < 0 ?
2297 array_index(&(s->mapping), mapping) :
2298 mapping->first_mapping_index;
2299 next_mapping->path = mapping->path;
2300 next_mapping->mode = mapping->mode;
2301 next_mapping->read_only = mapping->read_only;
2302 if (mapping->mode & MODE_DIRECTORY) {
2303 next_mapping->info.dir.parent_mapping_index =
2304 mapping->info.dir.parent_mapping_index;
2305 next_mapping->info.dir.first_dir_index =
2306 mapping->info.dir.first_dir_index +
2307 0x10 * s->sectors_per_cluster *
2308 (mapping->end - mapping->begin);
2309 } else
2310 next_mapping->info.file.offset = mapping->info.file.offset +
2311 mapping->end - mapping->begin;
2312
2313 mapping = next_mapping;
2314 }
2315
2316 cluster = c1;
a046433a 2317 }
de167e41 2318
de167e41
FB
2319 return 0;
2320}
2321
a046433a 2322static int commit_direntries(BDRVVVFATState* s,
d6a7e54e 2323 int dir_index, int parent_mapping_index)
de167e41 2324{
c227f099 2325 direntry_t* direntry = array_get(&(s->directory), dir_index);
a046433a 2326 uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);
c227f099 2327 mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
a046433a
FB
2328
2329 int factor = 0x10 * s->sectors_per_cluster;
2330 int old_cluster_count, new_cluster_count;
2331 int current_dir_index = mapping->info.dir.first_dir_index;
2332 int first_dir_index = current_dir_index;
2333 int ret, i;
2334 uint32_t c;
2335
2336DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapping->path, parent_mapping_index));
2337
2338 assert(direntry);
2339 assert(mapping);
2340 assert(mapping->begin == first_cluster);
2341 assert(mapping->info.dir.first_dir_index < s->directory.next);
2342 assert(mapping->mode & MODE_DIRECTORY);
2343 assert(dir_index == 0 || is_directory(direntry));
2344
2345 mapping->info.dir.parent_mapping_index = parent_mapping_index;
2346
2347 if (first_cluster == 0) {
d6a7e54e
HP
2348 old_cluster_count = new_cluster_count =
2349 s->last_cluster_of_root_directory;
a046433a 2350 } else {
d6a7e54e
HP
2351 for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2352 c = fat_get(s, c))
2353 old_cluster_count++;
de167e41 2354
d6a7e54e
HP
2355 for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
2356 c = modified_fat_get(s, c))
2357 new_cluster_count++;
a046433a 2358 }
de167e41 2359
a046433a 2360 if (new_cluster_count > old_cluster_count) {
d6a7e54e
HP
2361 if (insert_direntries(s,
2362 current_dir_index + factor * old_cluster_count,
2363 factor * (new_cluster_count - old_cluster_count)) == NULL)
2364 return -1;
a046433a 2365 } else if (new_cluster_count < old_cluster_count)
d6a7e54e
HP
2366 remove_direntries(s,
2367 current_dir_index + factor * new_cluster_count,
2368 factor * (old_cluster_count - new_cluster_count));
a046433a
FB
2369
2370 for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {
ebb72c9f 2371 direntry_t *first_direntry;
d6a7e54e
HP
2372 void* direntry = array_get(&(s->directory), current_dir_index);
2373 int ret = vvfat_read(s->bs, cluster2sector(s, c), direntry,
2374 s->sectors_per_cluster);
2375 if (ret)
2376 return ret;
ebb72c9f
KW
2377
2378 /* The first directory entry on the filesystem is the volume name */
2379 first_direntry = (direntry_t*) s->directory.pointer;
2380 assert(!memcmp(first_direntry->name, s->volume_label, 11));
2381
d6a7e54e 2382 current_dir_index += factor;
a046433a 2383 }
de167e41 2384
a046433a
FB
2385 ret = commit_mappings(s, first_cluster, dir_index);
2386 if (ret)
d6a7e54e 2387 return ret;
a046433a
FB
2388
2389 /* recurse */
2390 for (i = 0; i < factor * new_cluster_count; i++) {
d6a7e54e
HP
2391 direntry = array_get(&(s->directory), first_dir_index + i);
2392 if (is_directory(direntry) && !is_dot(direntry)) {
2393 mapping = find_mapping_for_cluster(s, first_cluster);
2394 assert(mapping->mode & MODE_DIRECTORY);
2395 ret = commit_direntries(s, first_dir_index + i,
2396 array_index(&(s->mapping), mapping));
2397 if (ret)
2398 return ret;
2399 }
a046433a 2400 }
de167e41 2401
a046433a
FB
2402 return 0;
2403}
de167e41 2404
a046433a
FB
2405/* commit one file (adjust contents, adjust mapping),
2406 return first_mapping_index */
2407static int commit_one_file(BDRVVVFATState* s,
d6a7e54e 2408 int dir_index, uint32_t offset)
a046433a 2409{
c227f099 2410 direntry_t* direntry = array_get(&(s->directory), dir_index);
a046433a
FB
2411 uint32_t c = begin_of_direntry(direntry);
2412 uint32_t first_cluster = c;
c227f099 2413 mapping_t* mapping = find_mapping_for_cluster(s, c);
a046433a 2414 uint32_t size = filesize_of_direntry(direntry);
7267c094 2415 char* cluster = g_malloc(s->cluster_size);
a046433a
FB
2416 uint32_t i;
2417 int fd = 0;
2418
2419 assert(offset < size);
2420 assert((offset % s->cluster_size) == 0);
2421
2422 for (i = s->cluster_size; i < offset; i += s->cluster_size)
d6a7e54e 2423 c = modified_fat_get(s, c);
a046433a 2424
6165f4d8 2425 fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
a046433a 2426 if (fd < 0) {
d6a7e54e
HP
2427 fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
2428 strerror(errno), errno);
ce137829 2429 g_free(cluster);
d6a7e54e 2430 return fd;
de167e41 2431 }
ce137829
SW
2432 if (offset > 0) {
2433 if (lseek(fd, offset, SEEK_SET) != offset) {
2e1e79da 2434 qemu_close(fd);
ce137829
SW
2435 g_free(cluster);
2436 return -3;
2437 }
2438 }
a046433a
FB
2439
2440 while (offset < size) {
d6a7e54e
HP
2441 uint32_t c1;
2442 int rest_size = (size - offset > s->cluster_size ?
2443 s->cluster_size : size - offset);
2444 int ret;
a046433a 2445
d6a7e54e 2446 c1 = modified_fat_get(s, c);
a046433a 2447
d6a7e54e
HP
2448 assert((size - offset == 0 && fat_eof(s, c)) ||
2449 (size > offset && c >=2 && !fat_eof(s, c)));
a046433a 2450
d6a7e54e
HP
2451 ret = vvfat_read(s->bs, cluster2sector(s, c),
2452 (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
a046433a 2453
ce137829 2454 if (ret < 0) {
2e1e79da 2455 qemu_close(fd);
ce137829
SW
2456 g_free(cluster);
2457 return ret;
2458 }
a046433a 2459
ce137829 2460 if (write(fd, cluster, rest_size) < 0) {
2e1e79da 2461 qemu_close(fd);
ce137829
SW
2462 g_free(cluster);
2463 return -2;
2464 }
a046433a 2465
d6a7e54e
HP
2466 offset += rest_size;
2467 c = c1;
a046433a
FB
2468 }
2469
2dedf83e
KS
2470 if (ftruncate(fd, size)) {
2471 perror("ftruncate()");
2e1e79da 2472 qemu_close(fd);
ce137829 2473 g_free(cluster);
2dedf83e
KS
2474 return -4;
2475 }
2e1e79da 2476 qemu_close(fd);
ce137829 2477 g_free(cluster);
a046433a
FB
2478
2479 return commit_mappings(s, first_cluster, dir_index);
2480}
2481
2482#ifdef DEBUG
2483/* test, if all mappings point to valid direntries */
2484static void check1(BDRVVVFATState* s)
2485{
2486 int i;
2487 for (i = 0; i < s->mapping.next; i++) {
d6a7e54e
HP
2488 mapping_t* mapping = array_get(&(s->mapping), i);
2489 if (mapping->mode & MODE_DELETED) {
2490 fprintf(stderr, "deleted\n");
2491 continue;
2492 }
2493 assert(mapping->dir_index < s->directory.next);
2494 direntry_t* direntry = array_get(&(s->directory), mapping->dir_index);
2495 assert(mapping->begin == begin_of_direntry(direntry) || mapping->first_mapping_index >= 0);
2496 if (mapping->mode & MODE_DIRECTORY) {
2497 assert(mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster * (mapping->end - mapping->begin) <= s->directory.next);
2498 assert((mapping->info.dir.first_dir_index % (0x10 * s->sectors_per_cluster)) == 0);
2499 }
de167e41 2500 }
de167e41
FB
2501}
2502
a046433a
FB
2503/* test, if all direntries have mappings */
2504static void check2(BDRVVVFATState* s)
de167e41 2505{
de167e41 2506 int i;
a046433a 2507 int first_mapping = -1;
de167e41 2508
a046433a 2509 for (i = 0; i < s->directory.next; i++) {
d6a7e54e
HP
2510 direntry_t* direntry = array_get(&(s->directory), i);
2511
2512 if (is_short_name(direntry) && begin_of_direntry(direntry)) {
2513 mapping_t* mapping = find_mapping_for_cluster(s, begin_of_direntry(direntry));
2514 assert(mapping);
2515 assert(mapping->dir_index == i || is_dot(direntry));
2516 assert(mapping->begin == begin_of_direntry(direntry) || is_dot(direntry));
2517 }
2518
2519 if ((i % (0x10 * s->sectors_per_cluster)) == 0) {
2520 /* cluster start */
2521 int j, count = 0;
2522
2523 for (j = 0; j < s->mapping.next; j++) {
2524 mapping_t* mapping = array_get(&(s->mapping), j);
2525 if (mapping->mode & MODE_DELETED)
2526 continue;
2527 if (mapping->mode & MODE_DIRECTORY) {
2528 if (mapping->info.dir.first_dir_index <= i && mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster > i) {
2529 assert(++count == 1);
2530 if (mapping->first_mapping_index == -1)
2531 first_mapping = array_index(&(s->mapping), mapping);
2532 else
2533 assert(first_mapping == mapping->first_mapping_index);
2534 if (mapping->info.dir.parent_mapping_index < 0)
2535 assert(j == 0);
2536 else {
2537 mapping_t* parent = array_get(&(s->mapping), mapping->info.dir.parent_mapping_index);
2538 assert(parent->mode & MODE_DIRECTORY);
2539 assert(parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index);
2540 }
2541 }
2542 }
2543 }
2544 if (count == 0)
2545 first_mapping = -1;
2546 }
a046433a
FB
2547 }
2548}
2549#endif
de167e41 2550
a046433a
FB
2551static int handle_renames_and_mkdirs(BDRVVVFATState* s)
2552{
2553 int i;
de167e41 2554
a046433a
FB
2555#ifdef DEBUG
2556 fprintf(stderr, "handle_renames\n");
2557 for (i = 0; i < s->commits.next; i++) {
d6a7e54e
HP
2558 commit_t* commit = array_get(&(s->commits), i);
2559 fprintf(stderr, "%d, %s (%d, %d)\n", i, commit->path ? commit->path : "(null)", commit->param.rename.cluster, commit->action);
a046433a
FB
2560 }
2561#endif
2562
2563 for (i = 0; i < s->commits.next;) {
d6a7e54e
HP
2564 commit_t* commit = array_get(&(s->commits), i);
2565 if (commit->action == ACTION_RENAME) {
2566 mapping_t* mapping = find_mapping_for_cluster(s,
2567 commit->param.rename.cluster);
2568 char* old_path = mapping->path;
2569
2570 assert(commit->path);
2571 mapping->path = commit->path;
2572 if (rename(old_path, mapping->path))
2573 return -2;
2574
2575 if (mapping->mode & MODE_DIRECTORY) {
2576 int l1 = strlen(mapping->path);
2577 int l2 = strlen(old_path);
2578 int diff = l1 - l2;
2579 direntry_t* direntry = array_get(&(s->directory),
2580 mapping->info.dir.first_dir_index);
2581 uint32_t c = mapping->begin;
2582 int i = 0;
2583
2584 /* recurse */
2585 while (!fat_eof(s, c)) {
2586 do {
2587 direntry_t* d = direntry + i;
2588
2589 if (is_file(d) || (is_directory(d) && !is_dot(d))) {
2590 mapping_t* m = find_mapping_for_cluster(s,
2591 begin_of_direntry(d));
2592 int l = strlen(m->path);
2593 char* new_path = g_malloc(l + diff + 1);
2594
2595 assert(!strncmp(m->path, mapping->path, l2));
a046433a 2596
363a37d5
BS
2597 pstrcpy(new_path, l + diff + 1, mapping->path);
2598 pstrcpy(new_path + l1, l + diff + 1 - l1,
2599 m->path + l2);
a046433a 2600
d6a7e54e
HP
2601 schedule_rename(s, m->begin, new_path);
2602 }
2603 i++;
2604 } while((i % (0x10 * s->sectors_per_cluster)) != 0);
2605 c = fat_get(s, c);
2606 }
2607 }
de167e41 2608
ce137829 2609 g_free(old_path);
d6a7e54e
HP
2610 array_remove(&(s->commits), i);
2611 continue;
2612 } else if (commit->action == ACTION_MKDIR) {
2613 mapping_t* mapping;
2614 int j, parent_path_len;
a046433a 2615
48c2f068
FB
2616#ifdef __MINGW32__
2617 if (mkdir(commit->path))
2618 return -5;
2619#else
2620 if (mkdir(commit->path, 0755))
2621 return -5;
2622#endif
a046433a 2623
d6a7e54e
HP
2624 mapping = insert_mapping(s, commit->param.mkdir.cluster,
2625 commit->param.mkdir.cluster + 1);
2626 if (mapping == NULL)
2627 return -6;
2628
2629 mapping->mode = MODE_DIRECTORY;
2630 mapping->read_only = 0;
2631 mapping->path = commit->path;
2632 j = s->directory.next;
2633 assert(j);
2634 insert_direntries(s, s->directory.next,
2635 0x10 * s->sectors_per_cluster);
2636 mapping->info.dir.first_dir_index = j;
2637
2638 parent_path_len = strlen(commit->path)
2639 - strlen(get_basename(commit->path)) - 1;
2640 for (j = 0; j < s->mapping.next; j++) {
2641 mapping_t* m = array_get(&(s->mapping), j);
2642 if (m->first_mapping_index < 0 && m != mapping &&
2643 !strncmp(m->path, mapping->path, parent_path_len) &&
2644 strlen(m->path) == parent_path_len)
2645 break;
2646 }
2647 assert(j < s->mapping.next);
2648 mapping->info.dir.parent_mapping_index = j;
2649
2650 array_remove(&(s->commits), i);
2651 continue;
2652 }
2653
2654 i++;
a046433a
FB
2655 }
2656 return 0;
2657}
2658
2659/*
2660 * TODO: make sure that the short name is not matching *another* file
2661 */
2662static int handle_commits(BDRVVVFATState* s)
2663{
2664 int i, fail = 0;
2665
2666 vvfat_close_current_file(s);
2667
2668 for (i = 0; !fail && i < s->commits.next; i++) {
d6a7e54e
HP
2669 commit_t* commit = array_get(&(s->commits), i);
2670 switch(commit->action) {
2671 case ACTION_RENAME: case ACTION_MKDIR:
43dc2a64 2672 abort();
d6a7e54e
HP
2673 fail = -2;
2674 break;
2675 case ACTION_WRITEOUT: {
a6c6f76c
BS
2676#ifndef NDEBUG
2677 /* these variables are only used by assert() below */
d6a7e54e
HP
2678 direntry_t* entry = array_get(&(s->directory),
2679 commit->param.writeout.dir_index);
2680 uint32_t begin = begin_of_direntry(entry);
2681 mapping_t* mapping = find_mapping_for_cluster(s, begin);
a6c6f76c 2682#endif
a046433a 2683
d6a7e54e
HP
2684 assert(mapping);
2685 assert(mapping->begin == begin);
2686 assert(commit->path == NULL);
2687
2688 if (commit_one_file(s, commit->param.writeout.dir_index,
2689 commit->param.writeout.modified_offset))
2690 fail = -3;
2691
2692 break;
2693 }
2694 case ACTION_NEW_FILE: {
2695 int begin = commit->param.new_file.first_cluster;
2696 mapping_t* mapping = find_mapping_for_cluster(s, begin);
2697 direntry_t* entry;
2698 int i;
2699
2700 /* find direntry */
2701 for (i = 0; i < s->directory.next; i++) {
2702 entry = array_get(&(s->directory), i);
2703 if (is_file(entry) && begin_of_direntry(entry) == begin)
2704 break;
2705 }
2706
2707 if (i >= s->directory.next) {
2708 fail = -6;
2709 continue;
2710 }
2711
2712 /* make sure there exists an initial mapping */
2713 if (mapping && mapping->begin != begin) {
2714 mapping->end = begin;
2715 mapping = NULL;
2716 }
2717 if (mapping == NULL) {
2718 mapping = insert_mapping(s, begin, begin+1);
2719 }
2720 /* most members will be fixed in commit_mappings() */
2721 assert(commit->path);
2722 mapping->path = commit->path;
2723 mapping->read_only = 0;
2724 mapping->mode = MODE_NORMAL;
2725 mapping->info.file.offset = 0;
2726
2727 if (commit_one_file(s, i, 0))
2728 fail = -7;
2729
2730 break;
2731 }
2732 default:
43dc2a64 2733 abort();
d6a7e54e 2734 }
a046433a
FB
2735 }
2736 if (i > 0 && array_remove_slice(&(s->commits), 0, i))
d6a7e54e 2737 return -1;
a046433a
FB
2738 return fail;
2739}
2740
2741static int handle_deletes(BDRVVVFATState* s)
2742{
2743 int i, deferred = 1, deleted = 1;
2744
2745 /* delete files corresponding to mappings marked as deleted */
2746 /* handle DELETEs and unused mappings (modified_fat_get(s, mapping->begin) == 0) */
2747 while (deferred && deleted) {
d6a7e54e
HP
2748 deferred = 0;
2749 deleted = 0;
2750
2751 for (i = 1; i < s->mapping.next; i++) {
2752 mapping_t* mapping = array_get(&(s->mapping), i);
2753 if (mapping->mode & MODE_DELETED) {
2754 direntry_t* entry = array_get(&(s->directory),
2755 mapping->dir_index);
2756
2757 if (is_free(entry)) {
2758 /* remove file/directory */
2759 if (mapping->mode & MODE_DIRECTORY) {
2760 int j, next_dir_index = s->directory.next,
2761 first_dir_index = mapping->info.dir.first_dir_index;
2762
2763 if (rmdir(mapping->path) < 0) {
2764 if (errno == ENOTEMPTY) {
2765 deferred++;
2766 continue;
2767 } else
2768 return -5;
2769 }
2770
2771 for (j = 1; j < s->mapping.next; j++) {
2772 mapping_t* m = array_get(&(s->mapping), j);
2773 if (m->mode & MODE_DIRECTORY &&
2774 m->info.dir.first_dir_index >
2775 first_dir_index &&
2776 m->info.dir.first_dir_index <
2777 next_dir_index)
2778 next_dir_index =
2779 m->info.dir.first_dir_index;
2780 }
2781 remove_direntries(s, first_dir_index,
2782 next_dir_index - first_dir_index);
2783
2784 deleted++;
2785 }
2786 } else {
2787 if (unlink(mapping->path))
2788 return -4;
2789 deleted++;
2790 }
2791 DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry));
2792 remove_mapping(s, i);
2793 }
2794 }
de167e41 2795 }
a046433a
FB
2796
2797 return 0;
2798}
2799
2800/*
2801 * synchronize mapping with new state:
2802 *
2803 * - copy FAT (with bdrv_read)
2804 * - mark all filenames corresponding to mappings as deleted
2805 * - recurse direntries from root (using bs->bdrv_read)
2806 * - delete files corresponding to mappings marked as deleted
2807 */
2808static int do_commit(BDRVVVFATState* s)
2809{
2810 int ret = 0;
2811
2812 /* the real meat are the commits. Nothing to do? Move along! */
2813 if (s->commits.next == 0)
d6a7e54e 2814 return 0;
a046433a
FB
2815
2816 vvfat_close_current_file(s);
2817
2818 ret = handle_renames_and_mkdirs(s);
2819 if (ret) {
d6a7e54e 2820 fprintf(stderr, "Error handling renames (%d)\n", ret);
43dc2a64 2821 abort();
d6a7e54e 2822 return ret;
a046433a
FB
2823 }
2824
5fafdf24 2825 /* copy FAT (with bdrv_read) */
a046433a
FB
2826 memcpy(s->fat.pointer, s->fat2, 0x200 * s->sectors_per_fat);
2827
2828 /* recurse direntries from root (using bs->bdrv_read) */
2829 ret = commit_direntries(s, 0, -1);
2830 if (ret) {
d6a7e54e 2831 fprintf(stderr, "Fatal: error while committing (%d)\n", ret);
43dc2a64 2832 abort();
d6a7e54e 2833 return ret;
a046433a
FB
2834 }
2835
2836 ret = handle_commits(s);
2837 if (ret) {
d6a7e54e 2838 fprintf(stderr, "Error handling commits (%d)\n", ret);
43dc2a64 2839 abort();
d6a7e54e 2840 return ret;
a046433a
FB
2841 }
2842
2843 ret = handle_deletes(s);
2844 if (ret) {
d6a7e54e 2845 fprintf(stderr, "Error deleting\n");
43dc2a64 2846 abort();
d6a7e54e 2847 return ret;
a046433a
FB
2848 }
2849
eecc7747
KW
2850 if (s->qcow->bs->drv->bdrv_make_empty) {
2851 s->qcow->bs->drv->bdrv_make_empty(s->qcow->bs);
7704df98 2852 }
a046433a
FB
2853
2854 memset(s->used_clusters, 0, sector2cluster(s, s->sector_count));
2855
2856DLOG(checkpoint());
2857 return 0;
2858}
2859
2860static int try_commit(BDRVVVFATState* s)
2861{
2862 vvfat_close_current_file(s);
2863DLOG(checkpoint());
2864 if(!is_consistent(s))
d6a7e54e 2865 return -1;
a046433a
FB
2866 return do_commit(s);
2867}
2868
5fafdf24 2869static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
a046433a
FB
2870 const uint8_t *buf, int nb_sectors)
2871{
5fafdf24 2872 BDRVVVFATState *s = bs->opaque;
a046433a
FB
2873 int i, ret;
2874
2875DLOG(checkpoint());
2876
ac48e389
KW
2877 /* Check if we're operating in read-only mode */
2878 if (s->qcow == NULL) {
2879 return -EACCES;
2880 }
2881
a046433a
FB
2882 vvfat_close_current_file(s);
2883
2884 /*
2885 * Some sanity checks:
2886 * - do not allow writing to the boot sector
2887 * - do not allow to write non-ASCII filenames
2888 */
2889
4dc705dc 2890 if (sector_num < s->offset_to_fat)
d6a7e54e 2891 return -1;
a046433a
FB
2892
2893 for (i = sector2cluster(s, sector_num);
d6a7e54e
HP
2894 i <= sector2cluster(s, sector_num + nb_sectors - 1);) {
2895 mapping_t* mapping = find_mapping_for_cluster(s, i);
2896 if (mapping) {
2897 if (mapping->read_only) {
2898 fprintf(stderr, "Tried to write to write-protected file %s\n",
2899 mapping->path);
2900 return -1;
2901 }
2902
2903 if (mapping->mode & MODE_DIRECTORY) {
2904 int begin = cluster2sector(s, i);
2905 int end = begin + s->sectors_per_cluster, k;
2906 int dir_index;
2907 const direntry_t* direntries;
2908 long_file_name lfn;
2909
2910 lfn_init(&lfn);
2911
2912 if (begin < sector_num)
2913 begin = sector_num;
2914 if (end > sector_num + nb_sectors)
2915 end = sector_num + nb_sectors;
2916 dir_index = mapping->dir_index +
2917 0x10 * (begin - mapping->begin * s->sectors_per_cluster);
2918 direntries = (direntry_t*)(buf + 0x200 * (begin - sector_num));
2919
2920 for (k = 0; k < (end - begin) * 0x10; k++) {
2921 /* do not allow non-ASCII filenames */
2922 if (parse_long_name(&lfn, direntries + k) < 0) {
2923 fprintf(stderr, "Warning: non-ASCII filename\n");
2924 return -1;
2925 }
2926 /* no access to the direntry of a read-only file */
2927 else if (is_short_name(direntries+k) &&
2928 (direntries[k].attributes & 1)) {
2929 if (memcmp(direntries + k,
2930 array_get(&(s->directory), dir_index + k),
2931 sizeof(direntry_t))) {
2932 fprintf(stderr, "Warning: tried to write to write-protected file\n");
2933 return -1;
2934 }
2935 }
2936 }
2937 }
2938 i = mapping->end;
2939 } else
2940 i++;
a046433a
FB
2941 }
2942
2943 /*
2944 * Use qcow backend. Commit later.
2945 */
2946DLOG(fprintf(stderr, "Write to qcow backend: %d + %d\n", (int)sector_num, nb_sectors));
18d51c4b 2947 ret = bdrv_write(s->qcow, sector_num, buf, nb_sectors);
a046433a 2948 if (ret < 0) {
d6a7e54e
HP
2949 fprintf(stderr, "Error writing to qcow backend\n");
2950 return ret;
a046433a
FB
2951 }
2952
2953 for (i = sector2cluster(s, sector_num);
d6a7e54e
HP
2954 i <= sector2cluster(s, sector_num + nb_sectors - 1); i++)
2955 if (i >= 0)
2956 s->used_clusters[i] |= USED_ALLOCATED;
a046433a
FB
2957
2958DLOG(checkpoint());
2959 /* TODO: add timeout */
2960 try_commit(s);
2961
2962DLOG(checkpoint());
2963 return 0;
2964}
2965
4575eb49
KW
2966static int coroutine_fn
2967vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2968 QEMUIOVector *qiov, int flags)
e183ef75
PB
2969{
2970 int ret;
2971 BDRVVVFATState *s = bs->opaque;
4575eb49
KW
2972 uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
2973 int nb_sectors = bytes >> BDRV_SECTOR_BITS;
2974 void *buf;
2975
2976 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2977 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
2978
2979 buf = g_try_malloc(bytes);
2980 if (bytes && buf == NULL) {
2981 return -ENOMEM;
2982 }
2983 qemu_iovec_to_buf(qiov, 0, buf, bytes);
2984
e183ef75
PB
2985 qemu_co_mutex_lock(&s->lock);
2986 ret = vvfat_write(bs, sector_num, buf, nb_sectors);
2987 qemu_co_mutex_unlock(&s->lock);
4575eb49
KW
2988
2989 g_free(buf);
2990
e183ef75
PB
2991 return ret;
2992}
2993
b6b8a333 2994static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,
d6a7e54e 2995 int64_t sector_num, int nb_sectors, int *n, BlockDriverState **file)
a046433a 2996{
139921aa 2997 *n = bs->total_sectors - sector_num;
4bc74be9
PB
2998 if (*n > nb_sectors) {
2999 *n = nb_sectors;
3000 } else if (*n < 0) {
3001 return 0;
3002 }
3003 return BDRV_BLOCK_DATA;
a046433a
FB
3004}
3005
4575eb49
KW
3006static int coroutine_fn
3007write_target_commit(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
3008 QEMUIOVector *qiov, int flags)
3009{
9217e26f 3010 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
a046433a
FB
3011 return try_commit(s);
3012}
3013
3014static void write_target_close(BlockDriverState *bs) {
9217e26f 3015 BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
eecc7747 3016 bdrv_unref_child(s->bs, s->qcow);
ce137829 3017 g_free(s->qcow_filename);
a046433a
FB
3018}
3019
3020static BlockDriver vvfat_write_target = {
f9e96436 3021 .format_name = "vvfat_write_target",
a8a4d15c 3022 .instance_size = sizeof(void*),
4575eb49 3023 .bdrv_co_pwritev = write_target_commit,
f9e96436 3024 .bdrv_close = write_target_close,
a046433a
FB
3025};
3026
eecc7747
KW
3027static void vvfat_qcow_options(int *child_flags, QDict *child_options,
3028 int parent_flags, QDict *parent_options)
a046433a 3029{
f87a0e29
AG
3030 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "off");
3031 *child_flags = BDRV_O_NO_FLUSH;
eecc7747
KW
3032}
3033
3034static const BdrvChildRole child_vvfat_qcow = {
3035 .inherit_options = vvfat_qcow_options,
3036};
3037
3038static int enable_write_target(BlockDriverState *bs, Error **errp)
3039{
3040 BDRVVVFATState *s = bs->opaque;
facdbb02 3041 BlockDriver *bdrv_qcow = NULL;
5db15a57 3042 BlockDriverState *backing;
facdbb02 3043 QemuOpts *opts = NULL;
a655211a 3044 int ret;
a046433a 3045 int size = sector2cluster(s, s->sector_count);
e6641719
HR
3046 QDict *options;
3047
a046433a
FB
3048 s->used_clusters = calloc(size, 1);
3049
c227f099 3050 array_init(&(s->commits), sizeof(commit_t));
a046433a 3051
9a29e18f
JC
3052 s->qcow_filename = g_malloc(PATH_MAX);
3053 ret = get_tmp_filename(s->qcow_filename, PATH_MAX);
eba25057 3054 if (ret < 0) {
68c70af1 3055 error_setg_errno(errp, -ret, "can't create temporary file");
78f27bd0 3056 goto err;
eba25057 3057 }
91a073a9
KW
3058
3059 bdrv_qcow = bdrv_find_format("qcow");
1bcb15cf
HR
3060 if (!bdrv_qcow) {
3061 error_setg(errp, "Failed to locate qcow driver");
3062 ret = -ENOENT;
3063 goto err;
3064 }
3065
c282e1fd 3066 opts = qemu_opts_create(bdrv_qcow->create_opts, NULL, 0, &error_abort);
39101f25
MA
3067 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s->sector_count * 512,
3068 &error_abort);
f43e47db 3069 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, "fat:", &error_abort);
91a073a9 3070
c282e1fd 3071 ret = bdrv_create(bdrv_qcow, s->qcow_filename, opts, errp);
facdbb02 3072 qemu_opts_del(opts);
78f27bd0
FZ
3073 if (ret < 0) {
3074 goto err;
3075 }
a655211a 3076
e6641719 3077 options = qdict_new();
46f5ac20 3078 qdict_put_str(options, "write-target.driver", "qcow");
eecc7747
KW
3079 s->qcow = bdrv_open_child(s->qcow_filename, options, "write-target", bs,
3080 &child_vvfat_qcow, false, errp);
c4b48bfd 3081 QDECREF(options);
5b363937
HR
3082 if (!s->qcow) {
3083 ret = -EINVAL;
78f27bd0 3084 goto err;
d6e9098e 3085 }
a046433a
FB
3086
3087#ifndef _WIN32
3088 unlink(s->qcow_filename);
3089#endif
3090
a8a4d15c
KW
3091 backing = bdrv_new_open_driver(&vvfat_write_target, NULL, BDRV_O_ALLOW_RDWR,
3092 &error_abort);
3093 *(void**) backing->opaque = s;
3094
12fa4af6 3095 bdrv_set_backing_hd(s->bs, backing, &error_abort);
5db15a57
KW
3096 bdrv_unref(backing);
3097
de167e41 3098 return 0;
78f27bd0
FZ
3099
3100err:
3101 g_free(s->qcow_filename);
3102 s->qcow_filename = NULL;
3103 return ret;
de167e41
FB
3104}
3105
91ef3825
KW
3106static void vvfat_child_perm(BlockDriverState *bs, BdrvChild *c,
3107 const BdrvChildRole *role,
3108 uint64_t perm, uint64_t shared,
3109 uint64_t *nperm, uint64_t *nshared)
3110{
3111 BDRVVVFATState *s = bs->opaque;
3112
3113 assert(c == s->qcow || role == &child_backing);
3114
3115 if (c == s->qcow) {
3116 /* This is a private node, nobody should try to attach to it */
3117 *nperm = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
3118 *nshared = BLK_PERM_WRITE_UNCHANGED;
3119 } else {
3120 /* The backing file is there so 'commit' can use it. vvfat doesn't
3121 * access it in any way. */
3122 *nperm = 0;
3123 *nshared = BLK_PERM_ALL;
3124 }
3125}
3126
de167e41
FB
3127static void vvfat_close(BlockDriverState *bs)
3128{
3129 BDRVVVFATState *s = bs->opaque;
3130
3131 vvfat_close_current_file(s);
3132 array_free(&(s->fat));
3133 array_free(&(s->directory));
3134 array_free(&(s->mapping));
ce137829 3135 g_free(s->cluster_buffer);
3397f0cb
KW
3136
3137 if (s->qcow) {
3138 migrate_del_blocker(s->migration_blocker);
3139 error_free(s->migration_blocker);
3140 }
de167e41
FB
3141}
3142
5efa9d5a 3143static BlockDriver bdrv_vvfat = {
7ad9be64
KW
3144 .format_name = "vvfat",
3145 .protocol_name = "fat",
3146 .instance_size = sizeof(BDRVVVFATState),
3147
3148 .bdrv_parse_filename = vvfat_parse_filename,
3149 .bdrv_file_open = vvfat_open,
a6506481 3150 .bdrv_refresh_limits = vvfat_refresh_limits,
7ad9be64 3151 .bdrv_close = vvfat_close,
91ef3825 3152 .bdrv_child_perm = vvfat_child_perm,
7ad9be64 3153
4575eb49
KW
3154 .bdrv_co_preadv = vvfat_co_preadv,
3155 .bdrv_co_pwritev = vvfat_co_pwritev,
b6b8a333 3156 .bdrv_co_get_block_status = vvfat_co_get_block_status,
de167e41
FB
3157};
3158
5efa9d5a
AL
3159static void bdrv_vvfat_init(void)
3160{
3161 bdrv_register(&bdrv_vvfat);
3162}
3163
3164block_init(bdrv_vvfat_init);
3165
a046433a 3166#ifdef DEBUG
3f47aa8c 3167static void checkpoint(void) {
c227f099 3168 assert(((mapping_t*)array_get(&(vvv->mapping), 0))->end == 2);
a046433a
FB
3169 check1(vvv);
3170 check2(vvv);
3171 assert(!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode & MODE_DIRECTORY));
3172#if 0
c227f099 3173 if (((direntry_t*)vvv->directory.pointer)[1].attributes != 0xf)
d6a7e54e 3174 fprintf(stderr, "Nonono!\n");
c227f099
AL
3175 mapping_t* mapping;
3176 direntry_t* direntry;
a046433a
FB
3177 assert(vvv->mapping.size >= vvv->mapping.item_size * vvv->mapping.next);
3178 assert(vvv->directory.size >= vvv->directory.item_size * vvv->directory.next);
3179 if (vvv->mapping.next<47)
d6a7e54e 3180 return;
a046433a
FB
3181 assert((mapping = array_get(&(vvv->mapping), 47)));
3182 assert(mapping->dir_index < vvv->directory.next);
3183 direntry = array_get(&(vvv->directory), mapping->dir_index);
3184 assert(!memcmp(direntry->name, "USB H ", 11) || direntry->name[0]==0);
3185#endif
a046433a
FB
3186}
3187#endif