vvfat.c 101.1 KB
Newer Older
1
/* vim:set shiftwidth=4 ts=4: */
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
 * 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.
 */
P
Peter Maydell 已提交
25
#include "qemu/osdep.h"
26
#include <dirent.h>
27
#include "qapi/error.h"
28
#include "block/block_int.h"
29
#include "qemu/module.h"
30
#include "qemu/bswap.h"
31
#include "migration/blocker.h"
32
#include "qapi/qmp/qbool.h"
33
#include "qapi/qmp/qstring.h"
34
#include "qemu/cutils.h"
35

36 37 38 39 40 41 42 43 44 45
#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
46
    Note that DOS assumes the system files to be the first files in the
47 48 49 50 51 52 53 54 55 56
    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

57
static void checkpoint(void);
58

59 60 61 62 63 64
#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 已提交
65
#define assert(a) do {if (!(a)) nonono(__FILE__, __LINE__, #a);}while(0)
66 67 68 69 70 71 72
#endif

#else

#define DLOG(a)

#endif
73 74

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

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

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

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

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

    return 0;
112 113
}

A
Anthony Liguori 已提交
114
static inline void* array_get_next(array_t* array) {
115 116 117
    unsigned int next = array->next;

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

    array->next = next + 1;
121
    return array_get(array, next);
122 123
}

A
Anthony Liguori 已提交
124
static inline void* array_insert(array_t* array,unsigned int index,unsigned int count) {
125
    if((array->next+count)*array->item_size>array->size) {
126 127 128
        int increment=count*array->item_size;
        array->pointer=g_realloc(array->pointer,array->size+increment);
        if(!array->pointer)
129
            return NULL;
130
        array->size+=increment;
131 132
    }
    memmove(array->pointer+(index+count)*array->item_size,
133 134
                array->pointer+index*array->item_size,
                (array->next-index)*array->item_size);
135 136 137 138 139 140
    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 已提交
141
static inline int array_roll(array_t* array,int index_to,int index_from,int count)
142 143 144 145 146 147 148
{
    char* buf;
    char* from;
    char* to;
    int is;

    if(!array ||
149 150 151
            index_to<0 || index_to>=array->next ||
            index_from<0 || index_from>=array->next)
        return -1;
152

153
    if(index_to==index_from)
154
        return 0;
155 156 157 158

    is=array->item_size;
    from=array->pointer+index_from*is;
    to=array->pointer+index_to*is;
159
    buf=g_malloc(is*count);
160 161 162
    memcpy(buf,from,is*count);

    if(index_to<index_from)
163
        memmove(to+is*count,to,from-to);
164
    else
165
        memmove(from,from+is*count,to-from);
166

167 168
    memcpy(to,buf,is*count);

169
    g_free(buf);
170 171 172 173

    return 0;
}

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

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

/* return the index for a given member */
A
Anthony Liguori 已提交
191
static int array_index(array_t* array, void* pointer)
192 193 194 195 196 197 198
{
    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;
}

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

A
Anthony Liguori 已提交
202
typedef struct bootsector_t {
203 204 205 206 207 208 209
    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;
210
    uint16_t total_sectors16;
211 212 213 214 215 216 217 218
    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 {
219
            uint8_t drive_number;
220
            uint8_t reserved1;
221 222 223
            uint8_t signature;
            uint32_t id;
            uint8_t volume_label[11];
224 225
            uint8_t fat_type[8];
            uint8_t ignored[0x1c0];
226 227 228 229 230
        } QEMU_PACKED fat16;
        struct {
            uint32_t sectors_per_fat;
            uint16_t flags;
            uint8_t major,minor;
231
            uint32_t first_cluster_of_root_dir;
232 233
            uint16_t info_sector;
            uint16_t backup_boot_sector;
234 235 236 237 238 239 240 241
            uint8_t reserved[12];
            uint8_t drive_number;
            uint8_t reserved1;
            uint8_t signature;
            uint32_t id;
            uint8_t volume_label[11];
            uint8_t fat_type[8];
            uint8_t ignored[0x1a4];
242
        } QEMU_PACKED fat32;
243 244
    } u;
    uint8_t magic[2];
245
} QEMU_PACKED bootsector_t;
246

T
ths 已提交
247 248 249 250
typedef struct {
    uint8_t head;
    uint8_t sector;
    uint8_t cylinder;
A
Anthony Liguori 已提交
251
} mbr_chs_t;
T
ths 已提交
252

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

A
Anthony Liguori 已提交
262
typedef struct mbr_t {
T
ths 已提交
263 264 265
    uint8_t ignored[0x1b8];
    uint32_t nt_id;
    uint8_t ignored2[2];
A
Anthony Liguori 已提交
266
    partition_t partition[4];
267
    uint8_t magic[2];
268
} QEMU_PACKED mbr_t;
269

A
Anthony Liguori 已提交
270
typedef struct direntry_t {
271
    uint8_t name[8 + 3];
272 273 274 275 276 277 278 279 280 281
    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;
282
} QEMU_PACKED direntry_t;
283 284 285

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

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

309 310 311 312 313 314 315
    enum {
        MODE_UNDEFINED = 0,
        MODE_NORMAL = 1,
        MODE_MODIFIED = 2,
        MODE_DIRECTORY = 4,
        MODE_DELETED = 8,
    } mode;
316
    int read_only;
A
Anthony Liguori 已提交
317
} mapping_t;
318

319
#ifdef DEBUG
A
Anthony Liguori 已提交
320 321
static void print_direntry(const struct direntry_t*);
static void print_mapping(const struct mapping_t* mapping);
322
#endif
323 324 325 326

/* here begins the real VVFAT driver */

typedef struct BDRVVVFATState {
327
    CoMutex lock;
328
    BlockDriverState* bs; /* pointer to parent */
329
    unsigned char first_sectors[0x40*0x200];
330

331
    int fat_type; /* 16 or 32 */
A
Anthony Liguori 已提交
332
    array_t fat,directory,mapping;
W
Wolfgang Bumiller 已提交
333
    char volume_label[11];
334

335 336
    uint32_t offset_to_bootsector; /* 0 for floppy, 0x3f for disk */

337 338 339
    unsigned int cluster_size;
    unsigned int sectors_per_cluster;
    unsigned int sectors_per_fat;
340
    uint32_t last_cluster_of_root_directory;
341 342
    /* how many entries are available in root directory (0 for FAT32) */
    uint16_t root_entries;
343 344 345
    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;
346 347
    uint32_t offset_to_fat;
    uint32_t offset_to_root_dir;
348

349
    int current_fd;
A
Anthony Liguori 已提交
350
    mapping_t* current_mapping;
351 352
    unsigned char* cluster; /* points to current cluster */
    unsigned char* cluster_buffer; /* points to a buffer to hold temp data */
353 354 355
    unsigned int current_cluster;

    /* write support */
356
    char* qcow_filename;
K
Kevin Wolf 已提交
357
    BdrvChild* qcow;
358 359
    void* fat2;
    char* used_clusters;
A
Anthony Liguori 已提交
360
    array_t commits;
361 362
    const char* path;
    int downcase_short_names;
K
Kevin Wolf 已提交
363 364

    Error *migration_blocker;
365 366
} BDRVVVFATState;

T
ths 已提交
367 368 369 370
/* 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.
 */
371 372
static int sector2CHS(mbr_chs_t *chs, int spos, int cyls, int heads, int secs)
{
T
ths 已提交
373
    int head,sector;
374 375 376
    sector   = spos % secs;  spos /= secs;
    head     = spos % heads; spos /= heads;
    if (spos >= cyls) {
T
ths 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389
        /* 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;
}
390

391
static void init_mbr(BDRVVVFATState *s, int cyls, int heads, int secs)
392 393
{
    /* TODO: if the files mbr.img and bootsect.img exist, use them */
A
Anthony Liguori 已提交
394 395
    mbr_t* real_mbr=(mbr_t*)s->first_sectors;
    partition_t* partition = &(real_mbr->partition[0]);
T
ths 已提交
396
    int lba;
397 398

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

T
ths 已提交
400 401 402
    /* Win NT Disk Signature */
    real_mbr->nt_id= cpu_to_le32(0xbe1afdfa);

403
    partition->attributes=0x80; /* bootable */
T
ths 已提交
404 405

    /* LBA is used when partition is outside the CHS geometry */
406
    lba  = sector2CHS(&partition->start_CHS, s->offset_to_bootsector,
407 408 409
                     cyls, heads, secs);
    lba |= sector2CHS(&partition->end_CHS,   s->bs->total_sectors - 1,
                     cyls, heads, secs);
T
ths 已提交
410 411

    /*LBA partitions are identified only by start/length_sector_long not by CHS*/
412
    partition->start_sector_long  = cpu_to_le32(s->offset_to_bootsector);
M
Markus Armbruster 已提交
413
    partition->length_sector_long = cpu_to_le32(s->bs->total_sectors
414
                                                - s->offset_to_bootsector);
T
ths 已提交
415

416
    /* FAT12/FAT16/FAT32 */
T
ths 已提交
417 418
    /* DOS uses different types when partition is LBA,
       probably to prevent older versions from using CHS on them */
H
Hervé Poussineau 已提交
419 420 421
    partition->fs_type = s->fat_type == 12 ? 0x1 :
                         s->fat_type == 16 ? (lba ? 0xe : 0x06) :
                       /*s->fat_type == 32*/ (lba ? 0xc : 0x0b);
422 423 424 425

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

426 427
/* direntry functions */

428
static direntry_t *create_long_filename(BDRVVVFATState *s, const char *filename)
429
{
430 431 432 433 434 435 436 437
    int number_of_entries, i;
    glong length;
    direntry_t *entry;

    gunichar2 *longname = g_utf8_to_utf16(filename, -1, NULL, &length, NULL);
    if (!longname) {
        fprintf(stderr, "vvfat: invalid UTF-8 name: %s\n", filename);
        return NULL;
438 439
    }

440
    number_of_entries = (length * 2 + 25) / 26;
441 442

    for(i=0;i<number_of_entries;i++) {
443 444 445 446 447
        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);
448
    }
449
    for(i=0;i<26*number_of_entries;i++) {
450 451 452 453 454
        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));
455 456 457 458 459 460 461
        if (i >= 2 * length + 2) {
            entry->name[offset] = 0xff;
        } else if (i % 2 == 0) {
            entry->name[offset] = longname[i / 2] & 0xff;
        } else {
            entry->name[offset] = longname[i / 2] >> 8;
        }
462
    }
463
    g_free(longname);
464 465 466
    return array_get(&(s->directory),s->directory.next-number_of_entries);
}

A
Anthony Liguori 已提交
467
static char is_free(const direntry_t* direntry)
468
{
469
    return direntry->name[0]==0xe5 || direntry->name[0]==0x00;
470 471
}

A
Anthony Liguori 已提交
472
static char is_volume_label(const direntry_t* direntry)
473 474 475 476
{
    return direntry->attributes == 0x28;
}

A
Anthony Liguori 已提交
477
static char is_long_name(const direntry_t* direntry)
478 479 480 481
{
    return direntry->attributes == 0xf;
}

A
Anthony Liguori 已提交
482
static char is_short_name(const direntry_t* direntry)
483 484
{
    return !is_volume_label(direntry) && !is_long_name(direntry)
485
        && !is_free(direntry);
486 487
}

