vvfat.c 80.1 KB
Newer Older
1
/* vim:set shiftwidth=4 ts=8: */
2 3
/*
 * QEMU Block driver for virtual VFAT (shadows a local directory)
4
 *
5
 * Copyright (c) 2004,2005 Johannes E. Schindelin
6
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <sys/stat.h>
#include <dirent.h>
P
pbrook 已提交
27
#include "qemu-common.h"
28
#include "block_int.h"
29
#include "module.h"
30

31 32 33 34 35 36 37 38 39 40
#ifndef S_IWGRP
#define S_IWGRP 0
#endif
#ifndef S_IWOTH
#define S_IWOTH 0
#endif

/* TODO: add ":bootsector=blabla.img:" */
/* LATER TODO: add automatic boot sector generation from
    BOOTEASY.ASM and Ranish Partition Manager
41
    Note that DOS assumes the system files to be the first files in the
42 43 44 45 46 47 48 49 50 51 52 53 54
    file system (test if the boot sector still relies on that fact)! */
/* MAYBE TODO: write block-visofs.c */
/* TODO: call try_commit() only after a timeout */

/* #define DEBUG */

#ifdef DEBUG

#define DLOG(a) a

#undef stderr
#define stderr STDERR
FILE* stderr = NULL;
55

56
static void checkpoint(void);
57

58 59 60 61 62 63
#ifdef __MINGW32__
void nonono(const char* file, int line, const char* msg) {
    fprintf(stderr, "Nonono! %s:%d %s\n", file, line, msg);
    exit(-5);
}
#undef assert
B
bellard 已提交
64
#define assert(a) do {if (!(a)) nonono(__FILE__, __LINE__, #a);}while(0)
65 66 67 68 69 70 71
#endif

#else

#define DLOG(a)

#endif
72 73

/* dynamic array functions */
A
Anthony Liguori 已提交
74
typedef struct array_t {
75 76
    char* pointer;
    unsigned int size,next,item_size;
A
Anthony Liguori 已提交
77
} array_t;
78

A
Anthony Liguori 已提交
79
static inline void array_init(array_t* array,unsigned int item_size)
80
{
81
    array->pointer = NULL;
82 83 84 85 86
    array->size=0;
    array->next=0;
    array->item_size=item_size;
}

A
Anthony Liguori 已提交
87
static inline void array_free(array_t* array)
88
{
89
    g_free(array->pointer);
90 91 92
    array->size=array->next=0;
}

93
/* does not automatically grow */
A
Anthony Liguori 已提交
94
static inline void* array_get(array_t* array,unsigned int index) {
95 96 97 98
    assert(index < array->next);
    return array->pointer + index * array->item_size;
}

A
Anthony Liguori 已提交
99
static inline int array_ensure_allocated(array_t* array, int index)
100 101 102
{
    if((index + 1) * array->item_size > array->size) {
	int new_size = (index + 32) * array->item_size;
103
	array->pointer = g_realloc(array->pointer, new_size);
104 105 106 107
	if (!array->pointer)
	    return -1;
	array->size = new_size;
	array->next = index + 1;
108
    }
109 110

    return 0;
111 112
}

A
Anthony Liguori 已提交
113
static inline void* array_get_next(array_t* array) {
114 115 116 117 118 119 120 121 122
    unsigned int next = array->next;
    void* result;

    if (array_ensure_allocated(array, next) < 0)
	return NULL;

    array->next = next + 1;
    result = array_get(array, next);

123 124 125
    return result;
}

A
Anthony Liguori 已提交
126
static inline void* array_insert(array_t* array,unsigned int index,unsigned int count) {
127 128
    if((array->next+count)*array->item_size>array->size) {
	int increment=count*array->item_size;
129
	array->pointer=g_realloc(array->pointer,array->size+increment);
130
	if(!array->pointer)
131
            return NULL;
132 133 134 135 136 137 138 139 140 141 142
	array->size+=increment;
    }
    memmove(array->pointer+(index+count)*array->item_size,
		array->pointer+index*array->item_size,
		(array->next-index)*array->item_size);
    array->next+=count;
    return array->pointer+index*array->item_size;
}

/* this performs a "roll", so that the element which was at index_from becomes
 * index_to, but the order of all other elements is preserved. */
A
Anthony Liguori 已提交
143
static inline int array_roll(array_t* array,int index_to,int index_from,int count)
144 145 146 147 148 149 150 151 152 153
{
    char* buf;
    char* from;
    char* to;
    int is;

    if(!array ||
	    index_to<0 || index_to>=array->next ||
	    index_from<0 || index_from>=array->next)
	return -1;
154

155 156 157 158 159 160
    if(index_to==index_from)
	return 0;

    is=array->item_size;
    from=array->pointer+index_from*is;
    to=array->pointer+index_to*is;
161
    buf=g_malloc(is*count);
162 163 164 165 166 167
    memcpy(buf,from,is*count);

    if(index_to<index_from)
	memmove(to+is*count,to,from-to);
    else
	memmove(from,from+is*count,to-from);
168

169 170
    memcpy(to,buf,is*count);

171
    g_free(buf);
172 173 174 175

    return 0;
}

A
Anthony Liguori 已提交
176
static inline int array_remove_slice(array_t* array,int index, int count)
177
{
178 179 180 181
    assert(index >=0);
    assert(count > 0);
    assert(index + count <= array->next);
    if(array_roll(array,array->next-1,index,count))
182
	return -1;
183
    array->next -= count;
184 185 186
    return 0;
}

A
Anthony Liguori 已提交
187
static int array_remove(array_t* array,int index)
188 189 190 191 192
{
    return array_remove_slice(array, index, 1);
}

/* return the index for a given member */
A
Anthony Liguori 已提交
193
static int array_index(array_t* array, void* pointer)
194 195 196 197 198 199 200
{
    size_t offset = (char*)pointer - array->pointer;
    assert((offset % array->item_size) == 0);
    assert(offset/array->item_size < array->next);
    return offset/array->item_size;
}

201
/* These structures are used to fake a disk and the VFAT filesystem.
202
 * For this reason we need to use QEMU_PACKED. */
203

A
Anthony Liguori 已提交
204
typedef struct bootsector_t {
205 206 207 208 209 210 211
    uint8_t jump[3];
    uint8_t name[8];
    uint16_t sector_size;
    uint8_t sectors_per_cluster;
    uint16_t reserved_sectors;
    uint8_t number_of_fats;
    uint16_t root_entries;
212
    uint16_t total_sectors16;
213 214 215 216 217 218 219 220 221 222 223 224 225
    uint8_t media_type;
    uint16_t sectors_per_fat;
    uint16_t sectors_per_track;
    uint16_t number_of_heads;
    uint32_t hidden_sectors;
    uint32_t total_sectors;
    union {
        struct {
	    uint8_t drive_number;
	    uint8_t current_head;
	    uint8_t signature;
	    uint32_t id;
	    uint8_t volume_label[11];
226
	} QEMU_PACKED fat16;
227 228 229 230 231 232 233 234
	struct {
	    uint32_t sectors_per_fat;
	    uint16_t flags;
	    uint8_t major,minor;
	    uint32_t first_cluster_of_root_directory;
	    uint16_t info_sector;
	    uint16_t backup_boot_sector;
	    uint16_t ignored;
235
	} QEMU_PACKED fat32;
236 237 238 239
    } u;
    uint8_t fat_type[8];
    uint8_t ignored[0x1c0];
    uint8_t magic[2];
240
} QEMU_PACKED bootsector_t;
241

T
ths 已提交
242 243 244 245
typedef struct {
    uint8_t head;
    uint8_t sector;
    uint8_t cylinder;
A
Anthony Liguori 已提交
246
} mbr_chs_t;
T
ths 已提交
247

A
Anthony Liguori 已提交
248
typedef struct partition_t {
249
    uint8_t attributes; /* 0x80 = bootable */
A
Anthony Liguori 已提交
250
    mbr_chs_t start_CHS;
T
ths 已提交
251
    uint8_t   fs_type; /* 0x1 = FAT12, 0x6 = FAT16, 0xe = FAT16_LBA, 0xb = FAT32, 0xc = FAT32_LBA */
A
Anthony Liguori 已提交
252
    mbr_chs_t end_CHS;
253
    uint32_t start_sector_long;
T
ths 已提交
254
    uint32_t length_sector_long;
255
} QEMU_PACKED partition_t;
256

A
Anthony Liguori 已提交
257
typedef struct mbr_t {
T
ths 已提交
258 259 260
    uint8_t ignored[0x1b8];
    uint32_t nt_id;
    uint8_t ignored2[2];
A
Anthony Liguori 已提交
261
    partition_t partition[4];
262
    uint8_t magic[2];
263
} QEMU_PACKED mbr_t;
264

A
Anthony Liguori 已提交
265
typedef struct direntry_t {
266 267 268 269 270 271 272 273 274 275 276 277
    uint8_t name[8];
    uint8_t extension[3];
    uint8_t attributes;
    uint8_t reserved[2];
    uint16_t ctime;
    uint16_t cdate;
    uint16_t adate;
    uint16_t begin_hi;
    uint16_t mtime;
    uint16_t mdate;
    uint16_t begin;
    uint32_t size;
278
} QEMU_PACKED direntry_t;
279 280 281

/* this structure are used to transparently access the files */

A
Anthony Liguori 已提交
282
typedef struct mapping_t {
283 284
    /* begin is the first cluster, end is the last+1 */
    uint32_t begin,end;
285 286
    /* as s->directory is growable, no pointer may be used here */
    unsigned int dir_index;
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    /* the clusters of a file may be in any order; this points to the first */
    int first_mapping_index;
    union {
	/* offset is
	 * - the offset in the file (in clusters) for a file, or
	 * - the next cluster of the directory for a directory, and
	 * - the address of the buffer for a faked entry
	 */
	struct {
	    uint32_t offset;
	} file;
	struct {
	    int parent_mapping_index;
	    int first_dir_index;
	} dir;
    } info;
    /* path contains the full path, i.e. it always starts with s->path */
    char* path;

    enum { MODE_UNDEFINED = 0, MODE_NORMAL = 1, MODE_MODIFIED = 2,
	MODE_DIRECTORY = 4, MODE_FAKED = 8,
	MODE_DELETED = 16, MODE_RENAMED = 32 } mode;
    int read_only;
A
Anthony Liguori 已提交
310
} mapping_t;
311

312
#ifdef DEBUG
A
Anthony Liguori 已提交
313 314
static void print_direntry(const struct direntry_t*);
static void print_mapping(const struct mapping_t* mapping);
315
#endif
316 317 318 319

/* here begins the real VVFAT driver */

typedef struct BDRVVVFATState {
320
    CoMutex lock;
321
    BlockDriverState* bs; /* pointer to parent */
322 323
    unsigned int first_sectors_number; /* 1 for a single partition, 0x40 for a disk with partition table */
    unsigned char first_sectors[0x40*0x200];
324

325
    int fat_type; /* 16 or 32 */
A
Anthony Liguori 已提交
326
    array_t fat,directory,mapping;
327

328 329 330 331
    unsigned int cluster_size;
    unsigned int sectors_per_cluster;
    unsigned int sectors_per_fat;
    unsigned int sectors_of_root_directory;
332
    uint32_t last_cluster_of_root_directory;
333 334 335 336
    unsigned int faked_sectors; /* how many sectors are faked before file data */
    uint32_t sector_count; /* total number of sectors of the partition */
    uint32_t cluster_count; /* total number of clusters of this partition */
    uint32_t max_fat_value;
337

338
    int current_fd;
A
Anthony Liguori 已提交
339
    mapping_t* current_mapping;
340 341
    unsigned char* cluster; /* points to current cluster */
    unsigned char* cluster_buffer; /* points to a buffer to hold temp data */
342 343 344
    unsigned int current_cluster;

    /* write support */
345 346 347 348 349
    BlockDriverState* write_target;
    char* qcow_filename;
    BlockDriverState* qcow;
    void* fat2;
    char* used_clusters;
A
Anthony Liguori 已提交
350
    array_t commits;
351 352
    const char* path;
    int downcase_short_names;
353 354
} BDRVVVFATState;

T
ths 已提交
355 356 357 358
/* take the sector position spos and convert it to Cylinder/Head/Sector position
 * if the position is outside the specified geometry, fill maximum value for CHS
 * and return 1 to signal overflow.
 */
A
Anthony Liguori 已提交
359
static int sector2CHS(BlockDriverState* bs, mbr_chs_t * chs, int spos){
T
ths 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    int head,sector;
    sector   = spos % (bs->secs);  spos/= bs->secs;
    head     = spos % (bs->heads); spos/= bs->heads;
    if(spos >= bs->cyls){
        /* Overflow,
        it happens if 32bit sector positions are used, while CHS is only 24bit.
        Windows/Dos is said to take 1023/255/63 as nonrepresentable CHS */
        chs->head     = 0xFF;
        chs->sector   = 0xFF;
        chs->cylinder = 0xFF;
        return 1;
    }
    chs->head     = (uint8_t)head;
    chs->sector   = (uint8_t)( (sector+1) | ((spos>>8)<<6) );
    chs->cylinder = (uint8_t)spos;
    return 0;
}
377 378 379 380