A
Anthony Liguori 已提交
488
static char is_directory(const direntry_t* direntry)
489 490 491 492
{
    return direntry->attributes & 0x10 && direntry->name[0] != 0xe5;
}

A
Anthony Liguori 已提交
493
static inline char is_dot(const direntry_t* direntry)
494 495 496 497
{
    return is_short_name(direntry) && direntry->name[0] == '.';
}

A
Anthony Liguori 已提交
498
static char is_file(const direntry_t* direntry)
499 500 501 502
{
    return is_short_name(direntry) && !is_directory(direntry);
}

A
Anthony Liguori 已提交
503
static inline uint32_t begin_of_direntry(const direntry_t* direntry)
504 505 506 507
{
    return le16_to_cpu(direntry->begin)|(le16_to_cpu(direntry->begin_hi)<<16);
}

A
Anthony Liguori 已提交
508
static inline uint32_t filesize_of_direntry(const direntry_t* direntry)
509 510 511 512
{
    return le32_to_cpu(direntry->size);
}

A
Anthony Liguori 已提交
513
static void set_begin_of_direntry(direntry_t* direntry, uint32_t begin)
514 515 516 517 518
{
    direntry->begin = cpu_to_le16(begin & 0xffff);
    direntry->begin_hi = cpu_to_le16((begin >> 16) & 0xffff);
}

519 520 521 522 523 524 525 526 527 528 529 530 531
static uint8_t to_valid_short_char(gunichar c)
{
    c = g_unichar_toupper(c);
    if ((c >= '0' && c <= '9') ||
        (c >= 'A' && c <= 'Z') ||
        strchr("$%'-_@~`!(){}^#&", c) != 0) {
        return c;
    } else {
        return 0;
    }
}

static direntry_t *create_short_filename(BDRVVVFATState *s,
532 533
                                         const char *filename,
                                         unsigned int directory_start)
534
{
535
    int i, j = 0;
536 537 538 539
    direntry_t *entry = array_get_next(&(s->directory));
    const gchar *p, *last_dot = NULL;
    gunichar c;
    bool lossy_conversion = false;
540
    char tail[11];
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

    if (!entry) {
        return NULL;
    }
    memset(entry->name, 0x20, sizeof(entry->name));

    /* copy filename and search last dot */
    for (p = filename; ; p = g_utf8_next_char(p)) {
        c = g_utf8_get_char(p);
        if (c == '\0') {
            break;
        } else if (c == '.') {
            if (j == 0) {
                /* '.' at start of filename */
                lossy_conversion = true;
            } else {
                if (last_dot) {
                    lossy_conversion = true;
                }
                last_dot = p;
            }
        } else if (!last_dot) {
            /* first part of the name; copy it */
            uint8_t v = to_valid_short_char(c);
            if (j < 8 && v) {
                entry->name[j++] = v;
            } else {
                lossy_conversion = true;
            }
        }
    }

    /* copy extension (if any) */
    if (last_dot) {
        j = 0;
        for (p = g_utf8_next_char(last_dot); ; p = g_utf8_next_char(p)) {
            c = g_utf8_get_char(p);
            if (c == '\0') {
                break;
            } else {
                /* extension; copy it */
                uint8_t v = to_valid_short_char(c);
                if (j < 3 && v) {
                    entry->name[8 + (j++)] = v;
                } else {
                    lossy_conversion = true;
                }
            }
        }
    }
591

592 593 594 595
    if (entry->name[0] == 0xe5) {
        entry->name[0] = 0x05;
    }

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    /* numeric-tail generation */
    for (j = 0; j < 8; j++) {
        if (entry->name[j] == ' ') {
            break;
        }
    }
    for (i = lossy_conversion ? 1 : 0; i < 999999; i++) {
        direntry_t *entry1;
        if (i > 0) {
            int len = sprintf(tail, "~%d", i);
            memcpy(entry->name + MIN(j, 8 - len), tail, len);
        }
        for (entry1 = array_get(&(s->directory), directory_start);
             entry1 < entry; entry1++) {
            if (!is_long_name(entry1) &&
                !memcmp(entry1->name, entry->name, 11)) {
                break; /* found dupe */
            }
        }
        if (entry1 == entry) {
            /* no dupe found */
            return entry;
        }
    }
    return NULL;
621 622
}

623 624
/* fat functions */

A
Anthony Liguori 已提交
625
static inline uint8_t fat_chksum(const direntry_t* entry)
626 627 628 629
{
    uint8_t chksum=0;
    int i;

630 631 632
    for (i = 0; i < ARRAY_SIZE(entry->name); i++) {
        chksum = (((chksum & 0xfe) >> 1) |
                  ((chksum & 0x01) ? 0x80 : 0)) + entry->name[i];
A
Aurelien Jarno 已提交
633
    }
634

635 636 637 638 639 640 641
    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;
    struct tm t1;
M
Michael S. Tsirkin 已提交
642
    t = &t1;
643 644
    localtime_r(&time,t);
    if(return_time)
645
        return cpu_to_le16((t->tm_sec/2)|(t->tm_min<<5)|(t->tm_hour<<11));
646 647 648 649 650
    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)
{
651
    if(s->fat_type==32) {
652 653
        uint32_t* entry=array_get(&(s->fat),cluster);
        *entry=cpu_to_le32(value);
654
    } else if(s->fat_type==16) {
655 656
        uint16_t* entry=array_get(&(s->fat),cluster);
        *entry=cpu_to_le16(value&0xffff);
657
    } else {
658 659
        int offset = (cluster*3/2);
        unsigned char* p = array_get(&(s->fat), offset);
660
        switch (cluster&1) {
661 662 663 664 665 666 667 668 669
        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;
        }
670 671 672 673 674
    }
}

static inline uint32_t fat_get(BDRVVVFATState* s,unsigned int cluster)
{
675
    if(s->fat_type==32) {
676 677
        uint32_t* entry=array_get(&(s->fat),cluster);
        return le32_to_cpu(*entry);
678
    } else if(s->fat_type==16) {
679 680
        uint16_t* entry=array_get(&(s->fat),cluster);
        return le16_to_cpu(*entry);
681
    } else {
682 683
        const uint8_t* x=(uint8_t*)(s->fat.pointer)+cluster*3/2;
        return ((x[0]|(x[1]<<8))>>(cluster&1?4:0))&0x0fff;
684 685 686 687 688 689
    }
}

static inline int fat_eof(BDRVVVFATState* s,uint32_t fat_entry)
{
    if(fat_entry>s->max_fat_value-8)
690
        return -1;
691 692 693 694 695
    return 0;
}

static inline void init_fat(BDRVVVFATState* s)
{
696
    if (s->fat_type == 12) {
697 698 699
        array_init(&(s->fat),1);
        array_ensure_allocated(&(s->fat),
                s->sectors_per_fat * 0x200 * 3 / 2 - 1);
700
    } else {
701 702 703
        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);
704
    }
705
    memset(s->fat.pointer,0,s->fat.size);
706

707
    switch(s->fat_type) {
708 709 710 711
        case 12: s->max_fat_value=0xfff; break;
        case 16: s->max_fat_value=0xffff; break;
        case 32: s->max_fat_value=0x0fffffff; break;
        default: s->max_fat_value=0; /* error... */
712 713 714 715
    }

}

A
Anthony Liguori 已提交
716
static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,
717
        unsigned int directory_start, const char* filename, int is_dot)
718
{
719
    int long_index = s->directory.next;
A
Anthony Liguori 已提交
720 721
    direntry_t* entry = NULL;
    direntry_t* entry_long = NULL;
722 723

    if(is_dot) {
724
        entry=array_get_next(&(s->directory));
725
        memset(entry->name, 0x20, sizeof(entry->name));
726 727
        memcpy(entry->name,filename,strlen(filename));
        return entry;
728
    }
729

730
    entry_long=create_long_filename(s,filename);
731
    entry = create_short_filename(s, filename, directory_start);
732 733 734 735 736

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

737 738 739 740 741 742
        /* calculate anew, because realloc could have taken place */
        entry_long=array_get(&(s->directory),long_index);
        while(entry_long<entry && is_long_name(entry_long)) {
            entry_long->reserved[1]=chksum;
            entry_long++;
        }
743 744 745 746 747
    }

    return entry;
}

748 749 750 751
/*
 * Read a directory. (the index of the corresponding mapping must be passed).
 */
static int read_directory(BDRVVVFATState* s, int mapping_index)
752
{
A
Anthony Liguori 已提交
753 754
    mapping_t* mapping = array_get(&(s->mapping), mapping_index);
    direntry_t* direntry;
755 756 757
    const char* dirname = mapping->path;
    int first_cluster = mapping->begin;
    int parent_index = mapping->info.dir.parent_mapping_index;
A
Anthony Liguori 已提交
758
    mapping_t* parent_mapping = (mapping_t*)
759
        (parent_index >= 0 ? array_get(&(s->mapping), parent_index) : NULL);
760
    int first_cluster_of_parent = parent_mapping ? parent_mapping->begin : -1;
761 762 763 764 765

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

766 767 768
    assert(mapping->mode & MODE_DIRECTORY);

    if(!dir) {
769 770
        mapping->end = mapping->begin;
        return -1;
771
    }
772

773
    i = mapping->info.dir.first_dir_index =
774
            first_cluster == 0 ? 0 : s->directory.next;
775

776 777 778 779 780 781
    if (first_cluster != 0) {
        /* create the top entries of a subdirectory */
        (void)create_short_and_long_name(s, i, ".", 1);
        (void)create_short_and_long_name(s, i, "..", 1);
    }

782
    /* actually read the directory, and allocate the mappings */
783
    while((entry=readdir(dir))) {
784
        unsigned int length=strlen(dirname)+2+strlen(entry->d_name);
785
        char* buffer;
786
        direntry_t* direntry;
787
        struct stat st;
788 789
        int is_dot=!strcmp(entry->d_name,".");
        int is_dotdot=!strcmp(entry->d_name,"..");
790

791 792 793 794 795 796
        if (first_cluster == 0 && s->directory.next >= s->root_entries - 1) {
            fprintf(stderr, "Too many entries in root directory\n");
            closedir(dir);
            return -2;
        }

797 798
        if(first_cluster == 0 && (is_dotdot || is_dot))
            continue;
799

800 801
        buffer = g_malloc(length);
        snprintf(buffer,length,"%s/%s",dirname,entry->d_name);
802

803
        if(stat(buffer,&st)<0) {
804
            g_free(buffer);
805
            continue;
806 807 808
        }

        /* create directory entry for this file */
809 810 811 812 813
        if (!is_dot && !is_dotdot) {
            direntry = create_short_and_long_name(s, i, entry->d_name, 0);
        } else {
            direntry = array_get(&(s->directory), is_dot ? i : i + 1);
        }
814 815 816 817 818 819 820 821 822 823 824 825 826 827
        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)
            set_begin_of_direntry(direntry, first_cluster_of_parent);
        else if(is_dot)
            set_begin_of_direntry(direntry, first_cluster);
        else
            direntry->begin=0; /* do that later */
828
        if (st.st_size > 0x7fffffff) {
829
            fprintf(stderr, "File %s is larger than 2GB\n", buffer);
830
            g_free(buffer);
B
Blue Swirl 已提交
831
            closedir(dir);
832
            return -2;
833
        }
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
        direntry->size=cpu_to_le32(S_ISDIR(st.st_mode)?0:st.st_size);

        /* create mapping for this file */
        if(!is_dot && !is_dotdot && (S_ISDIR(st.st_mode) || st.st_size)) {
            s->current_mapping = array_get_next(&(s->mapping));
            s->current_mapping->begin=0;
            s->current_mapping->end=st.st_size;
            /*
             * we get the direntry of the most recent direntry, which
             * contains the short name and all the relevant information.
             */
            s->current_mapping->dir_index=s->directory.next-1;
            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;
858 859 860
        } else {
            g_free(buffer);
        }
861 862 863 864 865
    }
    closedir(dir);

    /* fill with zeroes up to the end of the cluster */
    while(s->directory.next%(0x10*s->sectors_per_cluster)) {
866 867
        direntry_t* direntry=array_get_next(&(s->directory));
        memset(direntry,0,sizeof(direntry_t));
868 869
    }