static void init_mbr(BDRVVVFATState* s)
{
    /* TODO: if the files mbr.img and bootsect.img exist, use them */
A
Anthony Liguori 已提交
381 382
    mbr_t* real_mbr=(mbr_t*)s->first_sectors;
    partition_t* partition = &(real_mbr->partition[0]);
T
ths 已提交
383
    int lba;
384 385

    memset(s->first_sectors,0,512);
386

T
ths 已提交
387 388 389
    /* Win NT Disk Signature */
    real_mbr->nt_id= cpu_to_le32(0xbe1afdfa);

390
    partition->attributes=0x80; /* bootable */
T
ths 已提交
391 392 393 394 395 396 397 398 399

    /* LBA is used when partition is outside the CHS geometry */
    lba = sector2CHS(s->bs, &partition->start_CHS, s->first_sectors_number-1);
    lba|= sector2CHS(s->bs, &partition->end_CHS,   s->sector_count);

    /*LBA partitions are identified only by start/length_sector_long not by CHS*/
    partition->start_sector_long =cpu_to_le32(s->first_sectors_number-1);
    partition->length_sector_long=cpu_to_le32(s->sector_count - s->first_sectors_number+1);

400
    /* FAT12/FAT16/FAT32 */
T
ths 已提交
401 402 403 404 405
    /* DOS uses different types when partition is LBA,
       probably to prevent older versions from using CHS on them */
    partition->fs_type= s->fat_type==12 ? 0x1:
                        s->fat_type==16 ? (lba?0xe:0x06):
                         /*fat_tyoe==32*/ (lba?0xc:0x0b);
406 407 408 409

    real_mbr->magic[0]=0x55; real_mbr->magic[1]=0xaa;
}

410 411
/* direntry functions */

412
/* dest is assumed to hold 258 bytes, and pads with 0xffff up to next multiple of 26 */
T
ths 已提交
413
static inline int short2long_name(char* dest,const char* src)
414 415
{
    int i;
416
    int len;
417 418 419 420
    for(i=0;i<129 && src[i];i++) {
        dest[2*i]=src[i];
	dest[2*i+1]=0;
    }
421
    len=2*i;
422 423 424
    dest[2*i]=dest[2*i+1]=0;
    for(i=2*i+2;(i%26);i++)
	dest[i]=0xff;
425
    return len;
426 427
}

A
Anthony Liguori 已提交
428
static inline direntry_t* create_long_filename(BDRVVVFATState* s,const char* filename)
429 430 431 432
{
    char buffer[258];
    int length=short2long_name(buffer,filename),
        number_of_entries=(length+25)/26,i;
A
Anthony Liguori 已提交
433
    direntry_t* entry;
434 435 436 437 438 439 440 441

    for(i=0;i<number_of_entries;i++) {
	entry=array_get_next(&(s->directory));
	entry->attributes=0xf;
	entry->reserved[0]=0;
	entry->begin=0;
	entry->name[0]=(number_of_entries-i)|(i==0?0x40:0);
    }
442
    for(i=0;i<26*number_of_entries;i++) {
443 444 445 446 447 448 449 450 451 452
	int offset=(i%26);
	if(offset<10) offset=1+offset;
	else if(offset<22) offset=14+offset-10;
	else offset=28+offset-22;
	entry=array_get(&(s->directory),s->directory.next-1-(i/26));
	entry->name[offset]=buffer[i];
    }
    return array_get(&(s->directory),s->directory.next-number_of_entries);
}

A
Anthony Liguori 已提交
453
static char is_free(const direntry_t* direntry)
454
{
455
    return direntry->name[0]==0xe5 || direntry->name[0]==0x00;
456 457
}

A
Anthony Liguori 已提交
458
static char is_volume_label(const direntry_t* direntry)
459 460 461 462
{
    return direntry->attributes == 0x28;
}

A
Anthony Liguori 已提交
463
static char is_long_name(const direntry_t* direntry)
464 465 466 467
{
    return direntry->attributes == 0xf;
}

A
Anthony Liguori 已提交
468
static char is_short_name(const direntry_t* direntry)
469 470 471 472 473
{
    return !is_volume_label(direntry) && !is_long_name(direntry)
	&& !is_free(direntry);
}

A
Anthony Liguori 已提交
474
static char is_directory(const direntry_t* direntry)
475 476 477 478
{
    return direntry->attributes & 0x10 && direntry->name[0] != 0xe5;
}

A
Anthony Liguori 已提交
479
static inline char is_dot(const direntry_t* direntry)
480 481 482 483
{
    return is_short_name(direntry) && direntry->name[0] == '.';
}

A
Anthony Liguori 已提交
484
static char is_file(const direntry_t* direntry)
485 486 487 488
{
    return is_short_name(direntry) && !is_directory(direntry);
}

A
Anthony Liguori 已提交
489
static inline uint32_t begin_of_direntry(const direntry_t* direntry)
490 491 492 493
{
    return le16_to_cpu(direntry->begin)|(le16_to_cpu(direntry->begin_hi)<<16);
}

A
Anthony Liguori 已提交
494
static inline uint32_t filesize_of_direntry(const direntry_t* direntry)
495 496 497 498
{
    return le32_to_cpu(direntry->size);
}

A
Anthony Liguori 已提交
499
static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin)
500 501 502 503 504
{
    direntry->begin = cpu_to_le16(begin & 0xffff);
    direntry->begin_hi = cpu_to_le16((begin >> 16) & 0xffff);
}

505 506
/* fat functions */

A
Anthony Liguori 已提交
507
static inline uint8_t fat_chksum(const direntry_t* entry)
508 509 510 511
{
    uint8_t chksum=0;
    int i;

A
Aurelien Jarno 已提交
512 513 514
    for(i=0;i<11;i++) {
        unsigned char c;

515
        c = (i < 8) ? entry->name[i] : entry->extension[i-8];
A
Aurelien Jarno 已提交
516 517
        chksum=(((chksum&0xfe)>>1)|((chksum&0x01)?0x80:0)) + c;
    }
518

519 520 521 522 523 524 525 526 527 528
    return chksum;
}

/* if return_time==0, this returns the fat_date, else the fat_time */
static uint16_t fat_datetime(time_t time,int return_time) {
    struct tm* t;
#ifdef _WIN32
    t=localtime(&time); /* this is not thread safe */
#else
    struct tm t1;
M
Michael S. Tsirkin 已提交
529
    t = &t1;
530 531 532 533 534 535 536 537 538
    localtime_r(&time,t);
#endif
    if(return_time)
	return cpu_to_le16((t->tm_sec/2)|(t->tm_min<<5)|(t->tm_hour<<11));
    return cpu_to_le16((t->tm_mday)|((t->tm_mon+1)<<5)|((t->tm_year-80)<<9));
}

static inline void fat_set(BDRVVVFATState* s,unsigned int cluster,uint32_t value)
{
539 540 541
    if(s->fat_type==32) {
	uint32_t* entry=array_get(&(s->fat),cluster);
	*entry=cpu_to_le32(value);
542 543 544 545
    } else if(s->fat_type==16) {
	uint16_t* entry=array_get(&(s->fat),cluster);
	*entry=cpu_to_le16(value&0xffff);
    } else {
546 547 548 549 550 551 552 553 554 555 556 557
	int offset = (cluster*3/2);
	unsigned char* p = array_get(&(s->fat), offset);
        switch (cluster&1) {
	case 0:
		p[0] = value&0xff;
		p[1] = (p[1]&0xf0) | ((value>>8)&0xf);
		break;
	case 1:
		p[0] = (p[0]&0xf) | ((value&0xf)<<4);
		p[1] = (value>>4);
		break;
	}
558 559 560 561 562
    }
}

static inline uint32_t fat_get(BDRVVVFATState* s,unsigned int cluster)
{
563 564 565
    if(s->fat_type==32) {
	uint32_t* entry=array_get(&(s->fat),cluster);
	return le32_to_cpu(*entry);
566 567 568 569
    } else if(s->fat_type==16) {
	uint16_t* entry=array_get(&(s->fat),cluster);
	return le16_to_cpu(*entry);
    } else {
T
ths 已提交
570
	const uint8_t* x=(uint8_t*)(s->fat.pointer)+cluster*3/2;
571
	return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
572 573 574 575 576 577 578 579 580 581 582 583
    }
}

static inline int fat_eof(BDRVVVFATState* s,uint32_t fat_entry)
{
    if(fat_entry>s->max_fat_value-8)
	return -1;
    return 0;
}

static inline void init_fat(BDRVVVFATState* s)
{
584 585 586 587 588 589 590 591 592
    if (s->fat_type == 12) {
	array_init(&(s->fat),1);
	array_ensure_allocated(&(s->fat),
		s->sectors_per_fat * 0x200 * 3 / 2 - 1);
    } else {
	array_init(&(s->fat),(s->fat_type==32?4:2));
	array_ensure_allocated(&(s->fat),
		s->sectors_per_fat * 0x200 / s->fat.item_size - 1);
    }
593
    memset(s->fat.pointer,0,s->fat.size);
594

595 596 597
    switch(s->fat_type) {
	case 12: s->max_fat_value=0xfff; break;
	case 16: s->max_fat_value=0xffff; break;
598
	case 32: s->max_fat_value=0x0fffffff; break;
599 600 601 602 603
	default: s->max_fat_value=0; /* error... */
    }

}

604 605
/* TODO: in create_short_filename, 0xe5->0x05 is not yet handled! */
/* TODO: in parse_short_filename, 0x05->0xe5 is not yet handled! */
A
Anthony Liguori 已提交
606
static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,
607
	unsigned int directory_start, const char* filename, int is_dot)
608
{
609
    int i,j,long_index=s->directory.next;
A
Anthony Liguori 已提交
610 611
    direntry_t* entry = NULL;
    direntry_t* entry_long = NULL;
612 613 614 615 616 617 618

    if(is_dot) {
	entry=array_get_next(&(s->directory));
	memset(entry->name,0x20,11);
	memcpy(entry->name,filename,strlen(filename));
	return entry;
    }
619

620
    entry_long=create_long_filename(s,filename);
621

622
    i = strlen(filename);
623 624 625 626 627 628
    for(j = i - 1; j>0  && filename[j]!='.';j--);
    if (j > 0)
	i = (j > 8 ? 8 : j);
    else if (i > 8)
	i = 8;

629 630
    entry=array_get_next(&(s->directory));
    memset(entry->name,0x20,11);
B
blueswir1 已提交
631
    memcpy(entry->name, filename, i);
632

633 634 635
    if(j > 0)
	for (i = 0; i < 3 && filename[j+1+i]; i++)
	    entry->extension[i] = filename[j+1+i];
636 637 638

    /* upcase & remove unwanted characters */
    for(i=10;i>=0;i--) {
639
	if(i==10 || i==7) for(;i>0 && entry->name[i]==' ';i--);
640
	if(entry->name[i]<=' ' || entry->name[i]>0x7f
641
		|| strchr(".*?<>|\":/\\[];,+='",entry->name[i]))
642 643 644 645 646 647 648
	    entry->name[i]='_';
        else if(entry->name[i]>='a' && entry->name[i]<='z')
            entry->name[i]+='A'-'a';
    }

    /* mangle duplicates */
    while(1) {
A
Anthony Liguori 已提交
649
	direntry_t* entry1=array_get(&(s->directory),directory_start);
650 651 652
	int j;

	for(;entry1<entry;entry1++)
653
	    if(!is_long_name(entry1) && !memcmp(entry1->name,entry->name,11))
654 655 656 657
		break; /* found dupe */
	if(entry1==entry) /* no dupe found */
	    break;

658
	/* use all 8 characters of name */
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	if(entry->name[7]==' ') {
	    int j;
	    for(j=6;j>0 && entry->name[j]==' ';j--)
		entry->name[j]='~';
	}

	/* increment number */
	for(j=7;j>0 && entry->name[j]=='9';j--)
	    entry->name[j]='0';
	if(j>0) {
	    if(entry->name[j]<'0' || entry->name[j]>'9')
	        entry->name[j]='0';
	    else
	        entry->name[j]++;
	}
    }

    /* calculate checksum; propagate to long name */
    if(entry_long) {
        uint8_t chksum=fat_chksum(entry);

	/* calculate anew, because realloc could have taken place */
	entry_long=array_get(&(s->directory),long_index);
682
	while(entry_long<entry && is_long_name(entry_long)) {
683 684 685 686 687 688 689 690
	    entry_long->reserved[1]=chksum;
	    entry_long++;
	}
    }

    return entry;
}

691 692 693 694
/*
 * Read a directory. (the index of the corresponding mapping must be passed).
 */
static int read_directory(BDRVVVFATState* s, int mapping_index)
695
{
A
Anthony Liguori 已提交
696 697
    mapping_t* mapping = array_get(&(s->mapping), mapping_index);
    direntry_t* direntry;
698 699 700
    const char* dirname = mapping->path;
    int first_cluster = mapping->begin;
    int parent_index = mapping->info.dir.parent_mapping_index;
A
Anthony Liguori 已提交
701
    mapping_t* parent_mapping = (mapping_t*)
702
        (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);
703
    int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;
704 705 706 707 708

    DIR* dir=opendir(dirname);
    struct dirent* entry;
    int i;

709 710 711 712
    assert(mapping->mode & MODE_DIRECTORY);

    if(!dir) {
	mapping->end = mapping->begin;
713
	return -1;
714
    }
715

716 717 718
    i = mapping->info.dir.first_dir_index =
	    first_cluster == 0 ? 0 : s->directory.next;

719
    /* actually read the directory, and allocate the mappings */
720 721 722
    while((entry=readdir(dir))) {
	unsigned int length=strlen(dirname)+2+strlen(entry->d_name);
        char* buffer;
A
Anthony Liguori 已提交
723
	direntry_t* direntry;
724
        struct stat st;
725 726 727
	int is_dot=!strcmp(entry->d_name,".");
	int is_dotdot=!strcmp(entry->d_name,"..");

728
	if(first_cluster == 0 && (is_dotdot || is_dot))
729
	    continue;
730

731
	buffer=(char*)g_malloc(length);
732 733 734
	snprintf(buffer,length,"%s/%s",dirname,entry->d_name);

	if(stat(buffer,&st)<0) {
735
            g_free(buffer);
736 737 738 739
            continue;
	}

	/* create directory entry for this file */
740 741
	direntry=create_short_and_long_name(s, i, entry->d_name,
		is_dot || is_dotdot);
742 743 744 745 746 747 748 749 750
	direntry->attributes=(S_ISDIR(st.st_mode)?0x10:0x20);
	direntry->reserved[0]=direntry->reserved[1]=0;
	direntry->ctime=fat_datetime(st.st_ctime,1);
	direntry->cdate=fat_datetime(st.st_ctime,0);
	direntry->adate=fat_datetime(st.st_atime,0);
	direntry->begin_hi=0;
	direntry->mtime=fat_datetime(st.st_mtime,1);
	direntry->mdate=fat_datetime(st.st_mtime,0);
	if(is_dotdot)
751
	    set_begin_of_direntry(direntry, first_cluster_of_parent);
752
	else if(is_dot)
753
	    set_begin_of_direntry(direntry, first_cluster);
754
	else
755 756 757
	    direntry->begin=0; /* do that later */
        if (st.st_size > 0x7fffffff) {
	    fprintf(stderr, "File %s is larger than 2GB\n", buffer);
758
            g_free(buffer);
B
Blue Swirl 已提交
759
            closedir(dir);
760 761 762
	    return -2;
        }
	direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);
763 764

	/* create mapping for this file */
765
	if(!is_dot && !is_dotdot && (S_ISDIR(st.st_mode) || st.st_size)) {
A
Anthony Liguori 已提交
766
	    s->current_mapping=(mapping_t*)array_get_next(&(s->mapping));
767 768
	    s->current_mapping->begin=0;
	    s->current_mapping->end=st.st_size;
769 770 771 772
	    /*
	     * we get the direntry of the most recent direntry, which
	     * contains the short name and all the relevant information.
	     */
773
	    s->current_mapping->dir_index=s->directory.next-1;
774 775 776 777 778 779 780 781 782 783 784 785
	    s->current_mapping->first_mapping_index = -1;
	    if (S_ISDIR(st.st_mode)) {
		s->current_mapping->mode = MODE_DIRECTORY;
		s->current_mapping->info.dir.parent_mapping_index =
		    mapping_index;
	    } else {
		s->current_mapping->mode = MODE_UNDEFINED;
		s->current_mapping->info.file.offset = 0;
	    }
	    s->current_mapping->path=buffer;
	    s->current_mapping->read_only =
		(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)) == 0;
786 787 788 789 790 791
	}
    }
    closedir(dir);

    /* fill with zeroes up to the end of the cluster */
    while(s->directory.next%(0x10*s->sectors_per_cluster)) {
A
Anthony Liguori 已提交
792 793
	direntry_t* direntry=array_get_next(&(s->directory));
	memset(direntry,0,sizeof(direntry_t));
794 795
    }

796 797 798 799 800 801
/* TODO: if there are more entries, bootsector has to be adjusted! */
#define ROOT_ENTRIES (0x02 * 0x10 * s->sectors_per_cluster)
    if (mapping_index == 0 && s->directory.next < ROOT_ENTRIES) {
	/* root directory */
	int cur = s->directory.next;
	array_ensure_allocated(&(s->directory), ROOT_ENTRIES - 1);
802
	s->directory.next = ROOT_ENTRIES;
803
	memset(array_get(&(s->directory), cur), 0,
A
Anthony Liguori 已提交
804
		(ROOT_ENTRIES - cur) * sizeof(direntry_t));
805
    }
806

807
     /* reget the mapping, since s->mapping was possibly realloc()ed */
A
Anthony Liguori 已提交
808
    mapping = (mapping_t*)array_get(&(s->mapping), mapping_index);
809 810 811 812
    first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)
	* 0x20 / s->cluster_size;
    mapping->end = first_cluster;

A
Anthony Liguori 已提交
813
    direntry = (direntry_t*)array_get(&(s->directory), mapping->dir_index);
814
    set_begin_of_direntry(direntry, mapping->begin);
815

816 817
    return 0;
}
818

819 820 821 822
static inline uint32_t sector2cluster(BDRVVVFATState* s,off_t sector_num)
{
    return (sector_num-s->faked_sectors)/s->sectors_per_cluster;
}
823

824 825 826 827
static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
{
    return s->faked_sectors + s->sectors_per_cluster * cluster_num;
}
828

829 830
static int init_directories(BDRVVVFATState* s,
	const char* dirname)
831
{
A
Anthony Liguori 已提交
832 833
    bootsector_t* bootsector;
    mapping_t* mapping;
834 835 836 837 838 839
    unsigned int i;
    unsigned int cluster;

    memset(&(s->first_sectors[0]),0,0x40*0x200);

    s->cluster_size=s->sectors_per_cluster*0x200;
840
    s->cluster_buffer=g_malloc(s->cluster_size);
841 842 843 844 845 846 847 848 849 850

    /*
     * The formula: sc = spf+1+spf*spc*(512*8/fat_type),
     * where sc is sector_count,
     * spf is sectors_per_fat,
     * spc is sectors_per_clusters, and
     * fat_type = 12, 16 or 32.
     */
    i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;
    s->sectors_per_fat=(s->sector_count+i)/i; /* round up */
851

A
Anthony Liguori 已提交
852 853
    array_init(&(s->mapping),sizeof(mapping_t));
    array_init(&(s->directory),sizeof(direntry_t));
854 855 856

    /* add volume label */
    {
A
Anthony Liguori 已提交
857
	direntry_t* entry=array_get_next(&(s->directory));
858
	entry->attributes=0x28; /* archive | volume label */
859 860
	memcpy(entry->name,"QEMU VVF",8);
	memcpy(entry->extension,"AT ",3);
861 862 863 864 865
    }

    /* Now build FAT, and write back information into directory */
    init_fat(s);

866 867 868 869 870 871 872 873
    s->faked_sectors=s->first_sectors_number+s->sectors_per_fat*2;
    s->cluster_count=sector2cluster(s, s->sector_count);

    mapping = array_get_next(&(s->mapping));
    mapping->begin = 0;
    mapping->dir_index = 0;
    mapping->info.dir.parent_mapping_index = -1;
    mapping->first_mapping_index = -1;
874
    mapping->path = g_strdup(dirname);
875 876 877 878 879 880 881 882
    i = strlen(mapping->path);
    if (i > 0 && mapping->path[i - 1] == '/')
	mapping->path[i - 1] = '\0';
    mapping->mode = MODE_DIRECTORY;
    mapping->read_only = 0;
    s->path = mapping->path;

    for (i = 0, cluster = 0; i < s->mapping.next; i++) {
883
	/* MS-DOS expects the FAT to be 0 for the root directory
884 885 886 887 888 889 890 891 892 893
	 * (except for the media byte). */
	/* LATER TODO: still true for FAT32? */
	int fix_fat = (i != 0);
	mapping = array_get(&(s->mapping), i);

        if (mapping->mode & MODE_DIRECTORY) {
	    mapping->begin = cluster;
	    if(read_directory(s, i)) {
		fprintf(stderr, "Could not read directory %s\n",
			mapping->path);
894 895
		return -1;
	    }
896 897 898
	    mapping = array_get(&(s->mapping), i);
	} else {
	    assert(mapping->mode == MODE_UNDEFINED);
899
	    mapping->mode=MODE_NORMAL;
900 901
	    mapping->begin = cluster;
	    if (mapping->end > 0) {
A
Anthony Liguori 已提交
902
		direntry_t* direntry = array_get(&(s->directory),
903 904 905 906 907 908 909
			mapping->dir_index);

		mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;
		set_begin_of_direntry(direntry, mapping->begin);
	    } else {
		mapping->end = cluster + 1;
		fix_fat = 0;
910
	    }
911 912 913 914
	}

	assert(mapping->begin < mapping->end);

915 916 917 918 919 920 921 922 923 924 925 926
	/* next free cluster */
	cluster = mapping->end;

	if(cluster > s->cluster_count) {
	    fprintf(stderr,"Directory does not fit in FAT%d (capacity %s)\n",
		    s->fat_type,
		    s->fat_type == 12 ? s->sector_count == 2880 ? "1.44 MB"
								: "2.88 MB"
				      : "504MB");
	    return -EINVAL;
	}

927 928
	/* fix fat for entry */
	if (fix_fat) {
929
	    int j;
930 931 932 933
	    for(j = mapping->begin; j < mapping->end - 1; j++)
		fat_set(s, j, j+1);
	    fat_set(s, mapping->end - 1, s->max_fat_value);
	}
934 935
    }

936 937 938 939 940 941 942
    mapping = array_get(&(s->mapping), 0);
    s->sectors_of_root_directory = mapping->end * s->sectors_per_cluster;
    s->last_cluster_of_root_directory = mapping->end;

    /* the FAT signature */
    fat_set(s,0,s->max_fat_value);
    fat_set(s,1,s->max_fat_value);
943

944 945
    s->current_mapping = NULL;

A
Anthony Liguori 已提交
946
    bootsector=(bootsector_t*)(s->first_sectors+(s->first_sectors_number-1)*0x200);
947 948 949 950 951 952 953 954 955
    bootsector->jump[0]=0xeb;
    bootsector->jump[1]=0x3e;
    bootsector->jump[2]=0x90;
    memcpy(bootsector->name,"QEMU    ",8);
    bootsector->sector_size=cpu_to_le16(0x200);
    bootsector->sectors_per_cluster=s->sectors_per_cluster;
    bootsector->reserved_sectors=cpu_to_le16(1);
    bootsector->number_of_fats=0x2; /* number of FATs */
    bootsector->root_entries=cpu_to_le16(s->sectors_of_root_directory*0x10);
956 957 958
    bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
    bootsector->media_type=(s->fat_type!=12?0xf8:s->sector_count==5760?0xf9:0xf8); /* media descriptor */
    s->fat.pointer[0] = bootsector->media_type;
959
    bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
960 961
    bootsector->sectors_per_track=cpu_to_le16(s->bs->secs);
    bootsector->number_of_heads=cpu_to_le16(s->bs->heads);
962
    bootsector->hidden_sectors=cpu_to_le32(s->first_sectors_number==1?0:0x3f);
963
    bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
964

965 966
    /* LATER TODO: if FAT32, this is wrong */
    bootsector->u.fat16.drive_number=s->fat_type==12?0:0x80; /* assume this is hda (TODO) */
967 968 969 970 971 972 973 974 975 976 977
    bootsector->u.fat16.current_head=0;
    bootsector->u.fat16.signature=0x29;
    bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);

    memcpy(bootsector->u.fat16.volume_label,"QEMU VVFAT ",11);
    memcpy(bootsector->fat_type,(s->fat_type==12?"FAT12   ":s->fat_type==16?"FAT16   ":"FAT32   "),8);
    bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;

    return 0;
}

B
bellard 已提交
978
#ifdef DEBUG
979
static BDRVVVFATState *vvv = NULL;
B
bellard 已提交
980
#endif
981 982 983 984

static int enable_write_target(BDRVVVFATState *s);
static int is_consistent(BDRVVVFATState *s);

B
bellard 已提交
985
static int vvfat_open(BlockDriverState *bs, const char* dirname, int flags)
986 987
{
    BDRVVVFATState *s = bs->opaque;
988
    int floppy = 0;
989 990
    int i;

B
bellard 已提交
991
#ifdef DEBUG
992
    vvv = s;
B
bellard 已提交
993
#endif
994 995 996 997 998 999 1000 1001

DLOG(if (stderr == NULL) {
    stderr = fopen("vvfat.log", "a");
    setbuf(stderr, NULL);
})

    s->bs = bs;

1002
    s->fat_type=16;
1003 1004
    /* LATER TODO: if FAT32, adjust */
    s->sectors_per_cluster=0x10;
T
ths 已提交
1005 1006
    /* 504MB disk*/
    bs->cyls=1024; bs->heads=16; bs->secs=63;
1007 1008 1009 1010

    s->current_cluster=0xffffffff;

    s->first_sectors_number=0x40;
1011 1012 1013 1014 1015 1016
    /* read only is the default for safety */
    bs->read_only = 1;
    s->qcow = s->write_target = NULL;
    s->qcow_filename = NULL;
    s->fat2 = NULL;
    s->downcase_short_names = 1;
1017

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    if (!strstart(dirname, "fat:", NULL))
	return -1;

    if (strstr(dirname, ":floppy:")) {
	floppy = 1;
	s->fat_type = 12;
	s->first_sectors_number = 1;
	s->sectors_per_cluster=2;
	bs->cyls = 80; bs->heads = 2; bs->secs = 36;
    }

T
ths 已提交
1029 1030
    s->sector_count=bs->cyls*bs->heads*bs->secs;

1031 1032 1033 1034 1035 1036 1037 1038
    if (strstr(dirname, ":32:")) {
	fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. You are welcome to do so!\n");
	s->fat_type = 32;
    } else if (strstr(dirname, ":16:")) {
	s->fat_type = 16;
    } else if (strstr(dirname, ":12:")) {
	s->fat_type = 12;
	s->sector_count=2880;
1039
    }
1040

T
ths 已提交
1041 1042 1043 1044 1045 1046
    if (strstr(dirname, ":rw:")) {
	if (enable_write_target(s))
	    return -1;
	bs->read_only = 0;
    }

1047 1048
    i = strrchr(dirname, ':') - dirname;
    assert(i >= 3);
1049
    if (dirname[i-2] == ':' && qemu_isalpha(dirname[i-1]))
1050 1051 1052 1053 1054 1055
	/* workaround for DOS drive names */
	dirname += i-1;
    else
	dirname += i+1;

    bs->total_sectors=bs->cyls*bs->heads*bs->secs;
T
ths 已提交
1056

1057
    if(init_directories(s, dirname))
1058 1059
	return -1;

T
ths 已提交
1060 1061
    s->sector_count = s->faked_sectors + s->sectors_per_cluster*s->cluster_count;

1062 1063 1064
    if(s->first_sectors_number==0x40)
	init_mbr(s);

1065 1066 1067 1068 1069
    /* for some reason or other, MS-DOS does not like to know about CHS... */
    if (floppy)
	bs->heads = bs->cyls = bs->secs = 0;

    //    assert(is_consistent(s));
1070
    qemu_co_mutex_init(&s->lock);
1071 1072 1073 1074 1075 1076
    return 0;
}