870 871 872
    if (s->fat_type != 32 &&
        mapping_index == 0 &&
        s->directory.next < s->root_entries) {
873 874
        /* root directory */
        int cur = s->directory.next;
875 876
        array_ensure_allocated(&(s->directory), s->root_entries - 1);
        s->directory.next = s->root_entries;
877
        memset(array_get(&(s->directory), cur), 0,
878
                (s->root_entries - cur) * sizeof(direntry_t));
879
    }
880

H
Hervé Poussineau 已提交
881
    /* re-get the mapping, since s->mapping was possibly realloc()ed */
882
    mapping = array_get(&(s->mapping), mapping_index);
883
    first_cluster += (s->directory.next - mapping->info.dir.first_dir_index)
884
        * 0x20 / s->cluster_size;
885 886
    mapping->end = first_cluster;

887
    direntry = array_get(&(s->directory), mapping->dir_index);
888
    set_begin_of_direntry(direntry, mapping->begin);
889

890 891
    return 0;
}
892

893 894
static inline uint32_t sector2cluster(BDRVVVFATState* s,off_t sector_num)
{
895
    return (sector_num - s->offset_to_root_dir) / s->sectors_per_cluster;
896
}
897

898 899
static inline off_t cluster2sector(BDRVVVFATState* s, uint32_t cluster_num)
{
900
    return s->offset_to_root_dir + s->sectors_per_cluster * cluster_num;
901
}
902

903
static int init_directories(BDRVVVFATState* s,
904 905
                            const char *dirname, int heads, int secs,
                            Error **errp)
906
{
A
Anthony Liguori 已提交
907 908
    bootsector_t* bootsector;
    mapping_t* mapping;
909 910 911 912 913 914
    unsigned int i;
    unsigned int cluster;

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

    s->cluster_size=s->sectors_per_cluster*0x200;
915
    s->cluster_buffer=g_malloc(s->cluster_size);
916 917 918 919 920 921 922 923 924 925

    /*
     * 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 */
926

927 928 929
    s->offset_to_fat = s->offset_to_bootsector + 1;
    s->offset_to_root_dir = s->offset_to_fat + s->sectors_per_fat * 2;

A
Anthony Liguori 已提交
930 931
    array_init(&(s->mapping),sizeof(mapping_t));
    array_init(&(s->directory),sizeof(direntry_t));
932 933 934

    /* add volume label */
    {
935 936
        direntry_t* entry=array_get_next(&(s->directory));
        entry->attributes=0x28; /* archive | volume label */
W
Wolfgang Bumiller 已提交
937
        memcpy(entry->name, s->volume_label, sizeof(entry->name));
938 939 940 941 942
    }

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

943 944
    /* TODO: if there are more entries, bootsector has to be adjusted! */
    s->root_entries = 0x02 * 0x10 * s->sectors_per_cluster;
945 946 947 948 949 950 951
    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;
952
    mapping->path = g_strdup(dirname);
953 954
    i = strlen(mapping->path);
    if (i > 0 && mapping->path[i - 1] == '/')
955
        mapping->path[i - 1] = '\0';
956 957 958 959 960
    mapping->mode = MODE_DIRECTORY;
    mapping->read_only = 0;
    s->path = mapping->path;

    for (i = 0, cluster = 0; i < s->mapping.next; i++) {
961 962 963 964 965
        /* MS-DOS expects the FAT to be 0 for the root directory
         * (except for the media byte). */
        /* LATER TODO: still true for FAT32? */
        int fix_fat = (i != 0);
        mapping = array_get(&(s->mapping), i);
966 967

        if (mapping->mode & MODE_DIRECTORY) {
968 969
            mapping->begin = cluster;
            if(read_directory(s, i)) {
970 971
                error_setg(errp, "Could not read directory %s",
                           mapping->path);
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
                return -1;
            }
            mapping = array_get(&(s->mapping), i);
        } else {
            assert(mapping->mode == MODE_UNDEFINED);
            mapping->mode=MODE_NORMAL;
            mapping->begin = cluster;
            if (mapping->end > 0) {
                direntry_t* direntry = array_get(&(s->directory),
                        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;
            }
        }

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

        /* next free cluster */
        cluster = mapping->end;

        if(cluster > s->cluster_count) {
997 998 999 1000
            error_setg(errp,
                       "Directory does not fit in FAT%d (capacity %.2f MB)",
                       s->fat_type, s->sector_count / 2000.0);
            return -1;
1001
        }
1002

1003 1004 1005 1006 1007 1008 1009
        /* fix fat for entry */
        if (fix_fat) {
            int j;
            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);
        }
1010 1011
    }

1012 1013 1014 1015 1016 1017
    mapping = array_get(&(s->mapping), 0);
    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);
1018

1019 1020
    s->current_mapping = NULL;

1021 1022
    bootsector = (bootsector_t *)(s->first_sectors
                                  + s->offset_to_bootsector * 0x200);
1023 1024 1025
    bootsector->jump[0]=0xeb;
    bootsector->jump[1]=0x3e;
    bootsector->jump[2]=0x90;
1026
    memcpy(bootsector->name, "MSWIN4.1", 8);
1027 1028 1029 1030
    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 */
1031
    bootsector->root_entries = cpu_to_le16(s->root_entries);
1032
    bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);
1033 1034
    /* media descriptor: hard disk=0xf8, floppy=0xf0 */
    bootsector->media_type = (s->offset_to_bootsector > 0 ? 0xf8 : 0xf0);
1035
    s->fat.pointer[0] = bootsector->media_type;
1036
    bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);
1037 1038
    bootsector->sectors_per_track = cpu_to_le16(secs);
    bootsector->number_of_heads = cpu_to_le16(heads);
1039
    bootsector->hidden_sectors = cpu_to_le32(s->offset_to_bootsector);
1040
    bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);
1041

1042
    /* LATER TODO: if FAT32, this is wrong */
1043 1044
    /* drive_number: fda=0, hda=0x80 */
    bootsector->u.fat16.drive_number = s->offset_to_bootsector == 0 ? 0 : 0x80;
1045 1046 1047
    bootsector->u.fat16.signature=0x29;
    bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);

W
Wolfgang Bumiller 已提交
1048 1049
    memcpy(bootsector->u.fat16.volume_label, s->volume_label,
           sizeof(bootsector->u.fat16.volume_label));
1050 1051
    memcpy(bootsector->u.fat16.fat_type,
           s->fat_type == 12 ? "FAT12   " : "FAT16   ", 8);
1052 1053 1054 1055 1056
    bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;

    return 0;
}

B
bellard 已提交
1057
#ifdef DEBUG
1058
static BDRVVVFATState *vvv = NULL;
B
bellard 已提交
1059
#endif
1060

K
Kevin Wolf 已提交
1061
static int enable_write_target(BlockDriverState *bs, Error **errp);
1062 1063
static int is_consistent(BDRVVVFATState *s);

1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
static QemuOptsList runtime_opts = {
    .name = "vvfat",
    .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
    .desc = {
        {
            .name = "dir",
            .type = QEMU_OPT_STRING,
            .help = "Host directory to map to the vvfat device",
        },
        {
            .name = "fat-type",
            .type = QEMU_OPT_NUMBER,
            .help = "FAT type (12, 16 or 32)",
        },
        {
            .name = "floppy",
            .type = QEMU_OPT_BOOL,
            .help = "Create a floppy rather than a hard disk image",
        },
W
Wolfgang Bumiller 已提交
1083 1084 1085 1086 1087
        {
            .name = "label",
            .type = QEMU_OPT_STRING,
            .help = "Use a volume label other than QEMU VVFAT",
        },
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        {
            .name = "rw",
            .type = QEMU_OPT_BOOL,
            .help = "Make the image writable",
        },
        { /* end of list */ }
    },
};

static void vvfat_parse_filename(const char *filename, QDict *options,
                                 Error **errp)
{
    int fat_type = 0;
    bool floppy = false;
    bool rw = false;
    int i;

    if (!strstart(filename, "fat:", NULL)) {
        error_setg(errp, "File name string must start with 'fat:'");
        return;
    }

    /* Parse options */
    if (strstr(filename, ":32:")) {
        fat_type = 32;
    } else if (strstr(filename, ":16:")) {
        fat_type = 16;
    } else if (strstr(filename, ":12:")) {
        fat_type = 12;
    }

    if (strstr(filename, ":floppy:")) {
        floppy = true;
    }

    if (strstr(filename, ":rw:")) {
        rw = true;
    }

    /* Get the directory name without options */
    i = strrchr(filename, ':') - filename;
    assert(i >= 3);
    if (filename[i - 2] == ':' && qemu_isalpha(filename[i - 1])) {
        /* workaround for DOS drive names */
        filename += i - 1;
    } else {
        filename += i + 1;
    }

    /* Fill in the options QDict */
1138 1139 1140 1141
    qdict_put_str(options, "dir", filename);
    qdict_put_int(options, "fat-type", fat_type);
    qdict_put_bool(options, "floppy", floppy);
    qdict_put_bool(options, "rw", rw);
1142 1143
}

M
Max Reitz 已提交
1144 1145
static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,
                      Error **errp)
1146 1147
{
    BDRVVVFATState *s = bs->opaque;
1148 1149
    int cyls, heads, secs;
    bool floppy;
W
Wolfgang Bumiller 已提交
1150
    const char *dirname, *label;
1151 1152 1153
    QemuOpts *opts;
    Error *local_err = NULL;
    int ret;
1154

B
bellard 已提交
1155
#ifdef DEBUG
1156
    vvv = s;
B
bellard 已提交
1157
#endif
1158

1159
    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1160
    qemu_opts_absorb_qdict(opts, options, &local_err);
1161
    if (local_err) {
1162
        error_propagate(errp, local_err);
1163 1164 1165 1166 1167 1168
        ret = -EINVAL;
        goto fail;
    }

    dirname = qemu_opt_get(opts, "dir");
    if (!dirname) {
1169
        error_setg(errp, "vvfat block driver requires a 'dir' option");
1170 1171 1172 1173 1174 1175 1176
        ret = -EINVAL;
        goto fail;
    }

    s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);
    floppy = qemu_opt_get_bool(opts, "floppy", false);