static inline void vvfat_close_current_file(BDRVVVFATState *s)
{
    if(s->current_mapping) {
1077 1078 1079 1080 1081
	s->current_mapping = NULL;
	if (s->current_fd) {
		close(s->current_fd);
		s->current_fd = 0;
	}
1082
    }
1083
    s->current_cluster = -1;
1084 1085 1086 1087 1088 1089 1090 1091
}

/* mappings between index1 and index2-1 are supposed to be ordered
 * return value is the index of the last mapping for which end>cluster_num
 */
static inline int find_mapping_for_cluster_aux(BDRVVVFATState* s,int cluster_num,int index1,int index2)
{
    while(1) {
1092
        int index3;
A
Anthony Liguori 已提交
1093
	mapping_t* mapping;
1094 1095
	index3=(index1+index2)/2;
	mapping=array_get(&(s->mapping),index3);
1096 1097
	assert(mapping->begin < mapping->end);
	if(mapping->begin>=cluster_num) {
1098 1099
	    assert(index2!=index3 || index2==0);
	    if(index2==index3)
1100
		return index1;
1101 1102 1103
	    index2=index3;
	} else {
	    if(index1==index3)
1104
		return mapping->end<=cluster_num ? index2 : index1;
1105 1106 1107
	    index1=index3;
	}
	assert(index1<=index2);
1108 1109
	DLOG(mapping=array_get(&(s->mapping),index1);
	assert(mapping->begin<=cluster_num);
1110
	assert(index2 >= s->mapping.next ||
1111 1112
		((mapping = array_get(&(s->mapping),index2)) &&
		mapping->end>cluster_num)));
1113 1114 1115
    }
}

A
Anthony Liguori 已提交
1116
static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_num)
1117 1118
{
    int index=find_mapping_for_cluster_aux(s,cluster_num,0,s->mapping.next);
A
Anthony Liguori 已提交
1119
    mapping_t* mapping;
1120
    if(index>=s->mapping.next)
1121
        return NULL;
1122 1123
    mapping=array_get(&(s->mapping),index);
    if(mapping->begin>cluster_num)
1124
        return NULL;
1125
    assert(mapping->begin<=cluster_num && mapping->end>cluster_num);
1126 1127 1128
    return mapping;
}

A
Anthony Liguori 已提交
1129
static int open_file(BDRVVVFATState* s,mapping_t* mapping)
1130 1131 1132 1133
{
    if(!mapping)
	return -1;
    if(!s->current_mapping ||
1134
	    strcmp(s->current_mapping->path,mapping->path)) {
1135
	/* open file */
1136
	int fd = open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
	if(fd<0)
	    return -1;
	vvfat_close_current_file(s);
	s->current_fd = fd;
	s->current_mapping = mapping;
    }
    return 0;
}

static inline int read_cluster(BDRVVVFATState *s,int cluster_num)
{
    if(s->current_cluster != cluster_num) {
	int result=0;
	off_t offset;
1151
	assert(!s->current_mapping || s->current_fd || (s->current_mapping->mode & MODE_DIRECTORY));
1152 1153 1154 1155
	if(!s->current_mapping
		|| s->current_mapping->begin>cluster_num
		|| s->current_mapping->end<=cluster_num) {
	    /* binary search of mappings for file */
A
Anthony Liguori 已提交
1156
	    mapping_t* mapping=find_mapping_for_cluster(s,cluster_num);
1157 1158 1159 1160 1161 1162 1163 1164

	    assert(!mapping || (cluster_num>=mapping->begin && cluster_num<mapping->end));

	    if (mapping && mapping->mode & MODE_DIRECTORY) {
		vvfat_close_current_file(s);
		s->current_mapping = mapping;
read_cluster_directory:
		offset = s->cluster_size*(cluster_num-s->current_mapping->begin);
T
ths 已提交
1165
		s->cluster = (unsigned char*)s->directory.pointer+offset
1166 1167 1168 1169 1170 1171 1172 1173
			+ 0x20*s->current_mapping->info.dir.first_dir_index;
		assert(((s->cluster-(unsigned char*)s->directory.pointer)%s->cluster_size)==0);
		assert((char*)s->cluster+s->cluster_size <= s->directory.pointer+s->directory.next*s->directory.item_size);
		s->current_cluster = cluster_num;
		return 0;
	    }

	    if(open_file(s,mapping))
1174
		return -2;
1175 1176
	} else if (s->current_mapping->mode & MODE_DIRECTORY)
	    goto read_cluster_directory;
1177

1178 1179 1180
	assert(s->current_fd);

	offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset;
1181 1182
	if(lseek(s->current_fd, offset, SEEK_SET)!=offset)
	    return -3;
1183
	s->cluster=s->cluster_buffer;
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
	result=read(s->current_fd,s->cluster,s->cluster_size);
	if(result<0) {
	    s->current_cluster = -1;
	    return -1;
	}
	s->current_cluster = cluster_num;
    }
    return 0;
}

1194
#ifdef DEBUG
A
Anthony Liguori 已提交
1195
static void print_direntry(const direntry_t* direntry)
1196
{
1197 1198 1199
    int j = 0;
    char buffer[1024];

K
Kevin Wolf 已提交
1200
    fprintf(stderr, "direntry %p: ", direntry);
1201 1202
    if(!direntry)
	return;
1203
    if(is_long_name(direntry)) {
1204 1205 1206
	unsigned char* c=(unsigned char*)direntry;
	int i;
	for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)
1207
#define ADD_CHAR(c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;}
1208
	    ADD_CHAR(c[i]);
1209
	for(i=14;i<26 && c[i] && c[i]!=0xff;i+=2)
1210
	    ADD_CHAR(c[i]);
1211
	for(i=28;i<32 && c[i] && c[i]!=0xff;i+=2)
1212 1213 1214
	    ADD_CHAR(c[i]);
	buffer[j] = 0;
	fprintf(stderr, "%s\n", buffer);
1215 1216 1217
    } else {
	int i;
	for(i=0;i<11;i++)
1218 1219 1220 1221
	    ADD_CHAR(direntry->name[i]);
	buffer[j] = 0;
	fprintf(stderr,"%s attributes=0x%02x begin=%d size=%d\n",
		buffer,
1222
		direntry->attributes,
1223
		begin_of_direntry(direntry),le32_to_cpu(direntry->size));
1224 1225 1226
    }
}

A
Anthony Liguori 已提交
1227
static void print_mapping(const mapping_t* mapping)
1228
{
K
Kevin Wolf 已提交
1229 1230 1231 1232 1233
    fprintf(stderr, "mapping (%p): begin, end = %d, %d, dir_index = %d, "
        "first_mapping_index = %d, name = %s, mode = 0x%x, " ,
        mapping, mapping->begin, mapping->end, mapping->dir_index,
        mapping->first_mapping_index, mapping->path, mapping->mode);

1234 1235 1236 1237
    if (mapping->mode & MODE_DIRECTORY)
	fprintf(stderr, "parent_mapping_index = %d, first_dir_index = %d\n", mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);
    else
	fprintf(stderr, "offset = %d\n", mapping->info.file.offset);
1238
}
1239
#endif
1240

1241
static int vvfat_read(BlockDriverState *bs, int64_t sector_num,
1242
                    uint8_t *buf, int nb_sectors)
1243
{
1244
    BDRVVVFATState *s = bs->opaque;
1245 1246
    int i;

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    for(i=0;i<nb_sectors;i++,sector_num++) {
	if (sector_num >= s->sector_count)
	   return -1;
	if (s->qcow) {
	    int n;
	    if (s->qcow->drv->bdrv_is_allocated(s->qcow,
			sector_num, nb_sectors-i, &n)) {
DLOG(fprintf(stderr, "sectors %d+%d allocated\n", (int)sector_num, n));
		if (s->qcow->drv->bdrv_read(s->qcow, sector_num, buf+i*0x200, n))
		    return -1;
		i += n - 1;
		sector_num += n - 1;
		continue;
	    }
DLOG(fprintf(stderr, "sector %d not allocated\n", (int)sector_num));
1262
	}
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
	if(sector_num<s->faked_sectors) {
	    if(sector_num<s->first_sectors_number)
		memcpy(buf+i*0x200,&(s->first_sectors[sector_num*0x200]),0x200);
	    else if(sector_num-s->first_sectors_number<s->sectors_per_fat)
		memcpy(buf+i*0x200,&(s->fat.pointer[(sector_num-s->first_sectors_number)*0x200]),0x200);
	    else if(sector_num-s->first_sectors_number-s->sectors_per_fat<s->sectors_per_fat)
		memcpy(buf+i*0x200,&(s->fat.pointer[(sector_num-s->first_sectors_number-s->sectors_per_fat)*0x200]),0x200);
	} else {
	    uint32_t sector=sector_num-s->faked_sectors,
	    sector_offset_in_cluster=(sector%s->sectors_per_cluster),
	    cluster_num=sector/s->sectors_per_cluster;
	    if(read_cluster(s, cluster_num) != 0) {
		/* LATER TODO: strict: return -1; */
		memset(buf+i*0x200,0,0x200);
		continue;
1278
	    }
1279
	    memcpy(buf+i*0x200,s->cluster+sector_offset_in_cluster*0x200,0x200);
1280 1281 1282 1283 1284
	}
    }
    return 0;
}

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
static coroutine_fn int vvfat_co_read(BlockDriverState *bs, int64_t sector_num,
                                      uint8_t *buf, int nb_sectors)
{
    int ret;
    BDRVVVFATState *s = bs->opaque;
    qemu_co_mutex_lock(&s->lock);
    ret = vvfat_read(bs, sector_num, buf, nb_sectors);
    qemu_co_mutex_unlock(&s->lock);
    return ret;
}

1296
/* LATER TODO: statify all functions */
1297

1298 1299
/*
 * Idea of the write support (use snapshot):
1300
 *
1301 1302
 * 1. check if all data is consistent, recording renames, modifications,
 *    new files and directories (in s->commits).
1303
 *
1304
 * 2. if the data is not consistent, stop committing
1305
 *
1306 1307
 * 3. handle renames, and create new files and directories (do not yet
 *    write their contents)
1308
 *
1309 1310
 * 4. walk the directories, fixing the mapping and direntries, and marking
 *    the handled mappings as not deleted
1311
 *
1312
 * 5. commit the contents of the files
1313
 *
1314
 * 6. handle deleted files and directories
1315 1316 1317
 *
 */

A
Anthony Liguori 已提交
1318
typedef struct commit_t {
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
    char* path;
    union {
	struct { uint32_t cluster; } rename;
	struct { int dir_index; uint32_t modified_offset; } writeout;
	struct { uint32_t first_cluster; } new_file;
	struct { uint32_t cluster; } mkdir;
    } param;
    /* DELETEs and RMDIRs are handled differently: see handle_deletes() */
    enum {
	ACTION_RENAME, ACTION_WRITEOUT, ACTION_NEW_FILE, ACTION_MKDIR
    } action;
A
Anthony Liguori 已提交
1330
} commit_t;
1331

1332
static void clear_commits(BDRVVVFATState* s)
1333 1334
{
    int i;
1335 1336
DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));
    for (i = 0; i < s->commits.next; i++) {
A
Anthony Liguori 已提交
1337
	commit_t* commit = array_get(&(s->commits), i);
1338 1339 1340
	assert(commit->path || commit->action == ACTION_WRITEOUT);
	if (commit->action != ACTION_WRITEOUT) {
	    assert(commit->path);
1341
            g_free(commit->path);
1342 1343
	} else
	    assert(commit->path == NULL);
1344
    }
1345
    s->commits.next = 0;
1346 1347
}

1348 1349
static void schedule_rename(BDRVVVFATState* s,
	uint32_t cluster, char* new_path)
1350
{
A
Anthony Liguori 已提交
1351
    commit_t* commit = array_get_next(&(s->commits));
1352 1353 1354
    commit->path = new_path;
    commit->param.rename.cluster = cluster;
    commit->action = ACTION_RENAME;
1355 1356
}

1357 1358
static void schedule_writeout(BDRVVVFATState* s,
	int dir_index, uint32_t modified_offset)
1359
{
A
Anthony Liguori 已提交
1360
    commit_t* commit = array_get_next(&(s->commits));
1361 1362 1363 1364
    commit->path = NULL;
    commit->param.writeout.dir_index = dir_index;
    commit->param.writeout.modified_offset = modified_offset;
    commit->action = ACTION_WRITEOUT;
1365 1366
}

1367 1368
static void schedule_new_file(BDRVVVFATState* s,
	char* path, uint32_t first_cluster)
1369
{
A
Anthony Liguori 已提交
1370
    commit_t* commit = array_get_next(&(s->commits));
1371 1372 1373 1374 1375 1376 1377
    commit->path = path;
    commit->param.new_file.first_cluster = first_cluster;
    commit->action = ACTION_NEW_FILE;
}

static void schedule_mkdir(BDRVVVFATState* s, uint32_t cluster, char* path)
{
A
Anthony Liguori 已提交
1378
    commit_t* commit = array_get_next(&(s->commits));
1379 1380 1381 1382 1383 1384
    commit->path = path;
    commit->param.mkdir.cluster = cluster;
    commit->action = ACTION_MKDIR;
}

typedef struct {
1385 1386 1387 1388 1389 1390
    /*
     * Since the sequence number is at most 0x3f, and the filename
     * length is at most 13 times the sequence number, the maximal
     * filename length is 0x3f * 13 bytes.
     */
    unsigned char name[0x3f * 13 + 1];
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
    int checksum, len;
    int sequence_number;
} long_file_name;

static void lfn_init(long_file_name* lfn)
{
   lfn->sequence_number = lfn->len = 0;
   lfn->checksum = 0x100;
}

/* return 0 if parsed successfully, > 0 if no long name, < 0 if error */
static int parse_long_name(long_file_name* lfn,
A
Anthony Liguori 已提交
1403
	const direntry_t* direntry)
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
{
    int i, j, offset;
    const unsigned char* pointer = (const unsigned char*)direntry;

    if (!is_long_name(direntry))
	return 1;

    if (pointer[0] & 0x40) {
	lfn->sequence_number = pointer[0] & 0x3f;
	lfn->checksum = pointer[13];
	lfn->name[0] = 0;
T
ths 已提交
1415
	lfn->name[lfn->sequence_number * 13] = 0;
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    } else if ((pointer[0] & 0x3f) != --lfn->sequence_number)
	return -1;
    else if (pointer[13] != lfn->checksum)
	return -2;
    else if (pointer[12] || pointer[26] || pointer[27])
	return -3;

    offset = 13 * (lfn->sequence_number - 1);
    for (i = 0, j = 1; i < 13; i++, j+=2) {
	if (j == 11)
	    j = 14;
	else if (j == 26)
	    j = 28;

	if (pointer[j+1] == 0)
	    lfn->name[offset + i] = pointer[j];
	else if (pointer[j+1] != 0xff || (pointer[0] & 0x40) == 0)
	    return -4;
	else
	    lfn->name[offset + i] = 0;
1436
    }
1437 1438

    if (pointer[0] & 0x40)
T
ths 已提交
1439
	lfn->len = offset + strlen((char*)lfn->name + offset);
1440

1441 1442 1443
    return 0;
}

1444 1445
/* returns 0 if successful, >0 if no short_name, and <0 on error */
static int parse_short_name(BDRVVVFATState* s,
A
Anthony Liguori 已提交
1446
	long_file_name* lfn, direntry_t* direntry)
1447
{
1448
    int i, j;
1449

1450 1451 1452 1453 1454 1455 1456 1457
    if (!is_short_name(direntry))
	return 1;

    for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);
    for (i = 0; i <= j; i++) {
	if (direntry->name[i] <= ' ' || direntry->name[i] > 0x7f)
	    return -1;
	else if (s->downcase_short_names)
1458
	    lfn->name[i] = qemu_tolower(direntry->name[i]);
1459 1460
	else
	    lfn->name[i] = direntry->name[i];
1461 1462
    }

1463 1464 1465 1466 1467 1468 1469 1470
    for (j = 2; j >= 0 && direntry->extension[j] == ' '; j--);
    if (j >= 0) {
	lfn->name[i++] = '.';
	lfn->name[i + j + 1] = '\0';
	for (;j >= 0; j--) {
	    if (direntry->extension[j] <= ' ' || direntry->extension[j] > 0x7f)
		return -2;
	    else if (s->downcase_short_names)
1471
		lfn->name[i + j] = qemu_tolower(direntry->extension[j]);
1472 1473 1474 1475 1476 1477
	    else
		lfn->name[i + j] = direntry->extension[j];
	}
    } else
	lfn->name[i + j + 1] = '\0';

T
ths 已提交
1478
    lfn->len = strlen((char*)lfn->name);
1479 1480

    return 0;
1481 1482
}

1483 1484
static inline uint32_t modified_fat_get(BDRVVVFATState* s,
	unsigned int cluster)
1485
{
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    if (cluster < s->last_cluster_of_root_directory) {
	if (cluster + 1 == s->last_cluster_of_root_directory)
	    return s->max_fat_value;
	else
	    return cluster + 1;
    }

    if (s->fat_type==32) {
        uint32_t* entry=((uint32_t*)s->fat2)+cluster;
        return le32_to_cpu(*entry);
    } else if (s->fat_type==16) {
        uint16_t* entry=((uint16_t*)s->fat2)+cluster;
        return le16_to_cpu(*entry);
    } else {
        const uint8_t* x=s->fat2+cluster*3/2;
        return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
    }
}

static inline int cluster_was_modified(BDRVVVFATState* s, uint32_t cluster_num)
{
    int was_modified = 0;
    int i, dummy;

    if (s->qcow == NULL)
1511
	return 0;
1512 1513 1514 1515 1516 1517

    for (i = 0; !was_modified && i < s->sectors_per_cluster; i++)
	was_modified = s->qcow->drv->bdrv_is_allocated(s->qcow,
		cluster2sector(s, cluster_num) + i, 1, &dummy);

    return was_modified;
1518 1519
}

1520
static const char* get_basename(const char* path)
1521
{
1522 1523 1524 1525 1526
    char* basename = strrchr(path, '/');
    if (basename == NULL)
	return path;
    else
	return basename + 1; /* strip '/' */
1527 1528
}

1529 1530 1531 1532 1533 1534 1535 1536 1537
/*
 * The array s->used_clusters holds the states of the clusters. If it is
 * part of a file, it has bit 2 set, in case of a directory, bit 1. If it
 * was modified, bit 3 is set.
 * If any cluster is allocated, but not part of a file or directory, this
 * driver refuses to commit.
 */
typedef enum {
     USED_DIRECTORY = 1, USED_FILE = 2, USED_ANY = 3, USED_ALLOCATED = 4
A
Anthony Liguori 已提交
1538
} used_t;
1539

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
/*
 * get_cluster_count_for_direntry() not only determines how many clusters
 * are occupied by direntry, but also if it was renamed or modified.
 *
 * A file is thought to be renamed *only* if there already was a file with
 * exactly the same first cluster, but a different name.
 *
 * Further, the files/directories handled by this function are
 * assumed to be *not* deleted (and *only* those).
 */
static uint32_t get_cluster_count_for_direntry(BDRVVVFATState* s,
A
Anthony Liguori 已提交
1551
	direntry_t* direntry, const char* path)
1552
{
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    /*
     * This is a little bit tricky:
     * IF the guest OS just inserts a cluster into the file chain,
     * and leaves the rest alone, (i.e. the original file had clusters
     * 15 -> 16, but now has 15 -> 32 -> 16), then the following happens:
     *
     * - do_commit will write the cluster into the file at the given
     *   offset, but
     *
     * - the cluster which is overwritten should be moved to a later
     *   position in the file.
     *
     * I am not aware that any OS does something as braindead, but this
     * situation could happen anyway when not committing for a long time.
     * Just to be sure that this does not bite us, detect it, and copy the
     * contents of the clusters to-be-overwritten into the qcow.
     */
    int copy_it = 0;
    int was_modified = 0;
    int32_t ret = 0;

    uint32_t cluster_num = begin_of_direntry(direntry);
    uint32_t offset = 0;
    int first_mapping_index = -1;
A
Anthony Liguori 已提交
1577
    mapping_t* mapping = NULL;
1578
    const char* basename2 = NULL;
1579

1580
    vvfat_close_current_file(s);
1581

1582 1583
    /* the root directory */
    if (cluster_num == 0)
1584 1585
	return 0;

1586 1587 1588
    /* write support */
    if (s->qcow) {
	basename2 = get_basename(path);
1589

1590 1591 1592
	mapping = find_mapping_for_cluster(s, cluster_num);

	if (mapping) {
B
bellard 已提交
1593 1594
	    const char* basename;

1595 1596 1597
	    assert(mapping->mode & MODE_DELETED);
	    mapping->mode &= ~MODE_DELETED;

B
bellard 已提交
1598
	    basename = get_basename(mapping->path);
1599 1600 1601 1602 1603

	    assert(mapping->mode & MODE_NORMAL);

	    /* rename */
	    if (strcmp(basename, basename2))
1604
		schedule_rename(s, cluster_num, g_strdup(path));
1605 1606
	} else if (is_file(direntry))
	    /* new file */
1607
	    schedule_new_file(s, g_strdup(path), cluster_num);
1608
	else {
1609
            abort();
1610 1611
	    return 0;
	}
1612 1613
    }

1614 1615 1616 1617 1618 1619 1620
    while(1) {
	if (s->qcow) {
	    if (!copy_it && cluster_was_modified(s, cluster_num)) {
		if (mapping == NULL ||
			mapping->begin > cluster_num ||
			mapping->end <= cluster_num)
		mapping = find_mapping_for_cluster(s, cluster_num);
1621

1622 1623 1624 1625 1626 1627 1628 1629

		if (mapping &&
			(mapping->mode & MODE_DIRECTORY) == 0) {

		    /* was modified in qcow */
		    if (offset != mapping->info.file.offset + s->cluster_size
			    * (cluster_num - mapping->begin)) {
			/* offset of this cluster in file chain has changed */
1630
                        abort();
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
			copy_it = 1;
		    } else if (offset == 0) {
			const char* basename = get_basename(mapping->path);

			if (strcmp(basename, basename2))
			    copy_it = 1;
			first_mapping_index = array_index(&(s->mapping), mapping);
		    }

		    if (mapping->first_mapping_index != first_mapping_index
			    && mapping->info.file.offset > 0) {
1642
                        abort();
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
			copy_it = 1;
		    }

		    /* need to write out? */
		    if (!was_modified && is_file(direntry)) {
			was_modified = 1;
			schedule_writeout(s, mapping->dir_index, offset);
		    }
		}
	    }

	    if (copy_it) {
		int i, dummy;
		/*
		 * This is horribly inefficient, but that is okay, since
		 * it is rarely executed, if at all.
		 */
		int64_t offset = cluster2sector(s, cluster_num);

		vvfat_close_current_file(s);
		for (i = 0; i < s->sectors_per_cluster; i++)
		    if (!s->qcow->drv->bdrv_is_allocated(s->qcow,
				offset + i, 1, &dummy)) {
			if (vvfat_read(s->bs,
				    offset, s->cluster_buffer, 1))
			    return -1;
			if (s->qcow->drv->bdrv_write(s->qcow,
				    offset, s->cluster_buffer, 1))
			    return -2;
		    }
	    }
	}

	ret++;
	if (s->used_clusters[cluster_num] & USED_ANY)
	    return 0;
	s->used_clusters[cluster_num] = USED_FILE;

	cluster_num = modified_fat_get(s, cluster_num);

	if (fat_eof(s, cluster_num))
	    return ret;
	else if (cluster_num < 2 || cluster_num > s->max_fat_value - 16)
	    return -1;

	offset += s->cluster_size;
    }
1690 1691
}

1692
/*
1693
 * This function looks at the modified data (qcow).
1694 1695 1696 1697 1698
 * It returns 0 upon inconsistency or error, and the number of clusters
 * used by the directory, its subdirectories and their files.
 */
static int check_directory_consistency(BDRVVVFATState *s,
	int cluster_num, const char* path)
1699
{
1700
    int ret = 0;
1701
    unsigned char* cluster = g_malloc(s->cluster_size);
A
Anthony Liguori 已提交
1702 1703
    direntry_t* direntries = (direntry_t*)cluster;
    mapping_t* mapping = find_mapping_for_cluster(s, cluster_num);
1704 1705 1706

    long_file_name lfn;
    int path_len = strlen(path);
K
Kevin Wolf 已提交
1707
    char path2[PATH_MAX + 1];
1708 1709

    assert(path_len < PATH_MAX); /* len was tested before! */
B
blueswir1 已提交
1710
    pstrcpy(path2, sizeof(path2), path);
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    path2[path_len] = '/';
    path2[path_len + 1] = '\0';

    if (mapping) {
	const char* basename = get_basename(mapping->path);
	const char* basename2 = get_basename(path);

	assert(mapping->mode & MODE_DIRECTORY);

	assert(mapping->mode & MODE_DELETED);
	mapping->mode &= ~MODE_DELETED;

	if (strcmp(basename, basename2))
1724
	    schedule_rename(s, cluster_num, g_strdup(path));
1725 1726
    } else
	/* new directory */
1727
	schedule_mkdir(s, cluster_num, g_strdup(path));
1728

1729 1730
    lfn_init(&lfn);
    do {
1731
	int i;
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
	int subret = 0;

	ret++;

	if (s->used_clusters[cluster_num] & USED_ANY) {
	    fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num);
	    return 0;
	}
	s->used_clusters[cluster_num] = USED_DIRECTORY;

DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num)));
	subret = vvfat_read(s->bs, cluster2sector(s, cluster_num), cluster,
		s->sectors_per_cluster);
	if (subret) {
	    fprintf(stderr, "Error fetching direntries\n");
	fail:
1748
            g_free(cluster);
1749 1750 1751 1752
	    return 0;
	}

	for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) {
1753
	    int cluster_count = 0;
1754

1755
DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i));
1756 1757 1758 1759 1760 1761 1762 1763
	    if (is_volume_label(direntries + i) || is_dot(direntries + i) ||
		    is_free(direntries + i))
		continue;

	    subret = parse_long_name(&lfn, direntries + i);
	    if (subret < 0) {
		fprintf(stderr, "Error in long name\n");
		goto fail;
1764
	    }