W
Wolfgang Bumiller 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    memset(s->volume_label, ' ', sizeof(s->volume_label));
    label = qemu_opt_get(opts, "label");
    if (label) {
        size_t label_length = strlen(label);
        if (label_length > 11) {
            error_setg(errp, "vvfat label cannot be longer than 11 bytes");
            ret = -EINVAL;
            goto fail;
        }
        memcpy(s->volume_label, label, label_length);
K
Kevin Wolf 已提交
1187 1188
    } else {
        memcpy(s->volume_label, "QEMU VVFAT", 10);
W
Wolfgang Bumiller 已提交
1189 1190
    }

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    if (floppy) {
        /* 1.44MB or 2.88MB floppy.  2.88MB can be FAT12 (default) or FAT16. */
        if (!s->fat_type) {
            s->fat_type = 12;
            secs = 36;
            s->sectors_per_cluster = 2;
        } else {
            secs = s->fat_type == 12 ? 18 : 36;
            s->sectors_per_cluster = 1;
        }
        cyls = 80;
        heads = 2;
    } else {
        /* 32MB or 504MB disk*/
        if (!s->fat_type) {
            s->fat_type = 16;
        }
1208
        s->offset_to_bootsector = 0x3f;
1209 1210 1211 1212 1213 1214 1215
        cyls = s->fat_type == 12 ? 64 : 1024;
        heads = 16;
        secs = 63;
    }

    switch (s->fat_type) {
    case 32:
1216
            fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "
1217 1218 1219 1220 1221 1222
                "You are welcome to do so!\n");
        break;
    case 16:
    case 12:
        break;
    default:
1223
        error_setg(errp, "Valid FAT types are only 12, 16 and 32");
1224 1225 1226 1227 1228
        ret = -EINVAL;
        goto fail;
    }


1229 1230 1231 1232
    s->bs = bs;

    /* LATER TODO: if FAT32, adjust */
    s->sectors_per_cluster=0x10;
1233 1234 1235

    s->current_cluster=0xffffffff;

K
Kevin Wolf 已提交
1236
    s->qcow = NULL;
1237 1238 1239
    s->qcow_filename = NULL;
    s->fat2 = NULL;
    s->downcase_short_names = 1;
1240

1241 1242
    fprintf(stderr, "vvfat %s chs %d,%d,%d\n",
            dirname, cyls, heads, secs);
1243

1244
    s->sector_count = cyls * heads * secs - s->offset_to_bootsector;
1245

1246
    if (qemu_opt_get_bool(opts, "rw", false)) {
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
        if (!bdrv_is_read_only(bs)) {
            ret = enable_write_target(bs, errp);
            if (ret < 0) {
                goto fail;
            }
        } else {
            ret = -EPERM;
            error_setg(errp,
                       "Unable to set VVFAT to 'rw' when drive is read-only");
            goto fail;
        }
    } else  {
        /* read only is the default for safety */
        ret = bdrv_set_read_only(bs, true, &local_err);
1261
        if (ret < 0) {
1262
            error_propagate(errp, local_err);
1263 1264
            goto fail;
        }
T
ths 已提交
1265 1266
    }

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

1269
    if (init_directories(s, dirname, heads, secs, errp)) {
1270 1271
        ret = -EIO;
        goto fail;
1272
    }
1273

1274 1275
    s->sector_count = s->offset_to_root_dir
                    + s->sectors_per_cluster * s->cluster_count;
T
ths 已提交
1276

K
Kevin Wolf 已提交
1277 1278
    /* Disable migration when vvfat is used rw */
    if (s->qcow) {
1279 1280 1281 1282
        error_setg(&s->migration_blocker,
                   "The vvfat (rw) format used by node '%s' "
                   "does not support live migration",
                   bdrv_get_device_or_node_name(bs));
1283 1284 1285 1286 1287 1288
        ret = migrate_add_blocker(s->migration_blocker, &local_err);
        if (local_err) {
            error_propagate(errp, local_err);
            error_free(s->migration_blocker);
            goto fail;
        }
K
Kevin Wolf 已提交
1289 1290
    }

1291
    if (s->offset_to_bootsector > 0) {
1292 1293 1294 1295 1296
        init_mbr(s, cyls, heads, secs);
    }

    qemu_co_mutex_init(&s->lock);

1297 1298 1299 1300
    ret = 0;
fail:
    qemu_opts_del(opts);
    return ret;
1301 1302
}

1303 1304
static void vvfat_refresh_limits(BlockDriverState *bs, Error **errp)
{
1305
    bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
1306 1307
}

1308 1309 1310
static inline void vvfat_close_current_file(BDRVVVFATState *s)
{
    if(s->current_mapping) {
1311 1312 1313 1314 1315
        s->current_mapping = NULL;
        if (s->current_fd) {
                qemu_close(s->current_fd);
                s->current_fd = 0;
        }
1316
    }
1317
    s->current_cluster = -1;
1318 1319 1320 1321 1322 1323 1324 1325
}

/* 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) {
1326
        int index3;
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
        mapping_t* mapping;
        index3=(index1+index2)/2;
        mapping=array_get(&(s->mapping),index3);
        assert(mapping->begin < mapping->end);
        if(mapping->begin>=cluster_num) {
            assert(index2!=index3 || index2==0);
            if(index2==index3)
                return index1;
            index2=index3;
        } else {
            if(index1==index3)
                return mapping->end<=cluster_num ? index2 : index1;
            index1=index3;
        }
        assert(index1<=index2);
        DLOG(mapping=array_get(&(s->mapping),index1);
        assert(mapping->begin<=cluster_num);
        assert(index2 >= s->mapping.next ||
                ((mapping = array_get(&(s->mapping),index2)) &&
                mapping->end>cluster_num)));
1347 1348 1349
    }
}

A
Anthony Liguori 已提交
1350
static inline mapping_t* find_mapping_for_cluster(BDRVVVFATState* s,int cluster_num)
1351 1352
{
    int index=find_mapping_for_cluster_aux(s,cluster_num,0,s->mapping.next);
A
Anthony Liguori 已提交
1353
    mapping_t* mapping;
1354
    if(index>=s->mapping.next)
1355
        return NULL;
1356 1357
    mapping=array_get(&(s->mapping),index);
    if(mapping->begin>cluster_num)
1358
        return NULL;
1359
    assert(mapping->begin<=cluster_num && mapping->end>cluster_num);
1360 1361 1362
    return mapping;
}

A
Anthony Liguori 已提交
1363
static int open_file(BDRVVVFATState* s,mapping_t* mapping)
1364 1365
{
    if(!mapping)
1366
        return -1;
1367
    if(!s->current_mapping ||
1368 1369 1370 1371 1372 1373 1374 1375
            strcmp(s->current_mapping->path,mapping->path)) {
        /* open file */
        int fd = qemu_open(mapping->path, O_RDONLY | O_BINARY | O_LARGEFILE);
        if(fd<0)
            return -1;
        vvfat_close_current_file(s);
        s->current_fd = fd;
        s->current_mapping = mapping;
1376 1377 1378 1379 1380 1381 1382
    }
    return 0;
}

static inline int read_cluster(BDRVVVFATState *s,int cluster_num)
{
    if(s->current_cluster != cluster_num) {
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        int result=0;
        off_t offset;
        assert(!s->current_mapping || s->current_fd || (s->current_mapping->mode & MODE_DIRECTORY));
        if(!s->current_mapping
                || s->current_mapping->begin>cluster_num
                || s->current_mapping->end<=cluster_num) {
            /* binary search of mappings for file */
            mapping_t* mapping=find_mapping_for_cluster(s,cluster_num);

            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;
1397
read_cluster_directory:
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
                offset = s->cluster_size*(cluster_num-s->current_mapping->begin);
                s->cluster = (unsigned char*)s->directory.pointer+offset
                        + 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))
                return -2;
        } else if (s->current_mapping->mode & MODE_DIRECTORY)
            goto read_cluster_directory;

        assert(s->current_fd);

        offset=s->cluster_size*(cluster_num-s->current_mapping->begin)+s->current_mapping->info.file.offset;
        if(lseek(s->current_fd, offset, SEEK_SET)!=offset)
            return -3;
        s->cluster=s->cluster_buffer;
        result=read(s->current_fd,s->cluster,s->cluster_size);
        if(result<0) {
            s->current_cluster = -1;
            return -1;
        }
        s->current_cluster = cluster_num;
1424 1425 1426 1427
    }
    return 0;
}

1428
#ifdef DEBUG
A
Anthony Liguori 已提交
1429
static void print_direntry(const direntry_t* direntry)
1430
{
1431 1432 1433
    int j = 0;
    char buffer[1024];

K
Kevin Wolf 已提交
1434
    fprintf(stderr, "direntry %p: ", direntry);
1435
    if(!direntry)
1436
        return;
1437
    if(is_long_name(direntry)) {
1438 1439 1440
        unsigned char* c=(unsigned char*)direntry;
        int i;
        for(i=1;i<11 && c[i] && c[i]!=0xff;i+=2)
1441
#define ADD_CHAR(c) {buffer[j] = (c); if (buffer[j] < ' ') buffer[j] = 0xb0; j++;}
1442 1443 1444 1445 1446 1447 1448
            ADD_CHAR(c[i]);
        for(i=14;i<26 && c[i] && c[i]!=0xff;i+=2)
            ADD_CHAR(c[i]);
        for(i=28;i<32 && c[i] && c[i]!=0xff;i+=2)
            ADD_CHAR(c[i]);
        buffer[j] = 0;
        fprintf(stderr, "%s\n", buffer);
1449
    } else {
1450 1451 1452 1453 1454 1455 1456 1457
        int i;
        for(i=0;i<11;i++)
            ADD_CHAR(direntry->name[i]);
        buffer[j] = 0;
        fprintf(stderr,"%s attributes=0x%02x begin=%d size=%d\n",
                buffer,
                direntry->attributes,
                begin_of_direntry(direntry),le32_to_cpu(direntry->size));
1458 1459 1460
    }
}

A
Anthony Liguori 已提交
1461
static void print_mapping(const mapping_t* mapping)
1462
{
K
Kevin Wolf 已提交
1463 1464 1465 1466 1467
    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);

1468
    if (mapping->mode & MODE_DIRECTORY)
1469
        fprintf(stderr, "parent_mapping_index = %d, first_dir_index = %d\n", mapping->info.dir.parent_mapping_index, mapping->info.dir.first_dir_index);
1470
    else
1471
        fprintf(stderr, "offset = %d\n", mapping->info.file.offset);
1472
}
1473
#endif
1474

1475
static int vvfat_read(BlockDriverState *bs, int64_t sector_num,
1476
                    uint8_t *buf, int nb_sectors)
1477
{
1478
    BDRVVVFATState *s = bs->opaque;
1479 1480
    int i;

1481
    for(i=0;i<nb_sectors;i++,sector_num++) {
1482 1483 1484
        if (sector_num >= bs->total_sectors)
           return -1;
        if (s->qcow) {
1485
            int64_t n;
1486
            int ret;
1487 1488
            ret = bdrv_is_allocated(s->qcow->bs, sector_num * BDRV_SECTOR_SIZE,
                                    (nb_sectors - i) * BDRV_SECTOR_SIZE, &n);
1489 1490 1491 1492
            if (ret < 0) {
                return ret;
            }
            if (ret) {
1493 1494 1495 1496 1497
                DLOG(fprintf(stderr, "sectors %" PRId64 "+%" PRId64
                             " allocated\n", sector_num,
                             n >> BDRV_SECTOR_BITS));
                if (bdrv_read(s->qcow, sector_num, buf + i * 0x200,
                              n >> BDRV_SECTOR_BITS)) {
K
Kevin Wolf 已提交
1498 1499
                    return -1;
                }
1500 1501
                i += (n >> BDRV_SECTOR_BITS) - 1;
                sector_num += (n >> BDRV_SECTOR_BITS) - 1;
K
Kevin Wolf 已提交
1502 1503
                continue;
            }
1504 1505
            DLOG(fprintf(stderr, "sector %" PRId64 " not allocated\n",
                         sector_num));
1506
        }
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
        if (sector_num < s->offset_to_root_dir) {
            if (sector_num < s->offset_to_fat) {
                memcpy(buf + i * 0x200,
                       &(s->first_sectors[sector_num * 0x200]),
                       0x200);
            } else if (sector_num < s->offset_to_fat + s->sectors_per_fat) {
                memcpy(buf + i * 0x200,
                       &(s->fat.pointer[(sector_num
                                       - s->offset_to_fat) * 0x200]),
                       0x200);
            } else if (sector_num < s->offset_to_root_dir) {
                memcpy(buf + i * 0x200,
                       &(s->fat.pointer[(sector_num - s->offset_to_fat
                                       - s->sectors_per_fat) * 0x200]),
                       0x200);
            }
1523
        } else {
1524
            uint32_t sector = sector_num - s->offset_to_root_dir,
1525 1526 1527 1528 1529 1530 1531 1532 1533
            sector_offset_in_cluster=(sector%s->sectors_per_cluster),
            cluster_num=sector/s->sectors_per_cluster;
            if(cluster_num > s->cluster_count || read_cluster(s, cluster_num) != 0) {
                /* LATER TODO: strict: return -1; */
                memset(buf+i*0x200,0,0x200);
                continue;
            }
            memcpy(buf+i*0x200,s->cluster+sector_offset_in_cluster*0x200,0x200);
        }
1534 1535 1536 1537
    }
    return 0;
}

1538 1539 1540
static int coroutine_fn
vvfat_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                QEMUIOVector *qiov, int flags)
1541 1542 1543
{
    int ret;
    BDRVVVFATState *s = bs->opaque;
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
    int nb_sectors = bytes >> BDRV_SECTOR_BITS;
    void *buf;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    buf = g_try_malloc(bytes);
    if (bytes && buf == NULL) {
        return -ENOMEM;
    }

1556 1557 1558
    qemu_co_mutex_lock(&s->lock);
    ret = vvfat_read(bs, sector_num, buf, nb_sectors);
    qemu_co_mutex_unlock(&s->lock);
1559 1560 1561 1562

    qemu_iovec_from_buf(qiov, 0, buf, bytes);
    g_free(buf);

1563 1564 1565
    return ret;
}

1566
/* LATER TODO: statify all functions */
1567

1568 1569
/*
 * Idea of the write support (use snapshot):
1570
 *
1571 1572
 * 1. check if all data is consistent, recording renames, modifications,
 *    new files and directories (in s->commits).
1573
 *
1574
 * 2. if the data is not consistent, stop committing
1575
 *
1576 1577
 * 3. handle renames, and create new files and directories (do not yet
 *    write their contents)
1578
 *
1579 1580
 * 4. walk the directories, fixing the mapping and direntries, and marking
 *    the handled mappings as not deleted
1581
 *
1582
 * 5. commit the contents of the files
1583
 *
1584
 * 6. handle deleted files and directories
1585 1586 1587
 *
 */

A
Anthony Liguori 已提交
1588
typedef struct commit_t {
1589 1590
    char* path;
    union {
1591 1592 1593 1594
        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;
1595 1596 1597
    } param;
    /* DELETEs and RMDIRs are handled differently: see handle_deletes() */
    enum {
1598
        ACTION_RENAME, ACTION_WRITEOUT, ACTION_NEW_FILE, ACTION_MKDIR
1599
    } action;
A
Anthony Liguori 已提交
1600
} commit_t;
1601

1602
static void clear_commits(BDRVVVFATState* s)
1603 1604
{
    int i;
1605 1606
DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));
    for (i = 0; i < s->commits.next; i++) {
1607 1608 1609 1610
        commit_t* commit = array_get(&(s->commits), i);
        assert(commit->path || commit->action == ACTION_WRITEOUT);
        if (commit->action != ACTION_WRITEOUT) {
            assert(commit->path);
1611
            g_free(commit->path);
1612 1613
        } else
            assert(commit->path == NULL);
1614
    }
1615
    s->commits.next = 0;
1616 1617
}

1618
static void schedule_rename(BDRVVVFATState* s,
1619
        uint32_t cluster, char* new_path)
1620
{
A
Anthony Liguori 已提交
1621
    commit_t* commit = array_get_next(&(s->commits));
1622 1623 1624
    commit->path = new_path;
    commit->param.rename.cluster = cluster;
    commit->action = ACTION_RENAME;
1625 1626
}

1627
static void schedule_writeout(BDRVVVFATState* s,
1628
        int dir_index, uint32_t modified_offset)
1629
{
A
Anthony Liguori 已提交
1630
    commit_t* commit = array_get_next(&(s->commits));
1631 1632 1633 1634
    commit->path = NULL;
    commit->param.writeout.dir_index = dir_index;
    commit->param.writeout.modified_offset = modified_offset;
    commit->action = ACTION_WRITEOUT;
1635 1636
}

1637
static void schedule_new_file(BDRVVVFATState* s,
1638
        char* path, uint32_t first_cluster)
1639
{
A
Anthony Liguori 已提交
1640
    commit_t* commit = array_get_next(&(s->commits));
1641 1642 1643 1644 1645 1646 1647
    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 已提交
1648
    commit_t* commit = array_get_next(&(s->commits));
1649 1650 1651 1652 1653 1654
    commit->path = path;
    commit->param.mkdir.cluster = cluster;
    commit->action = ACTION_MKDIR;
}

typedef struct {
1655 1656 1657 1658 1659 1660
    /*
     * 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];
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
    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,
1673
        const direntry_t* direntry)
1674 1675 1676 1677 1678
{
    int i, j, offset;
    const unsigned char* pointer = (const unsigned char*)direntry;

    if (!is_long_name(direntry))
1679
        return 1;
1680 1681

    if (pointer[0] & 0x40) {
1682 1683 1684 1685
        lfn->sequence_number = pointer[0] & 0x3f;
        lfn->checksum = pointer[13];
        lfn->name[0] = 0;
        lfn->name[lfn->sequence_number * 13] = 0;
1686
    } else if ((pointer[0] & 0x3f) != --lfn->sequence_number)
1687
        return -1;
1688
    else if (pointer[13] != lfn->checksum)
1689
        return -2;
1690
    else if (pointer[12] || pointer[26] || pointer[27])
1691
        return -3;
1692 1693 1694

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

1700 1701 1702 1703 1704 1705
        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;
1706
    }
1707 1708

    if (pointer[0] & 0x40)
1709
        lfn->len = offset + strlen((char*)lfn->name + offset);
1710

1711 1712 1713
    return 0;
}

1714 1715
/* returns 0 if successful, >0 if no short_name, and <0 on error */
static int parse_short_name(BDRVVVFATState* s,
1716
        long_file_name* lfn, direntry_t* direntry)
1717
{
1718
    int i, j;
1719

1720
    if (!is_short_name(direntry))
1721
        return 1;
1722 1723 1724

    for (j = 7; j >= 0 && direntry->name[j] == ' '; j--);
    for (i = 0; i <= j; i++) {
1725 1726 1727 1728 1729 1730
        if (direntry->name[i] <= ' ' || direntry->name[i] > 0x7f)
            return -1;
        else if (s->downcase_short_names)
            lfn->name[i] = qemu_tolower(direntry->name[i]);
        else
            lfn->name[i] = direntry->name[i];
1731 1732
    }

1733 1734
    for (j = 2; j >= 0 && direntry->name[8 + j] == ' '; j--) {
    }
1735
    if (j >= 0) {
1736 1737 1738
        lfn->name[i++] = '.';
        lfn->name[i + j + 1] = '\0';
        for (;j >= 0; j--) {
1739 1740 1741 1742 1743 1744 1745 1746
            uint8_t c = direntry->name[8 + j];
            if (c <= ' ' || c > 0x7f) {
                return -2;
            } else if (s->downcase_short_names) {
                lfn->name[i + j] = qemu_tolower(c);
            } else {
                lfn->name[i + j] = c;
            }
1747
        }
1748
    } else
1749
        lfn->name[i + j + 1] = '\0';
1750

1751 1752 1753
    if (lfn->name[0] == 0x05) {
        lfn->name[0] = 0xe5;
    }
T
ths 已提交
1754
    lfn->len = strlen((char*)lfn->name);
1755 1756

    return 0;
1757 1758
}

1759
static inline uint32_t modified_fat_get(BDRVVVFATState* s,
1760
        unsigned int cluster)
1761
{
1762
    if (cluster < s->last_cluster_of_root_directory) {
1763 1764 1765 1766
        if (cluster + 1 == s->last_cluster_of_root_directory)
            return s->max_fat_value;
        else
            return cluster + 1;
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    }

    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;
    }
}

1781 1782
static inline bool cluster_was_modified(BDRVVVFATState *s,
                                        uint32_t cluster_num)
1783 1784
{
    int was_modified = 0;
1785
    int i;
1786

K
Kevin Wolf 已提交
1787 1788 1789
    if (s->qcow == NULL) {
        return 0;
    }
1790

K
Kevin Wolf 已提交
1791 1792
    for (i = 0; !was_modified && i < s->sectors_per_cluster; i++) {
        was_modified = bdrv_is_allocated(s->qcow->bs,
1793 1794 1795
                                         (cluster2sector(s, cluster_num) +
                                          i) * BDRV_SECTOR_SIZE,
                                         BDRV_SECTOR_SIZE, NULL);
K
Kevin Wolf 已提交
1796
    }
1797

1798 1799 1800 1801 1802 1803 1804
    /*
     * Note that this treats failures to learn allocation status the
     * same as if an allocation has occurred.  It's as safe as
     * anything else, given that a failure to learn allocation status
     * will probably result in more failures.
     */
    return !!was_modified;
1805 1806
}

1807
static const char* get_basename(const char* path)
1808
{
1809 1810
    char* basename = strrchr(path, '/');
    if (basename == NULL)
1811
        return path;
1812
    else
1813
        return basename + 1; /* strip '/' */
1814 1815
}

1816 1817 1818 1819 1820 1821 1822 1823 1824
/*
 * 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 已提交
1825
} used_t;
1826

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
/*
 * 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,
1838
        direntry_t* direntry, const char* path)
1839
{
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
    /*
     * 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 已提交
1864
    mapping_t* mapping = NULL;
1865
    const char* basename2 = NULL;
1866

1867
    vvfat_close_current_file(s);
1868

1869 1870
    /* the root directory */
    if (cluster_num == 0)
1871
        return 0;
1872

1873 1874
    /* write support */
    if (s->qcow) {
1875
        basename2 = get_basename(path);
1876

1877
        mapping = find_mapping_for_cluster(s, cluster_num);
1878

1879 1880
        if (mapping) {
            const char* basename;
B
bellard 已提交
1881

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

1885
            basename = get_basename(mapping->path);
1886

1887
            assert(mapping->mode & MODE_NORMAL);
1888

1889 1890 1891 1892 1893 1894 1895
            /* rename */
            if (strcmp(basename, basename2))
                schedule_rename(s, cluster_num, g_strdup(path));
        } else if (is_file(direntry))
            /* new file */
            schedule_new_file(s, g_strdup(path), cluster_num);
        else {
1896
            abort();
1897 1898
            return 0;
        }
1899 1900
    }