1765 1766 1767 1768 1769 1770 1771 1772 1773
	    if (subret == 0 || is_free(direntries + i))
		continue;

	    if (fat_chksum(direntries+i) != lfn.checksum) {
		subret = parse_short_name(s, &lfn, direntries + i);
		if (subret < 0) {
		    fprintf(stderr, "Error in short name (%d)\n", subret);
		    goto fail;
		}
T
ths 已提交
1774 1775
		if (subret > 0 || !strcmp((char*)lfn.name, ".")
			|| !strcmp((char*)lfn.name, ".."))
1776 1777 1778 1779 1780 1781 1782 1783
		    continue;
	    }
	    lfn.checksum = 0x100; /* cannot use long name twice */

	    if (path_len + 1 + lfn.len >= PATH_MAX) {
		fprintf(stderr, "Name too long: %s/%s\n", path, lfn.name);
		goto fail;
	    }
B
blueswir1 已提交
1784 1785
            pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1,
                    (char*)lfn.name);
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

	    if (is_directory(direntries + i)) {
		if (begin_of_direntry(direntries + i) == 0) {
		    DLOG(fprintf(stderr, "invalid begin for directory: %s\n", path2); print_direntry(direntries + i));
		    goto fail;
		}
		cluster_count = check_directory_consistency(s,
			begin_of_direntry(direntries + i), path2);
		if (cluster_count == 0) {
		    DLOG(fprintf(stderr, "problem in directory %s:\n", path2); print_direntry(direntries + i));
		    goto fail;
		}
	    } else if (is_file(direntries + i)) {
		/* check file size with FAT */
		cluster_count = get_cluster_count_for_direntry(s, direntries + i, path2);
		if (cluster_count !=
			(le32_to_cpu(direntries[i].size) + s->cluster_size
			 - 1) / s->cluster_size) {
		    DLOG(fprintf(stderr, "Cluster count mismatch\n"));
		    goto fail;
		}
	    } else
1808
                abort(); /* cluster_count = 0; */
1809 1810

	    ret += cluster_count;
1811 1812
	}

1813 1814
	cluster_num = modified_fat_get(s, cluster_num);
    } while(!fat_eof(s, cluster_num));
1815

1816
    g_free(cluster);
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
    return ret;
}

/* returns 1 on success */
static int is_consistent(BDRVVVFATState* s)
{
    int i, check;
    int used_clusters_count = 0;

DLOG(checkpoint());
    /*
     * - get modified FAT
     * - compare the two FATs (TODO)
     * - get buffer for marking used clusters
     * - recurse direntries from root (using bs->bdrv_read to make
     *    sure to get the new data)
     *   - check that the FAT agrees with the size
     *   - count the number of clusters occupied by this directory and
     *     its files
     * - check that the cumulative used cluster count agrees with the
     *   FAT
     * - if all is fine, return number of used clusters
     */
    if (s->fat2 == NULL) {
	int size = 0x200 * s->sectors_per_fat;
1842
	s->fat2 = g_malloc(size);
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
	memcpy(s->fat2, s->fat.pointer, size);
    }
    check = vvfat_read(s->bs,
	    s->first_sectors_number, s->fat2, s->sectors_per_fat);
    if (check) {
	fprintf(stderr, "Could not copy fat\n");
	return 0;
    }
    assert (s->used_clusters);
    for (i = 0; i < sector2cluster(s, s->sector_count); i++)
	s->used_clusters[i] &= ~USED_ANY;

    clear_commits(s);

    /* mark every mapped file/directory as deleted.
     * (check_directory_consistency() will unmark those still present). */
    if (s->qcow)
	for (i = 0; i < s->mapping.next; i++) {
A
Anthony Liguori 已提交
1861
	    mapping_t* mapping = array_get(&(s->mapping), i);
1862 1863
	    if (mapping->first_mapping_index < 0)
		mapping->mode |= MODE_DELETED;
1864
	}
1865 1866 1867 1868 1869

    used_clusters_count = check_directory_consistency(s, 0, s->path);
    if (used_clusters_count <= 0) {
	DLOG(fprintf(stderr, "problem in directory\n"));
	return 0;
1870 1871
    }

1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
    check = s->last_cluster_of_root_directory;
    for (i = check; i < sector2cluster(s, s->sector_count); i++) {
	if (modified_fat_get(s, i)) {
	    if(!s->used_clusters[i]) {
		DLOG(fprintf(stderr, "FAT was modified (%d), but cluster is not used?\n", i));
		return 0;
	    }
	    check++;
	}

	if (s->used_clusters[i] == USED_ALLOCATED) {
	    /* allocated, but not used... */
	    DLOG(fprintf(stderr, "unused, modified cluster: %d\n", i));
	    return 0;
	}
    }

    if (check != used_clusters_count)
	return 0;

    return used_clusters_count;
}

static inline void adjust_mapping_indices(BDRVVVFATState* s,
	int offset, int adjust)
{
    int i;

    for (i = 0; i < s->mapping.next; i++) {
A
Anthony Liguori 已提交
1901
	mapping_t* mapping = array_get(&(s->mapping), i);
1902 1903 1904 1905 1906 1907 1908 1909

#define ADJUST_MAPPING_INDEX(name) \
	if (mapping->name >= offset) \
	    mapping->name += adjust

	ADJUST_MAPPING_INDEX(first_mapping_index);
	if (mapping->mode & MODE_DIRECTORY)
	    ADJUST_MAPPING_INDEX(info.dir.parent_mapping_index);
1910
    }
1911 1912 1913
}

/* insert or update mapping */
A
Anthony Liguori 已提交
1914
static mapping_t* insert_mapping(BDRVVVFATState* s,
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
	uint32_t begin, uint32_t end)
{
    /*
     * - find mapping where mapping->begin >= begin,
     * - if mapping->begin > begin: insert
     *   - adjust all references to mappings!
     * - else: adjust
     * - replace name
     */
    int index = find_mapping_for_cluster_aux(s, begin, 0, s->mapping.next);
A
Anthony Liguori 已提交
1925 1926
    mapping_t* mapping = NULL;
    mapping_t* first_mapping = array_get(&(s->mapping), 0);
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941

    if (index < s->mapping.next && (mapping = array_get(&(s->mapping), index))
	    && mapping->begin < begin) {
	mapping->end = begin;
	index++;
	mapping = array_get(&(s->mapping), index);
    }
    if (index >= s->mapping.next || mapping->begin > begin) {
	mapping = array_insert(&(s->mapping), index, 1);
	mapping->path = NULL;
	adjust_mapping_indices(s, index, +1);
    }

    mapping->begin = begin;
    mapping->end = end;
1942

A
Anthony Liguori 已提交
1943
DLOG(mapping_t* next_mapping;
1944 1945 1946 1947
assert(index + 1 >= s->mapping.next ||
((next_mapping = array_get(&(s->mapping), index + 1)) &&
 next_mapping->begin >= end)));

A
Anthony Liguori 已提交
1948
    if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
1949 1950 1951 1952 1953 1954 1955 1956
	s->current_mapping = array_get(&(s->mapping),
		s->current_mapping - first_mapping);

    return mapping;
}

static int remove_mapping(BDRVVVFATState* s, int mapping_index)
{
A
Anthony Liguori 已提交
1957 1958
    mapping_t* mapping = array_get(&(s->mapping), mapping_index);
    mapping_t* first_mapping = array_get(&(s->mapping), 0);
1959 1960

    /* free mapping */
1961 1962 1963
    if (mapping->first_mapping_index < 0) {
        g_free(mapping->path);
    }
1964 1965 1966 1967 1968 1969 1970

    /* remove from s->mapping */
    array_remove(&(s->mapping), mapping_index);

    /* adjust all references to mappings */
    adjust_mapping_indices(s, mapping_index, -1);

A
Anthony Liguori 已提交
1971
    if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
1972 1973
	s->current_mapping = array_get(&(s->mapping),
		s->current_mapping - first_mapping);
1974 1975 1976 1977

    return 0;
}

1978 1979 1980 1981
static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust)
{
    int i;
    for (i = 0; i < s->mapping.next; i++) {
A
Anthony Liguori 已提交
1982
	mapping_t* mapping = array_get(&(s->mapping), i);
1983 1984 1985 1986 1987 1988 1989
	if (mapping->dir_index >= offset)
	    mapping->dir_index += adjust;
	if ((mapping->mode & MODE_DIRECTORY) &&
		mapping->info.dir.first_dir_index >= offset)
	    mapping->info.dir.first_dir_index += adjust;
    }
}
1990

A
Anthony Liguori 已提交
1991
static direntry_t* insert_direntries(BDRVVVFATState* s,
1992
	int dir_index, int count)
1993
{
1994 1995 1996 1997
    /*
     * make room in s->directory,
     * adjust_dirindices
     */
A
Anthony Liguori 已提交
1998
    direntry_t* result = array_insert(&(s->directory), dir_index, count);
1999 2000 2001
    if (result == NULL)
	return NULL;
    adjust_dirindices(s, dir_index, count);
2002 2003 2004
    return result;
}

2005 2006 2007 2008 2009 2010 2011 2012
static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)
{
    int ret = array_remove_slice(&(s->directory), dir_index, count);
    if (ret)
	return ret;
    adjust_dirindices(s, dir_index, -count);
    return 0;
}
2013

2014 2015 2016 2017 2018 2019 2020 2021
/*
 * Adapt the mappings of the cluster chain starting at first cluster
 * (i.e. if a file starts at first_cluster, the chain is followed according
 * to the modified fat, and the corresponding entries in s->mapping are
 * adjusted)
 */
static int commit_mappings(BDRVVVFATState* s,
	uint32_t first_cluster, int dir_index)
2022
{
A
Anthony Liguori 已提交
2023 2024
    mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
    direntry_t* direntry = array_get(&(s->directory), dir_index);
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
    uint32_t cluster = first_cluster;

    vvfat_close_current_file(s);

    assert(mapping);
    assert(mapping->begin == first_cluster);
    mapping->first_mapping_index = -1;
    mapping->dir_index = dir_index;
    mapping->mode = (dir_index <= 0 || is_directory(direntry)) ?
	MODE_DIRECTORY : MODE_NORMAL;

    while (!fat_eof(s, cluster)) {
	uint32_t c, c1;

	for (c = cluster, c1 = modified_fat_get(s, c); c + 1 == c1;
		c = c1, c1 = modified_fat_get(s, c1));

	c++;
	if (c > mapping->end) {
	    int index = array_index(&(s->mapping), mapping);
	    int i, max_i = s->mapping.next - index;
	    for (i = 1; i < max_i && mapping[i].begin < c; i++);
	    while (--i > 0)
		remove_mapping(s, index + 1);
	}
	assert(mapping == array_get(&(s->mapping), s->mapping.next - 1)
		|| mapping[1].begin >= c);
	mapping->end = c;

	if (!fat_eof(s, c1)) {
	    int i = find_mapping_for_cluster_aux(s, c1, 0, s->mapping.next);
A
Anthony Liguori 已提交
2056
	    mapping_t* next_mapping = i >= s->mapping.next ? NULL :
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
		array_get(&(s->mapping), i);

	    if (next_mapping == NULL || next_mapping->begin > c1) {
		int i1 = array_index(&(s->mapping), mapping);

		next_mapping = insert_mapping(s, c1, c1+1);

		if (c1 < c)
		    i1++;
		mapping = array_get(&(s->mapping), i1);
	    }

	    next_mapping->dir_index = mapping->dir_index;
2070
	    next_mapping->first_mapping_index =
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
		mapping->first_mapping_index < 0 ?
		array_index(&(s->mapping), mapping) :
		mapping->first_mapping_index;
	    next_mapping->path = mapping->path;
	    next_mapping->mode = mapping->mode;
	    next_mapping->read_only = mapping->read_only;
	    if (mapping->mode & MODE_DIRECTORY) {
		next_mapping->info.dir.parent_mapping_index =
			mapping->info.dir.parent_mapping_index;
		next_mapping->info.dir.first_dir_index =
			mapping->info.dir.first_dir_index +
			0x10 * s->sectors_per_cluster *
			(mapping->end - mapping->begin);
	    } else
		next_mapping->info.file.offset = mapping->info.file.offset +
			mapping->end - mapping->begin;

	    mapping = next_mapping;
	}
2090

2091 2092
	cluster = c1;
    }
2093 2094 2095 2096

    return 0;
}

2097 2098
static int commit_direntries(BDRVVVFATState* s,
	int dir_index, int parent_mapping_index)
2099
{
A
Anthony Liguori 已提交
2100
    direntry_t* direntry = array_get(&(s->directory), dir_index);
2101
    uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);
A
Anthony Liguori 已提交
2102
    mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128

    int factor = 0x10 * s->sectors_per_cluster;
    int old_cluster_count, new_cluster_count;
    int current_dir_index = mapping->info.dir.first_dir_index;
    int first_dir_index = current_dir_index;
    int ret, i;
    uint32_t c;

DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapping->path, parent_mapping_index));

    assert(direntry);
    assert(mapping);
    assert(mapping->begin == first_cluster);
    assert(mapping->info.dir.first_dir_index < s->directory.next);
    assert(mapping->mode & MODE_DIRECTORY);
    assert(dir_index == 0 || is_directory(direntry));

    mapping->info.dir.parent_mapping_index = parent_mapping_index;

    if (first_cluster == 0) {
	old_cluster_count = new_cluster_count =
	    s->last_cluster_of_root_directory;
    } else {
	for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
		c = fat_get(s, c))
	    old_cluster_count++;