1901
    while(1) {
1902 1903 1904 1905 1906 1907
        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);
1908

1909

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

1913 1914 1915 1916
                    /* 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 */
1917
                        abort();
1918 1919 1920
                        copy_it = 1;
                    } else if (offset == 0) {
                        const char* basename = get_basename(mapping->path);
1921

1922 1923 1924 1925
                        if (strcmp(basename, basename2))
                            copy_it = 1;
                        first_mapping_index = array_index(&(s->mapping), mapping);
                    }
1926

1927 1928
                    if (mapping->first_mapping_index != first_mapping_index
                            && mapping->info.file.offset > 0) {
1929
                        abort();
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
                        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) {
1942
                int i;
1943 1944 1945 1946 1947 1948 1949
                /*
                 * 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);
K
Kevin Wolf 已提交
1950
                for (i = 0; i < s->sectors_per_cluster; i++) {
K
Kevin Wolf 已提交
1951 1952
                    int res;

1953 1954 1955
                    res = bdrv_is_allocated(s->qcow->bs,
                                            (offset + i) * BDRV_SECTOR_SIZE,
                                            BDRV_SECTOR_SIZE, NULL);
1956 1957 1958
                    if (res < 0) {
                        return -1;
                    }
K
Kevin Wolf 已提交
1959 1960 1961
                    if (!res) {
                        res = vvfat_read(s->bs, offset, s->cluster_buffer, 1);
                        if (res) {
K
Kevin Wolf 已提交
1962 1963
                            return -1;
                        }
1964
                        res = bdrv_write(s->qcow, offset, s->cluster_buffer, 1);
K
Kevin Wolf 已提交
1965
                        if (res) {
K
Kevin Wolf 已提交
1966 1967 1968 1969
                            return -2;
                        }
                    }
                }
1970 1971
            }
        }
1972

1973 1974 1975 1976
        ret++;
        if (s->used_clusters[cluster_num] & USED_ANY)
            return 0;
        s->used_clusters[cluster_num] = USED_FILE;
1977

1978
        cluster_num = modified_fat_get(s, cluster_num);
1979

1980 1981 1982 1983
        if (fat_eof(s, cluster_num))
            return ret;
        else if (cluster_num < 2 || cluster_num > s->max_fat_value - 16)
            return -1;
1984

1985
        offset += s->cluster_size;
1986
    }
1987 1988
}

1989
/*
1990
 * This function looks at the modified data (qcow).
1991 1992 1993 1994
 * 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,
1995
        int cluster_num, const char* path)
1996
{
1997
    int ret = 0;
1998
    unsigned char* cluster = g_malloc(s->cluster_size);
A
Anthony Liguori 已提交
1999 2000
    direntry_t* direntries = (direntry_t*)cluster;
    mapping_t* mapping = find_mapping_for_cluster(s, cluster_num);
2001 2002 2003

    long_file_name lfn;
    int path_len = strlen(path);
K
Kevin Wolf 已提交
2004
    char path2[PATH_MAX + 1];
2005 2006

    assert(path_len < PATH_MAX); /* len was tested before! */
B
blueswir1 已提交
2007
    pstrcpy(path2, sizeof(path2), path);
2008 2009 2010 2011
    path2[path_len] = '/';
    path2[path_len + 1] = '\0';

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

2015
        assert(mapping->mode & MODE_DIRECTORY);
2016

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

2020 2021
        if (strcmp(basename, basename2))
            schedule_rename(s, cluster_num, g_strdup(path));
2022
    } else
2023 2024
        /* new directory */
        schedule_mkdir(s, cluster_num, g_strdup(path));
2025

2026 2027
    lfn_init(&lfn);
    do {
2028 2029
        int i;
        int subret = 0;
2030

2031
        ret++;
2032

2033 2034
        if (s->used_clusters[cluster_num] & USED_ANY) {
            fprintf(stderr, "cluster %d used more than once\n", (int)cluster_num);
2035
            goto fail;
2036 2037
        }
        s->used_clusters[cluster_num] = USED_DIRECTORY;
2038 2039

DLOG(fprintf(stderr, "read cluster %d (sector %d)\n", (int)cluster_num, (int)cluster2sector(s, cluster_num)));
2040 2041 2042 2043 2044
        subret = vvfat_read(s->bs, cluster2sector(s, cluster_num), cluster,
                s->sectors_per_cluster);
        if (subret) {
            fprintf(stderr, "Error fetching direntries\n");
        fail:
2045
            g_free(cluster);
2046 2047
            return 0;
        }
2048

2049 2050
        for (i = 0; i < 0x10 * s->sectors_per_cluster; i++) {
            int cluster_count = 0;
2051

2052
DLOG(fprintf(stderr, "check direntry %d:\n", i); print_direntry(direntries + i));
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
            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;
            }
            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;
                }
                if (subret > 0 || !strcmp((char*)lfn.name, ".")
                        || !strcmp((char*)lfn.name, ".."))
                    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 已提交
2081 2082
            pstrcpy(path2 + path_len + 1, sizeof(path2) - path_len - 1,
                    (char*)lfn.name);
2083

2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
            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 !=
L
Laurent Vivier 已提交
2099
            DIV_ROUND_UP(le32_to_cpu(direntries[i].size), s->cluster_size)) {
2100 2101 2102 2103
                    DLOG(fprintf(stderr, "Cluster count mismatch\n"));
                    goto fail;
                }
            } else
2104
                abort(); /* cluster_count = 0; */
2105

2106 2107
            ret += cluster_count;
        }
2108

2109
        cluster_num = modified_fat_get(s, cluster_num);
2110
    } while(!fat_eof(s, cluster_num));
2111

2112
    g_free(cluster);
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
    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) {
2137 2138 2139
        int size = 0x200 * s->sectors_per_fat;
        s->fat2 = g_malloc(size);
        memcpy(s->fat2, s->fat.pointer, size);
2140 2141
    }
    check = vvfat_read(s->bs,
2142
            s->offset_to_fat, s->fat2, s->sectors_per_fat);
2143
    if (check) {
2144 2145
        fprintf(stderr, "Could not copy fat\n");
        return 0;
2146 2147 2148
    }
    assert (s->used_clusters);
    for (i = 0; i < sector2cluster(s, s->sector_count); i++)
2149
        s->used_clusters[i] &= ~USED_ANY;
2150 2151 2152 2153 2154 2155

    clear_commits(s);

    /* mark every mapped file/directory as deleted.
     * (check_directory_consistency() will unmark those still present). */
    if (s->qcow)
2156 2157 2158 2159 2160
        for (i = 0; i < s->mapping.next; i++) {
            mapping_t* mapping = array_get(&(s->mapping), i);
            if (mapping->first_mapping_index < 0)
                mapping->mode |= MODE_DELETED;
        }
2161 2162 2163

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

2168 2169
    check = s->last_cluster_of_root_directory;
    for (i = check; i < sector2cluster(s, s->sector_count); i++) {
2170 2171 2172 2173 2174 2175 2176
        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++;
        }
2177

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

    if (check != used_clusters_count)
2186
        return 0;
2187 2188 2189 2190 2191

    return used_clusters_count;
}

static inline void adjust_mapping_indices(BDRVVVFATState* s,
2192
        int offset, int adjust)
2193 2194 2195 2196
{
    int i;

    for (i = 0; i < s->mapping.next; i++) {
2197
        mapping_t* mapping = array_get(&(s->mapping), i);
2198 2199

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

2203 2204 2205
        ADJUST_MAPPING_INDEX(first_mapping_index);
        if (mapping->mode & MODE_DIRECTORY)
            ADJUST_MAPPING_INDEX(info.dir.parent_mapping_index);
2206
    }
2207 2208 2209
}

/* insert or update mapping */
A
Anthony Liguori 已提交
2210
static mapping_t* insert_mapping(BDRVVVFATState* s,
2211
        uint32_t begin, uint32_t end)
2212 2213 2214 2215 2216 2217 2218 2219 2220
{
    /*
     * - 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 已提交
2221 2222
    mapping_t* mapping = NULL;
    mapping_t* first_mapping = array_get(&(s->mapping), 0);
2223 2224

    if (index < s->mapping.next && (mapping = array_get(&(s->mapping), index))
2225 2226 2227 2228
            && mapping->begin < begin) {
        mapping->end = begin;
        index++;
        mapping = array_get(&(s->mapping), index);
2229 2230
    }
    if (index >= s->mapping.next || mapping->begin > begin) {
2231 2232 2233
        mapping = array_insert(&(s->mapping), index, 1);
        mapping->path = NULL;
        adjust_mapping_indices(s, index, +1);
2234 2235 2236 2237
    }

    mapping->begin = begin;
    mapping->end = end;
2238

A
Anthony Liguori 已提交
2239
DLOG(mapping_t* next_mapping;
2240 2241 2242 2243
assert(index + 1 >= s->mapping.next ||
((next_mapping = array_get(&(s->mapping), index + 1)) &&
 next_mapping->begin >= end)));

A
Anthony Liguori 已提交
2244
    if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
2245 2246
        s->current_mapping = array_get(&(s->mapping),
                s->current_mapping - first_mapping);
2247 2248 2249 2250 2251 2252

    return mapping;
}

static int remove_mapping(BDRVVVFATState* s, int mapping_index)
{
A
Anthony Liguori 已提交
2253 2254
    mapping_t* mapping = array_get(&(s->mapping), mapping_index);
    mapping_t* first_mapping = array_get(&(s->mapping), 0);
2255 2256

    /* free mapping */
2257 2258 2259
    if (mapping->first_mapping_index < 0) {
        g_free(mapping->path);
    }
2260 2261 2262 2263 2264 2265 2266

    /* 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 已提交
2267
    if (s->current_mapping && first_mapping != (mapping_t*)s->mapping.pointer)
2268 2269
        s->current_mapping = array_get(&(s->mapping),
                s->current_mapping - first_mapping);
2270 2271 2272 2273

    return 0;
}

2274 2275 2276 2277
static void adjust_dirindices(BDRVVVFATState* s, int offset, int adjust)
{
    int i;
    for (i = 0; i < s->mapping.next; i++) {
2278 2279 2280 2281 2282 2283
        mapping_t* mapping = array_get(&(s->mapping), i);
        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;
2284 2285
    }
}
2286

A
Anthony Liguori 已提交
2287
static direntry_t* insert_direntries(BDRVVVFATState* s,
2288
        int dir_index, int count)
2289
{
2290 2291 2292 2293
    /*
     * make room in s->directory,
     * adjust_dirindices
     */
A
Anthony Liguori 已提交
2294
    direntry_t* result = array_insert(&(s->directory), dir_index, count);
2295
    if (result == NULL)
2296
        return NULL;
2297
    adjust_dirindices(s, dir_index, count);
2298 2299 2300
    return result;
}

2301 2302 2303 2304
static int remove_direntries(BDRVVVFATState* s, int dir_index, int count)
{
    int ret = array_remove_slice(&(s->directory), dir_index, count);
    if (ret)
2305
        return ret;
2306 2307 2308
    adjust_dirindices(s, dir_index, -count);
    return 0;
}
2309