2129

2130 2131 2132 2133
	for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
		c = modified_fat_get(s, c))
	    new_cluster_count++;
    }
2134

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
    if (new_cluster_count > old_cluster_count) {
	if (insert_direntries(s,
		current_dir_index + factor * old_cluster_count,
		factor * (new_cluster_count - old_cluster_count)) == NULL)
	    return -1;
    } else if (new_cluster_count < old_cluster_count)
	remove_direntries(s,
		current_dir_index + factor * new_cluster_count,
		factor * (old_cluster_count - new_cluster_count));

    for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {
	void* direntry = array_get(&(s->directory), current_dir_index);
	int ret = vvfat_read(s->bs, cluster2sector(s, c), direntry,
		s->sectors_per_cluster);
	if (ret)
	    return ret;
	assert(!strncmp(s->directory.pointer, "QEMU", 4));
	current_dir_index += factor;
    }
2154

2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
    ret = commit_mappings(s, first_cluster, dir_index);
    if (ret)
	return ret;

    /* recurse */
    for (i = 0; i < factor * new_cluster_count; i++) {
	direntry = array_get(&(s->directory), first_dir_index + i);
	if (is_directory(direntry) && !is_dot(direntry)) {
	    mapping = find_mapping_for_cluster(s, first_cluster);
	    assert(mapping->mode & MODE_DIRECTORY);
	    ret = commit_direntries(s, first_dir_index + i,
		array_index(&(s->mapping), mapping));
	    if (ret)
		return ret;
	}
    }
2171

2172 2173
    return 0;
}
2174

2175 2176 2177 2178 2179
/* commit one file (adjust contents, adjust mapping),
   return first_mapping_index */
static int commit_one_file(BDRVVVFATState* s,
	int dir_index, uint32_t offset)
{
A
Anthony Liguori 已提交
2180
    direntry_t* direntry = array_get(&(s->directory), dir_index);
2181 2182
    uint32_t c = begin_of_direntry(direntry);
    uint32_t first_cluster = c;
A
Anthony Liguori 已提交
2183
    mapping_t* mapping = find_mapping_for_cluster(s, c);
2184
    uint32_t size = filesize_of_direntry(direntry);
2185
    char* cluster = g_malloc(s->cluster_size);
2186 2187 2188 2189 2190 2191 2192 2193 2194
    uint32_t i;
    int fd = 0;

    assert(offset < size);
    assert((offset % s->cluster_size) == 0);

    for (i = s->cluster_size; i < offset; i += s->cluster_size)
	c = modified_fat_get(s, c);

B
bellard 已提交
2195
    fd = open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
2196 2197 2198
    if (fd < 0) {
	fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
		strerror(errno), errno);
2199
        g_free(cluster);
2200
	return fd;
2201
    }
2202 2203 2204 2205 2206 2207
    if (offset > 0) {
        if (lseek(fd, offset, SEEK_SET) != offset) {
            g_free(cluster);
            return -3;
        }
    }
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220

    while (offset < size) {
	uint32_t c1;
	int rest_size = (size - offset > s->cluster_size ?
		s->cluster_size : size - offset);
	int ret;

	c1 = modified_fat_get(s, c);

	assert((size - offset == 0 && fat_eof(s, c)) ||
		(size > offset && c >=2 && !fat_eof(s, c)));

	ret = vvfat_read(s->bs, cluster2sector(s, c),
T
ths 已提交
2221
	    (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
2222

2223 2224 2225 2226
        if (ret < 0) {
            g_free(cluster);
            return ret;
        }
2227

2228 2229 2230 2231
        if (write(fd, cluster, rest_size) < 0) {
            g_free(cluster);
            return -2;
        }
2232 2233 2234 2235 2236

	offset += rest_size;
	c = c1;
    }

2237 2238 2239
    if (ftruncate(fd, size)) {
        perror("ftruncate()");
        close(fd);
2240
        g_free(cluster);
2241 2242
        return -4;
    }
2243
    close(fd);
2244
    g_free(cluster);
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254

    return commit_mappings(s, first_cluster, dir_index);
}

#ifdef DEBUG
/* test, if all mappings point to valid direntries */
static void check1(BDRVVVFATState* s)
{
    int i;
    for (i = 0; i < s->mapping.next; i++) {
A
Anthony Liguori 已提交
2255
	mapping_t* mapping = array_get(&(s->mapping), i);
2256 2257 2258 2259 2260
	if (mapping->mode & MODE_DELETED) {
	    fprintf(stderr, "deleted\n");
	    continue;
	}
	assert(mapping->dir_index < s->directory.next);
A
Anthony Liguori 已提交
2261
	direntry_t* direntry = array_get(&(s->directory), mapping->dir_index);
2262 2263 2264 2265
	assert(mapping->begin == begin_of_direntry(direntry) || mapping->first_mapping_index >= 0);
	if (mapping->mode & MODE_DIRECTORY) {
	    assert(mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster * (mapping->end - mapping->begin) <= s->directory.next);
	    assert((mapping->info.dir.first_dir_index % (0x10 * s->sectors_per_cluster)) == 0);
2266 2267 2268 2269
	}
    }
}

2270 2271
/* test, if all direntries have mappings */
static void check2(BDRVVVFATState* s)
2272 2273
{
    int i;
2274
    int first_mapping = -1;
2275

2276
    for (i = 0; i < s->directory.next; i++) {
A
Anthony Liguori 已提交
2277
	direntry_t* direntry = array_get(&(s->directory), i);
2278

2279
	if (is_short_name(direntry) && begin_of_direntry(direntry)) {
A
Anthony Liguori 已提交
2280
	    mapping_t* mapping = find_mapping_for_cluster(s, begin_of_direntry(direntry));
2281 2282 2283 2284
	    assert(mapping);
	    assert(mapping->dir_index == i || is_dot(direntry));
	    assert(mapping->begin == begin_of_direntry(direntry) || is_dot(direntry));
	}
2285

2286 2287 2288
	if ((i % (0x10 * s->sectors_per_cluster)) == 0) {
	    /* cluster start */
	    int j, count = 0;
2289

2290
	    for (j = 0; j < s->mapping.next; j++) {
A
Anthony Liguori 已提交
2291
		mapping_t* mapping = array_get(&(s->mapping), j);
2292
		if (mapping->mode & MODE_DELETED)
2293
		    continue;
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
		if (mapping->mode & MODE_DIRECTORY) {
		    if (mapping->info.dir.first_dir_index <= i && mapping->info.dir.first_dir_index + 0x10 * s->sectors_per_cluster > i) {
			assert(++count == 1);
			if (mapping->first_mapping_index == -1)
			    first_mapping = array_index(&(s->mapping), mapping);
			else
			    assert(first_mapping == mapping->first_mapping_index);
			if (mapping->info.dir.parent_mapping_index < 0)
			    assert(j == 0);
			else {
A
Anthony Liguori 已提交
2304
			    mapping_t* parent = array_get(&(s->mapping), mapping->info.dir.parent_mapping_index);
2305 2306 2307 2308
			    assert(parent->mode & MODE_DIRECTORY);
			    assert(parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index);
			}
		    }
2309
		}
2310 2311 2312 2313 2314 2315 2316
	    }
	    if (count == 0)
		first_mapping = -1;
	}
    }
}
#endif
2317

2318 2319 2320
static int handle_renames_and_mkdirs(BDRVVVFATState* s)
{
    int i;
2321

2322 2323 2324
#ifdef DEBUG
    fprintf(stderr, "handle_renames\n");
    for (i = 0; i < s->commits.next; i++) {
A
Anthony Liguori 已提交
2325
	commit_t* commit = array_get(&(s->commits), i);
2326 2327 2328 2329 2330
	fprintf(stderr, "%d, %s (%d, %d)\n", i, commit->path ? commit->path : "(null)", commit->param.rename.cluster, commit->action);
    }
#endif

    for (i = 0; i < s->commits.next;) {
A
Anthony Liguori 已提交
2331
	commit_t* commit = array_get(&(s->commits), i);
2332
	if (commit->action == ACTION_RENAME) {
A
Anthony Liguori 已提交
2333
	    mapping_t* mapping = find_mapping_for_cluster(s,
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
		    commit->param.rename.cluster);
	    char* old_path = mapping->path;

	    assert(commit->path);
	    mapping->path = commit->path;
	    if (rename(old_path, mapping->path))
		return -2;

	    if (mapping->mode & MODE_DIRECTORY) {
		int l1 = strlen(mapping->path);
		int l2 = strlen(old_path);
		int diff = l1 - l2;
A
Anthony Liguori 已提交
2346
		direntry_t* direntry = array_get(&(s->directory),
2347 2348 2349 2350 2351 2352 2353
			mapping->info.dir.first_dir_index);
		uint32_t c = mapping->begin;
		int i = 0;

		/* recurse */
		while (!fat_eof(s, c)) {
		    do {
A
Anthony Liguori 已提交
2354
			direntry_t* d = direntry + i;
2355 2356

			if (is_file(d) || (is_directory(d) && !is_dot(d))) {
A
Anthony Liguori 已提交
2357
			    mapping_t* m = find_mapping_for_cluster(s,
2358 2359
				    begin_of_direntry(d));
			    int l = strlen(m->path);
2360
			    char* new_path = g_malloc(l + diff + 1);
2361 2362 2363

			    assert(!strncmp(m->path, mapping->path, l2));

B
blueswir1 已提交
2364 2365 2366
                            pstrcpy(new_path, l + diff + 1, mapping->path);
                            pstrcpy(new_path + l1, l + diff + 1 - l1,
                                    m->path + l2);
2367 2368

			    schedule_rename(s, m->begin, new_path);
2369
			}
2370 2371 2372
			i++;
		    } while((i % (0x10 * s->sectors_per_cluster)) != 0);
		    c = fat_get(s, c);
2373 2374 2375
		}
	    }

2376
            g_free(old_path);
2377 2378 2379
	    array_remove(&(s->commits), i);
	    continue;
	} else if (commit->action == ACTION_MKDIR) {
A
Anthony Liguori 已提交
2380
	    mapping_t* mapping;
2381 2382
	    int j, parent_path_len;

B
bellard 已提交
2383 2384 2385 2386 2387 2388 2389
#ifdef __MINGW32__
            if (mkdir(commit->path))
                return -5;
#else
            if (mkdir(commit->path, 0755))
                return -5;
#endif
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407

	    mapping = insert_mapping(s, commit->param.mkdir.cluster,
		    commit->param.mkdir.cluster + 1);
	    if (mapping == NULL)
		return -6;

	    mapping->mode = MODE_DIRECTORY;
	    mapping->read_only = 0;
	    mapping->path = commit->path;
	    j = s->directory.next;
	    assert(j);
	    insert_direntries(s, s->directory.next,
		    0x10 * s->sectors_per_cluster);
	    mapping->info.dir.first_dir_index = j;

	    parent_path_len = strlen(commit->path)
		- strlen(get_basename(commit->path)) - 1;
	    for (j = 0; j < s->mapping.next; j++) {
A
Anthony Liguori 已提交
2408
		mapping_t* m = array_get(&(s->mapping), j);
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
		if (m->first_mapping_index < 0 && m != mapping &&
			!strncmp(m->path, mapping->path, parent_path_len) &&
			strlen(m->path) == parent_path_len)
		    break;
	    }
	    assert(j < s->mapping.next);
	    mapping->info.dir.parent_mapping_index = j;

	    array_remove(&(s->commits), i);
	    continue;
	}

	i++;
    }
    return 0;
}

/*
 * TODO: make sure that the short name is not matching *another* file
 */
static int handle_commits(BDRVVVFATState* s)
{
    int i, fail = 0;

    vvfat_close_current_file(s);

    for (i = 0; !fail && i < s->commits.next; i++) {
A
Anthony Liguori 已提交
2436
	commit_t* commit = array_get(&(s->commits), i);
2437 2438
	switch(commit->action) {
	case ACTION_RENAME: case ACTION_MKDIR:
2439
            abort();
2440 2441 2442
	    fail = -2;
	    break;
	case ACTION_WRITEOUT: {
B
Blue Swirl 已提交
2443 2444
#ifndef NDEBUG
            /* these variables are only used by assert() below */
A
Anthony Liguori 已提交
2445
	    direntry_t* entry = array_get(&(s->directory),
2446 2447
		    commit->param.writeout.dir_index);
	    uint32_t begin = begin_of_direntry(entry);
A
Anthony Liguori 已提交
2448
	    mapping_t* mapping = find_mapping_for_cluster(s, begin);
B
Blue Swirl 已提交
2449
#endif
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462

	    assert(mapping);
	    assert(mapping->begin == begin);
	    assert(commit->path == NULL);

	    if (commit_one_file(s, commit->param.writeout.dir_index,
			commit->param.writeout.modified_offset))
		fail = -3;

	    break;
	}
	case ACTION_NEW_FILE: {
	    int begin = commit->param.new_file.first_cluster;
A
Anthony Liguori 已提交
2463 2464
	    mapping_t* mapping = find_mapping_for_cluster(s, begin);
	    direntry_t* entry;
2465
	    int i;
2466

2467 2468 2469 2470 2471
	    /* find direntry */
	    for (i = 0; i < s->directory.next; i++) {
		entry = array_get(&(s->directory), i);
		if (is_file(entry) && begin_of_direntry(entry) == begin)
		    break;
2472 2473
	    }

2474 2475 2476 2477
	    if (i >= s->directory.next) {
		fail = -6;
		continue;
	    }
2478

2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
	    /* make sure there exists an initial mapping */
	    if (mapping && mapping->begin != begin) {
		mapping->end = begin;
		mapping = NULL;
	    }
	    if (mapping == NULL) {
		mapping = insert_mapping(s, begin, begin+1);
	    }
	    /* most members will be fixed in commit_mappings() */
	    assert(commit->path);
	    mapping->path = commit->path;
	    mapping->read_only = 0;
	    mapping->mode = MODE_NORMAL;
	    mapping->info.file.offset = 0;

	    if (commit_one_file(s, i, 0))
		fail = -7;

	    break;
	}
	default:
2500
            abort();
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
	}
    }
    if (i > 0 && array_remove_slice(&(s->commits), 0, i))
	return -1;
    return fail;
}

static int handle_deletes(BDRVVVFATState* s)
{
    int i, deferred = 1, deleted = 1;

    /* delete files corresponding to mappings marked as deleted */
    /* handle DELETEs and unused mappings (modified_fat_get(s, mapping->begin) == 0) */
    while (deferred && deleted) {
	deferred = 0;
	deleted = 0;

	for (i = 1; i < s->mapping.next; i++) {
A
Anthony Liguori 已提交
2519
	    mapping_t* mapping = array_get(&(s->mapping), i);
2520
	    if (mapping->mode & MODE_DELETED) {
A
Anthony Liguori 已提交
2521
		direntry_t* entry = array_get(&(s->directory),
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
			mapping->dir_index);

		if (is_free(entry)) {
		    /* remove file/directory */
		    if (mapping->mode & MODE_DIRECTORY) {
			int j, next_dir_index = s->directory.next,
			first_dir_index = mapping->info.dir.first_dir_index;

			if (rmdir(mapping->path) < 0) {
			    if (errno == ENOTEMPTY) {
				deferred++;
				continue;
			    } else
				return -5;
2536
			}
2537 2538

			for (j = 1; j < s->mapping.next; j++) {
A
Anthony Liguori 已提交
2539
			    mapping_t* m = array_get(&(s->mapping), j);
2540 2541 2542 2543 2544 2545 2546
			    if (m->mode & MODE_DIRECTORY &&
				    m->info.dir.first_dir_index >
				    first_dir_index &&
				    m->info.dir.first_dir_index <
				    next_dir_index)
				next_dir_index =
				    m->info.dir.first_dir_index;
2547
			}
2548 2549
			remove_direntries(s, first_dir_index,
				next_dir_index - first_dir_index);
2550

2551
			deleted++;
2552
		    }
2553 2554 2555 2556
		} else {
		    if (unlink(mapping->path))
			return -4;
		    deleted++;
2557
		}
2558 2559
		DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry));
		remove_mapping(s, i);
2560 2561 2562
	    }
	}
    }
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587

    return 0;
}

/*
 * synchronize mapping with new state:
 *
 * - copy FAT (with bdrv_read)
 * - mark all filenames corresponding to mappings as deleted
 * - recurse direntries from root (using bs->bdrv_read)
 * - delete files corresponding to mappings marked as deleted
 */
static int do_commit(BDRVVVFATState* s)
{
    int ret = 0;

    /* the real meat are the commits. Nothing to do? Move along! */
    if (s->commits.next == 0)
	return 0;

    vvfat_close_current_file(s);

    ret = handle_renames_and_mkdirs(s);
    if (ret) {
	fprintf(stderr, "Error handling renames (%d)\n", ret);
2588
        abort();
2589 2590 2591
	return ret;
    }

2592
    /* copy FAT (with bdrv_read) */
2593 2594 2595 2596 2597 2598
    memcpy(s->fat.pointer, s->fat2, 0x200 * s->sectors_per_fat);

    /* recurse direntries from root (using bs->bdrv_read) */
    ret = commit_direntries(s, 0, -1);
    if (ret) {
	fprintf(stderr, "Fatal: error while committing (%d)\n", ret);
2599
        abort();
2600 2601 2602 2603 2604 2605
	return ret;
    }

    ret = handle_commits(s);
    if (ret) {
	fprintf(stderr, "Error handling commits (%d)\n", ret);
2606
        abort();
2607 2608 2609 2610 2611 2612
	return ret;
    }

    ret = handle_deletes(s);
    if (ret) {
	fprintf(stderr, "Error deleting\n");
2613
        abort();
2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
	return ret;
    }

    s->qcow->drv->bdrv_make_empty(s->qcow);

    memset(s->used_clusters, 0, sector2cluster(s, s->sector_count));

DLOG(checkpoint());
    return 0;
}

static int try_commit(BDRVVVFATState* s)
{
    vvfat_close_current_file(s);
DLOG(checkpoint());
    if(!is_consistent(s))
	return -1;
    return do_commit(s);
}

2634
static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
2635 2636
                    const uint8_t *buf, int nb_sectors)
{
2637
    BDRVVVFATState *s = bs->opaque;
2638 2639 2640 2641
    int i, ret;

DLOG(checkpoint());

2642 2643 2644 2645 2646
    /* Check if we're operating in read-only mode */
    if (s->qcow == NULL) {
        return -EACCES;
    }

2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
    vvfat_close_current_file(s);

    /*
     * Some sanity checks:
     * - do not allow writing to the boot sector
     * - do not allow to write non-ASCII filenames
     */

    if (sector_num < s->first_sectors_number)
	return -1;

    for (i = sector2cluster(s, sector_num);
	    i <= sector2cluster(s, sector_num + nb_sectors - 1);) {
A
Anthony Liguori 已提交
2660
	mapping_t* mapping = find_mapping_for_cluster(s, i);
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
	if (mapping) {
	    if (mapping->read_only) {
		fprintf(stderr, "Tried to write to write-protected file %s\n",
			mapping->path);
		return -1;
	    }

	    if (mapping->mode & MODE_DIRECTORY) {
		int begin = cluster2sector(s, i);
		int end = begin + s->sectors_per_cluster, k;
		int dir_index;
A
Anthony Liguori 已提交
2672
		const direntry_t* direntries;
2673 2674 2675 2676 2677 2678 2679 2680
		long_file_name lfn;

		lfn_init(&lfn);

		if (begin < sector_num)
		    begin = sector_num;
		if (end > sector_num + nb_sectors)
		    end = sector_num + nb_sectors;
2681
		dir_index  = mapping->dir_index +
2682
		    0x10 * (begin - mapping->begin * s->sectors_per_cluster);
A
Anthony Liguori 已提交
2683
		direntries = (direntry_t*)(buf + 0x200 * (begin - sector_num));
2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695

		for (k = 0; k < (end - begin) * 0x10; k++) {
		    /* do not allow non-ASCII filenames */
		    if (parse_long_name(&lfn, direntries + k) < 0) {
			fprintf(stderr, "Warning: non-ASCII filename\n");
			return -1;
		    }
		    /* no access to the direntry of a read-only file */
		    else if (is_short_name(direntries+k) &&
			    (direntries[k].attributes & 1)) {
			if (memcmp(direntries + k,
				    array_get(&(s->directory), dir_index + k),
A
Anthony Liguori 已提交
2696
				    sizeof(direntry_t))) {
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
			    fprintf(stderr, "Warning: tried to write to write-protected file\n");
			    return -1;
			}
		    }
		}
	    }
	    i = mapping->end;
	} else
	    i++;
    }

    /*
     * Use qcow backend. Commit later.
     */
DLOG(fprintf(stderr, "Write to qcow backend: %d + %d\n", (int)sector_num, nb_sectors));
    ret = s->qcow->drv->bdrv_write(s->qcow, sector_num, buf, nb_sectors);
    if (ret < 0) {
	fprintf(stderr, "Error writing to qcow backend\n");
	return ret;
    }

    for (i = sector2cluster(s, sector_num);
	    i <= sector2cluster(s, sector_num + nb_sectors - 1); i++)
	if (i >= 0)
	    s->used_clusters[i] |= USED_ALLOCATED;

DLOG(checkpoint());
    /* TODO: add timeout */
    try_commit(s);

DLOG(checkpoint());
    return 0;
}

2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
static coroutine_fn int vvfat_co_write(BlockDriverState *bs, int64_t sector_num,
                                       const uint8_t *buf, int nb_sectors)
{
    int ret;
    BDRVVVFATState *s = bs->opaque;
    qemu_co_mutex_lock(&s->lock);
    ret = vvfat_write(bs, sector_num, buf, nb_sectors);
    qemu_co_mutex_unlock(&s->lock);
    return ret;
}

2742 2743 2744 2745 2746 2747 2748 2749 2750
static int vvfat_is_allocated(BlockDriverState *bs,
	int64_t sector_num, int nb_sectors, int* n)
{
    BDRVVVFATState* s = bs->opaque;
    *n = s->sector_count - sector_num;
    if (*n > nb_sectors)
	*n = nb_sectors;
    else if (*n < 0)
	return 0;
2751
    return 1;
2752 2753 2754 2755
}

static int write_target_commit(BlockDriverState *bs, int64_t sector_num,
	const uint8_t* buffer, int nb_sectors) {
2756
    BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
2757 2758 2759 2760
    return try_commit(s);
}

static void write_target_close(BlockDriverState *bs) {
2761
    BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
2762
    bdrv_delete(s->qcow);
2763
    g_free(s->qcow_filename);
2764 2765 2766
}

static BlockDriver vvfat_write_target = {
2767 2768 2769
    .format_name        = "vvfat_write_target",
    .bdrv_write         = write_target_commit,
    .bdrv_close         = write_target_close,
2770 2771 2772 2773
};

static int enable_write_target(BDRVVVFATState *s)
{
K
Kevin Wolf 已提交
2774 2775
    BlockDriver *bdrv_qcow;
    QEMUOptionParameter *options;
K
Kevin Wolf 已提交
2776
    int ret;
2777 2778 2779
    int size = sector2cluster(s, s->sector_count);
    s->used_clusters = calloc(size, 1);

A
Anthony Liguori 已提交
2780
    array_init(&(s->commits), sizeof(commit_t));
2781

2782
    s->qcow_filename = g_malloc(1024);
B
bellard 已提交
2783
    get_tmp_filename(s->qcow_filename, 1024);
K
Kevin Wolf 已提交
2784 2785 2786 2787 2788 2789 2790

    bdrv_qcow = bdrv_find_format("qcow");
    options = parse_option_parameters("", bdrv_qcow->create_options, NULL);
    set_option_parameter_int(options, BLOCK_OPT_SIZE, s->sector_count * 512);
    set_option_parameter(options, BLOCK_OPT_BACKING_FILE, "fat:");

    if (bdrv_create(bdrv_qcow, s->qcow_filename, options) < 0)
2791
	return -1;
K
Kevin Wolf 已提交
2792

2793
    s->qcow = bdrv_new("");
K
Kevin Wolf 已提交
2794 2795 2796 2797 2798 2799 2800 2801
    if (s->qcow == NULL) {
        return -1;
    }

    ret = bdrv_open(s->qcow, s->qcow_filename,
            BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, bdrv_qcow);
    if (ret < 0) {
	return ret;
K
Kevin Wolf 已提交
2802
    }
2803 2804 2805 2806 2807 2808 2809

#ifndef _WIN32
    unlink(s->qcow_filename);
#endif

    s->bs->backing_hd = calloc(sizeof(BlockDriverState), 1);
    s->bs->backing_hd->drv = &vvfat_write_target;
2810
    s->bs->backing_hd->opaque = g_malloc(sizeof(void*));
2811
    *(void**)s->bs->backing_hd->opaque = s;
2812

2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
    return 0;
}

static void vvfat_close(BlockDriverState *bs)
{
    BDRVVVFATState *s = bs->opaque;

    vvfat_close_current_file(s);
    array_free(&(s->fat));
    array_free(&(s->directory));
    array_free(&(s->mapping));
2824
    g_free(s->cluster_buffer);
2825 2826
}

2827
static BlockDriver bdrv_vvfat = {
2828 2829
    .format_name	= "vvfat",
    .instance_size	= sizeof(BDRVVVFATState),
2830
    .bdrv_file_open	= vvfat_open,
2831
    .bdrv_read          = vvfat_co_read,
2832
    .bdrv_write         = vvfat_co_write,
2833 2834 2835
    .bdrv_close		= vvfat_close,
    .bdrv_is_allocated	= vvfat_is_allocated,
    .protocol_name	= "fat",
2836 2837
};

2838 2839 2840 2841 2842 2843 2844
static void bdrv_vvfat_init(void)
{
    bdrv_register(&bdrv_vvfat);
}

block_init(bdrv_vvfat_init);

2845
#ifdef DEBUG
2846
static void checkpoint(void) {
A
Anthony Liguori 已提交
2847
    assert(((mapping_t*)array_get(&(vvv->mapping), 0))->end == 2);
2848 2849 2850 2851
    check1(vvv);
    check2(vvv);
    assert(!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode & MODE_DIRECTORY));
#if 0
A
Anthony Liguori 已提交
2852
    if (((direntry_t*)vvv->directory.pointer)[1].attributes != 0xf)
2853
	fprintf(stderr, "Nonono!\n");
A
Anthony Liguori 已提交
2854 2855
    mapping_t* mapping;
    direntry_t* direntry;
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
    assert(vvv->mapping.size >= vvv->mapping.item_size * vvv->mapping.next);
    assert(vvv->directory.size >= vvv->directory.item_size * vvv->directory.next);
    if (vvv->mapping.next<47)
	return;
    assert((mapping = array_get(&(vvv->mapping), 47)));
    assert(mapping->dir_index < vvv->directory.next);
    direntry = array_get(&(vvv->directory), mapping->dir_index);
    assert(!memcmp(direntry->name, "USB     H  ", 11) || direntry->name[0]==0);
#endif
}
#endif