2310 2311 2312 2313 2314 2315 2316
/*
 * 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,
2317
        uint32_t first_cluster, int dir_index)
2318
{
A
Anthony Liguori 已提交
2319 2320
    mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
    direntry_t* direntry = array_get(&(s->directory), dir_index);
2321 2322 2323 2324 2325 2326 2327 2328 2329
    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)) ?
2330
        MODE_DIRECTORY : MODE_NORMAL;
2331 2332

    while (!fat_eof(s, cluster)) {
2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
        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);
            mapping_t* next_mapping = i >= s->mapping.next ? NULL :
                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;
            next_mapping->first_mapping_index =
                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;
        }

        cluster = c1;
2388
    }
2389 2390 2391 2392

    return 0;
}

2393
static int commit_direntries(BDRVVVFATState* s,
2394
        int dir_index, int parent_mapping_index)
2395
{
A
Anthony Liguori 已提交
2396
    direntry_t* direntry = array_get(&(s->directory), dir_index);
2397
    uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);
A
Anthony Liguori 已提交
2398
    mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418

    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) {
2419 2420
        old_cluster_count = new_cluster_count =
            s->last_cluster_of_root_directory;
2421
    } else {
2422 2423 2424
        for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
                c = fat_get(s, c))
            old_cluster_count++;
2425

2426 2427 2428
        for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);
                c = modified_fat_get(s, c))
            new_cluster_count++;
2429
    }
2430

2431
    if (new_cluster_count > old_cluster_count) {
2432 2433 2434 2435
        if (insert_direntries(s,
                current_dir_index + factor * old_cluster_count,
                factor * (new_cluster_count - old_cluster_count)) == NULL)
            return -1;
2436
    } else if (new_cluster_count < old_cluster_count)
2437 2438 2439
        remove_direntries(s,
                current_dir_index + factor * new_cluster_count,
                factor * (old_cluster_count - new_cluster_count));
2440 2441

    for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {
K
Kevin Wolf 已提交
2442
        direntry_t *first_direntry;
2443 2444 2445 2446 2447
        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;
K
Kevin Wolf 已提交
2448 2449 2450 2451 2452

        /* The first directory entry on the filesystem is the volume name */
        first_direntry = (direntry_t*) s->directory.pointer;
        assert(!memcmp(first_direntry->name, s->volume_label, 11));

2453
        current_dir_index += factor;
2454
    }
2455

2456 2457
    ret = commit_mappings(s, first_cluster, dir_index);
    if (ret)
2458
        return ret;
2459 2460 2461

    /* recurse */
    for (i = 0; i < factor * new_cluster_count; i++) {
2462 2463 2464 2465 2466 2467 2468 2469 2470
        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;
        }
2471
    }
2472

2473 2474
    return 0;
}
2475

2476 2477 2478
/* commit one file (adjust contents, adjust mapping),
   return first_mapping_index */
static int commit_one_file(BDRVVVFATState* s,
2479
        int dir_index, uint32_t offset)
2480
{
A
Anthony Liguori 已提交
2481
    direntry_t* direntry = array_get(&(s->directory), dir_index);
2482 2483
    uint32_t c = begin_of_direntry(direntry);
    uint32_t first_cluster = c;
A
Anthony Liguori 已提交
2484
    mapping_t* mapping = find_mapping_for_cluster(s, c);
2485
    uint32_t size = filesize_of_direntry(direntry);
2486
    char* cluster = g_malloc(s->cluster_size);
2487 2488 2489 2490 2491 2492 2493
    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)
2494
        c = modified_fat_get(s, c);
2495

2496
    fd = qemu_open(mapping->path, O_RDWR | O_CREAT | O_BINARY, 0666);
2497
    if (fd < 0) {
2498 2499
        fprintf(stderr, "Could not open %s... (%s, %d)\n", mapping->path,
                strerror(errno), errno);
2500
        g_free(cluster);
2501
        return fd;
2502
    }
2503 2504
    if (offset > 0) {
        if (lseek(fd, offset, SEEK_SET) != offset) {
2505
            qemu_close(fd);
2506 2507 2508 2509
            g_free(cluster);
            return -3;
        }
    }
2510 2511

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

2517
        c1 = modified_fat_get(s, c);
2518

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

2522 2523
        ret = vvfat_read(s->bs, cluster2sector(s, c),
            (uint8_t*)cluster, (rest_size + 0x1ff) / 0x200);
2524

2525
        if (ret < 0) {
2526
            qemu_close(fd);
2527 2528 2529
            g_free(cluster);
            return ret;
        }
2530

2531
        if (write(fd, cluster, rest_size) < 0) {
2532
            qemu_close(fd);
2533 2534 2535
            g_free(cluster);
            return -2;
        }
2536

2537 2538
        offset += rest_size;
        c = c1;
2539 2540
    }

2541 2542
    if (ftruncate(fd, size)) {
        perror("ftruncate()");
2543
        qemu_close(fd);
2544
        g_free(cluster);
2545 2546
        return -4;
    }
2547
    qemu_close(fd);
2548
    g_free(cluster);
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

    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++) {
2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
        mapping_t* mapping = array_get(&(s->mapping), i);
        if (mapping->mode & MODE_DELETED) {
            fprintf(stderr, "deleted\n");
            continue;
        }
        assert(mapping->dir_index < s->directory.next);
        direntry_t* direntry = array_get(&(s->directory), mapping->dir_index);
        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);
        }
2571 2572 2573
    }
}

2574 2575
/* test, if all direntries have mappings */
static void check2(BDRVVVFATState* s)
2576 2577
{
    int i;
2578
    int first_mapping = -1;
2579

2580
    for (i = 0; i < s->directory.next; i++) {
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
        direntry_t* direntry = array_get(&(s->directory), i);

        if (is_short_name(direntry) && begin_of_direntry(direntry)) {
            mapping_t* mapping = find_mapping_for_cluster(s, begin_of_direntry(direntry));
            assert(mapping);
            assert(mapping->dir_index == i || is_dot(direntry));
            assert(mapping->begin == begin_of_direntry(direntry) || is_dot(direntry));
        }

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

            for (j = 0; j < s->mapping.next; j++) {
                mapping_t* mapping = array_get(&(s->mapping), j);
                if (mapping->mode & MODE_DELETED)
                    continue;
                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 {
                            mapping_t* parent = array_get(&(s->mapping), mapping->info.dir.parent_mapping_index);
                            assert(parent->mode & MODE_DIRECTORY);
                            assert(parent->info.dir.first_dir_index < mapping->info.dir.first_dir_index);
                        }
                    }
                }
            }
            if (count == 0)
                first_mapping = -1;
        }
2618 2619 2620
    }
}
#endif
2621

2622 2623 2624
static int handle_renames_and_mkdirs(BDRVVVFATState* s)
{
    int i;
2625

2626 2627 2628
#ifdef DEBUG
    fprintf(stderr, "handle_renames\n");
    for (i = 0; i < s->commits.next; i++) {
2629 2630
        commit_t* commit = array_get(&(s->commits), i);
        fprintf(stderr, "%d, %s (%d, %d)\n", i, commit->path ? commit->path : "(null)", commit->param.rename.cluster, commit->action);
2631 2632 2633 2634
    }
#endif

    for (i = 0; i < s->commits.next;) {
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
        commit_t* commit = array_get(&(s->commits), i);
        if (commit->action == ACTION_RENAME) {
            mapping_t* mapping = find_mapping_for_cluster(s,
                    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;
                direntry_t* direntry = array_get(&(s->directory),
                        mapping->info.dir.first_dir_index);
                uint32_t c = mapping->begin;
                int i = 0;

                /* recurse */
                while (!fat_eof(s, c)) {
                    do {
                        direntry_t* d = direntry + i;

                        if (is_file(d) || (is_directory(d) && !is_dot(d))) {
                            mapping_t* m = find_mapping_for_cluster(s,
                                    begin_of_direntry(d));
                            int l = strlen(m->path);
                            char* new_path = g_malloc(l + diff + 1);

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

B
blueswir1 已提交
2668 2669 2670
                            pstrcpy(new_path, l + diff + 1, mapping->path);
                            pstrcpy(new_path + l1, l + diff + 1 - l1,
                                    m->path + l2);
2671

2672 2673 2674 2675 2676 2677 2678
                            schedule_rename(s, m->begin, new_path);
                        }
                        i++;
                    } while((i % (0x10 * s->sectors_per_cluster)) != 0);
                    c = fat_get(s, c);
                }
            }
2679

2680
            g_free(old_path);
2681 2682 2683 2684 2685
            array_remove(&(s->commits), i);
            continue;
        } else if (commit->action == ACTION_MKDIR) {
            mapping_t* mapping;
            int j, parent_path_len;
2686

B
bellard 已提交
2687 2688 2689 2690 2691 2692 2693
#ifdef __MINGW32__
            if (mkdir(commit->path))
                return -5;
#else
            if (mkdir(commit->path, 0755))
                return -5;
#endif
2694

2695 2696 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
            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++) {
                mapping_t* m = array_get(&(s->mapping), j);
                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++;
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
    }
    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++) {
2740 2741 2742
        commit_t* commit = array_get(&(s->commits), i);
        switch(commit->action) {
        case ACTION_RENAME: case ACTION_MKDIR:
2743
            abort();
2744 2745 2746
            fail = -2;
            break;
        case ACTION_WRITEOUT: {
B
Blue Swirl 已提交
2747 2748
#ifndef NDEBUG
            /* these variables are only used by assert() below */
2749 2750 2751 2752
            direntry_t* entry = array_get(&(s->directory),
                    commit->param.writeout.dir_index);
            uint32_t begin = begin_of_direntry(entry);
            mapping_t* mapping = find_mapping_for_cluster(s, begin);
B
Blue Swirl 已提交
2753
#endif
2754

2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
            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;
            mapping_t* mapping = find_mapping_for_cluster(s, begin);
            direntry_t* entry;
            int i;

            /* 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;
            }

            if (i >= s->directory.next) {
                fail = -6;
                continue;
            }

            /* 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:
2804
            abort();
2805
        }
2806 2807
    }
    if (i > 0 && array_remove_slice(&(s->commits), 0, i))
2808
        return -1;
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
    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) {
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
        deferred = 0;
        deleted = 0;

        for (i = 1; i < s->mapping.next; i++) {
            mapping_t* mapping = array_get(&(s->mapping), i);
            if (mapping->mode & MODE_DELETED) {
                direntry_t* entry = array_get(&(s->directory),
                        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;
                        }

                        for (j = 1; j < s->mapping.next; j++) {
                            mapping_t* m = array_get(&(s->mapping), j);
                            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;
                        }
                        remove_direntries(s, first_dir_index,
                                next_dir_index - first_dir_index);

                        deleted++;
                    }
                } else {
                    if (unlink(mapping->path))
                        return -4;
                    deleted++;
                }
                DLOG(fprintf(stderr, "DELETE (%d)\n", i); print_mapping(mapping); print_direntry(entry));
                remove_mapping(s, i);
            }
        }
2866
    }
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884

    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)
2885
        return 0;
2886 2887 2888 2889 2890

    vvfat_close_current_file(s);

    ret = handle_renames_and_mkdirs(s);
    if (ret) {
2891
        fprintf(stderr, "Error handling renames (%d)\n", ret);
2892
        abort();
2893
        return ret;
2894 2895
    }

2896
    /* copy FAT (with bdrv_read) */
2897 2898 2899 2900 2901
    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) {
2902
        fprintf(stderr, "Fatal: error while committing (%d)\n", ret);
2903
        abort();
2904
        return ret;
2905 2906 2907 2908
    }

    ret = handle_commits(s);
    if (ret) {
2909
        fprintf(stderr, "Error handling commits (%d)\n", ret);
2910
        abort();
2911
        return ret;
2912 2913 2914 2915
    }

    ret = handle_deletes(s);
    if (ret) {
2916
        fprintf(stderr, "Error deleting\n");
2917
        abort();
2918
        return ret;
2919 2920
    }

K
Kevin Wolf 已提交
2921 2922
    if (s->qcow->bs->drv->bdrv_make_empty) {
        s->qcow->bs->drv->bdrv_make_empty(s->qcow->bs);
K
Kevin Wolf 已提交
2923
    }
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935

    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))
2936
        return -1;
2937 2938 2939
    return do_commit(s);
}

2940
static int vvfat_write(BlockDriverState *bs, int64_t sector_num,
2941 2942
                    const uint8_t *buf, int nb_sectors)
{
2943
    BDRVVVFATState *s = bs->opaque;
2944 2945 2946 2947
    int i, ret;

DLOG(checkpoint());

2948 2949 2950 2951 2952
    /* Check if we're operating in read-only mode */
    if (s->qcow == NULL) {
        return -EACCES;
    }

2953 2954 2955 2956 2957 2958 2959 2960
    vvfat_close_current_file(s);

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

2961
    if (sector_num < s->offset_to_fat)
2962
        return -1;
2963 2964

    for (i = sector2cluster(s, sector_num);
2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011
            i <= sector2cluster(s, sector_num + nb_sectors - 1);) {
        mapping_t* mapping = find_mapping_for_cluster(s, i);
        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;
                const direntry_t* direntries;
                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;
                dir_index  = mapping->dir_index +
                    0x10 * (begin - mapping->begin * s->sectors_per_cluster);
                direntries = (direntry_t*)(buf + 0x200 * (begin - sector_num));

                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),
                                    sizeof(direntry_t))) {
                            fprintf(stderr, "Warning: tried to write to write-protected file\n");
                            return -1;
                        }
                    }
                }
            }
            i = mapping->end;
        } else
            i++;
3012 3013 3014 3015 3016 3017
    }

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

    for (i = sector2cluster(s, sector_num);
3025 3026 3027
            i <= sector2cluster(s, sector_num + nb_sectors - 1); i++)
        if (i >= 0)
            s->used_clusters[i] |= USED_ALLOCATED;
3028 3029 3030 3031 3032 3033 3034 3035 3036

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

DLOG(checkpoint());
    return 0;
}

3037 3038 3039
static int coroutine_fn
vvfat_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                 QEMUIOVector *qiov, int flags)
3040 3041 3042
{
    int ret;
    BDRVVVFATState *s = bs->opaque;
3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
    uint64_t sector_num = offset >> BDRV_SECTOR_BITS;
    int nb_sectors = bytes >> BDRV_SECTOR_BITS;
    void *buf;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    buf = g_try_malloc(bytes);
    if (bytes && buf == NULL) {
        return -ENOMEM;
    }
    qemu_iovec_to_buf(qiov, 0, buf, bytes);

3056 3057 3058
    qemu_co_mutex_lock(&s->lock);
    ret = vvfat_write(bs, sector_num, buf, nb_sectors);
    qemu_co_mutex_unlock(&s->lock);
3059 3060 3061

    g_free(buf);

3062 3063 3064
    return ret;
}

3065
static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,
3066
        int64_t sector_num, int nb_sectors, int *n, BlockDriverState **file)
3067
{
3068
    *n = bs->total_sectors - sector_num;
3069 3070 3071 3072 3073 3074
    if (*n > nb_sectors) {
        *n = nb_sectors;
    } else if (*n < 0) {
        return 0;
    }
    return BDRV_BLOCK_DATA;
3075 3076
}

3077 3078 3079 3080
static int coroutine_fn
write_target_commit(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                    QEMUIOVector *qiov, int flags)
{
P
Paolo Bonzini 已提交
3081 3082
    int ret;

3083
    BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
P
Paolo Bonzini 已提交
3084 3085 3086 3087 3088
    qemu_co_mutex_lock(&s->lock);
    ret = try_commit(s);
    qemu_co_mutex_unlock(&s->lock);

    return ret;
3089 3090 3091
}

static void write_target_close(BlockDriverState *bs) {
3092
    BDRVVVFATState* s = *((BDRVVVFATState**) bs->opaque);
K
Kevin Wolf 已提交
3093
    bdrv_unref_child(s->bs, s->qcow);
3094
    g_free(s->qcow_filename);
3095 3096 3097
}

static BlockDriver vvfat_write_target = {
3098
    .format_name        = "vvfat_write_target",
3099
    .instance_size      = sizeof(void*),
3100
    .bdrv_co_pwritev    = write_target_commit,
3101
    .bdrv_close         = write_target_close,
3102 3103
};

K
Kevin Wolf 已提交
3104 3105
static void vvfat_qcow_options(int *child_flags, QDict *child_options,
                               int parent_flags, QDict *parent_options)
3106
{
3107 3108
    qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "off");
    *child_flags = BDRV_O_NO_FLUSH;
K
Kevin Wolf 已提交
3109 3110 3111 3112 3113 3114 3115 3116 3117
}

static const BdrvChildRole child_vvfat_qcow = {
    .inherit_options    = vvfat_qcow_options,
};

static int enable_write_target(BlockDriverState *bs, Error **errp)
{
    BDRVVVFATState *s = bs->opaque;
3118
    BlockDriver *bdrv_qcow = NULL;
3119
    BlockDriverState *backing;
3120
    QemuOpts *opts = NULL;
K
Kevin Wolf 已提交
3121
    int ret;
3122
    int size = sector2cluster(s, s->sector_count);
3123 3124
    QDict *options;

3125 3126
    s->used_clusters = calloc(size, 1);

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

3129 3130
    s->qcow_filename = g_malloc(PATH_MAX);
    ret = get_tmp_filename(s->qcow_filename, PATH_MAX);
3131
    if (ret < 0) {
3132
        error_setg_errno(errp, -ret, "can't create temporary file");
3133
        goto err;
3134
    }
K
Kevin Wolf 已提交
3135 3136

    bdrv_qcow = bdrv_find_format("qcow");
3137 3138 3139 3140 3141 3142
    if (!bdrv_qcow) {
        error_setg(errp, "Failed to locate qcow driver");
        ret = -ENOENT;
        goto err;
    }

C
Chunyan Liu 已提交
3143
    opts = qemu_opts_create(bdrv_qcow->create_opts, NULL, 0, &error_abort);
3144 3145
    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s->sector_count * 512,
                        &error_abort);
3146
    qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, "fat:", &error_abort);
K
Kevin Wolf 已提交
3147

C
Chunyan Liu 已提交
3148
    ret = bdrv_create(bdrv_qcow, s->qcow_filename, opts, errp);
3149
    qemu_opts_del(opts);
3150 3151 3152
    if (ret < 0) {
        goto err;
    }
K
Kevin Wolf 已提交
3153

3154
    options = qdict_new();
3155
    qdict_put_str(options, "write-target.driver", "qcow");
K
Kevin Wolf 已提交
3156 3157
    s->qcow = bdrv_open_child(s->qcow_filename, options, "write-target", bs,
                              &child_vvfat_qcow, false, errp);
3158
    QDECREF(options);
M
Max Reitz 已提交
3159 3160
    if (!s->qcow) {
        ret = -EINVAL;
3161
        goto err;
K
Kevin Wolf 已提交
3162
    }
3163 3164 3165 3166 3167

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

3168 3169 3170 3171
    backing = bdrv_new_open_driver(&vvfat_write_target, NULL, BDRV_O_ALLOW_RDWR,
                                   &error_abort);
    *(void**) backing->opaque = s;

3172
    bdrv_set_backing_hd(s->bs, backing, &error_abort);
3173 3174
    bdrv_unref(backing);

3175
    return 0;
3176 3177 3178 3179 3180

err:
    g_free(s->qcow_filename);
    s->qcow_filename = NULL;
    return ret;
3181 3182
}

K
Kevin Wolf 已提交
3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
static void vvfat_child_perm(BlockDriverState *bs, BdrvChild *c,
                             const BdrvChildRole *role,
                             uint64_t perm, uint64_t shared,
                             uint64_t *nperm, uint64_t *nshared)
{
    BDRVVVFATState *s = bs->opaque;

    assert(c == s->qcow || role == &child_backing);

    if (c == s->qcow) {
        /* This is a private node, nobody should try to attach to it */
        *nperm = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
        *nshared = BLK_PERM_WRITE_UNCHANGED;
    } else {
        /* The backing file is there so 'commit' can use it. vvfat doesn't
         * access it in any way. */
        *nperm = 0;
        *nshared = BLK_PERM_ALL;
    }
}

3204 3205 3206 3207 3208 3209 3210 3211
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));
3212
    g_free(s->cluster_buffer);
K
Kevin Wolf 已提交
3213 3214 3215 3216 3217

    if (s->qcow) {
        migrate_del_blocker(s->migration_blocker);
        error_free(s->migration_blocker);
    }
3218 3219
}

3220
static BlockDriver bdrv_vvfat = {
3221 3222 3223 3224 3225 3226
    .format_name            = "vvfat",
    .protocol_name          = "fat",
    .instance_size          = sizeof(BDRVVVFATState),

    .bdrv_parse_filename    = vvfat_parse_filename,
    .bdrv_file_open         = vvfat_open,
3227
    .bdrv_refresh_limits    = vvfat_refresh_limits,
3228
    .bdrv_close             = vvfat_close,
K
Kevin Wolf 已提交
3229
    .bdrv_child_perm        = vvfat_child_perm,
3230

3231 3232
    .bdrv_co_preadv         = vvfat_co_preadv,
    .bdrv_co_pwritev        = vvfat_co_pwritev,
3233
    .bdrv_co_get_block_status = vvfat_co_get_block_status,
3234 3235
};

3236 3237 3238 3239 3240 3241 3242
static void bdrv_vvfat_init(void)
{
    bdrv_register(&bdrv_vvfat);
}

block_init(bdrv_vvfat_init);

3243
#ifdef DEBUG
3244
static void checkpoint(void) {
A
Anthony Liguori 已提交
3245
    assert(((mapping_t*)array_get(&(vvv->mapping), 0))->end == 2);
3246 3247 3248 3249
    check1(vvv);
    check2(vvv);
    assert(!vvv->current_mapping || vvv->current_fd || (vvv->current_mapping->mode & MODE_DIRECTORY));
#if 0
A
Anthony Liguori 已提交
3250
    if (((direntry_t*)vvv->directory.pointer)[1].attributes != 0xf)
3251
        fprintf(stderr, "Nonono!\n");
A
Anthony Liguori 已提交
3252 3253
    mapping_t* mapping;
    direntry_t* direntry;
3254 3255 3256
    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)
3257
        return;
3258 3259 3260 3261 3262 3263 3264
    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