Statistics
| Branch: | Revision:

root / block / raw-win32.c @ d5124c00

History | View | Annotate | Download (17.1 kB)

1
/*
2
 * Block driver for RAW files (win32)
3
 *
4
 * Copyright (c) 2006 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "qemu-common.h"
25
#include "qemu/timer.h"
26
#include "block/block_int.h"
27
#include "qemu/module.h"
28
#include "raw-aio.h"
29
#include "trace.h"
30
#include "block/thread-pool.h"
31
#include "qemu/iov.h"
32
#include <windows.h>
33
#include <winioctl.h>
34

    
35
#define FTYPE_FILE 0
36
#define FTYPE_CD     1
37
#define FTYPE_HARDDISK 2
38

    
39
static QEMUWin32AIOState *aio;
40

    
41
typedef struct RawWin32AIOData {
42
    BlockDriverState *bs;
43
    HANDLE hfile;
44
    struct iovec *aio_iov;
45
    int aio_niov;
46
    size_t aio_nbytes;
47
    off64_t aio_offset;
48
    int aio_type;
49
} RawWin32AIOData;
50

    
51
typedef struct BDRVRawState {
52
    HANDLE hfile;
53
    int type;
54
    char drive_path[16]; /* format: "d:\" */
55
    QEMUWin32AIOState *aio;
56
} BDRVRawState;
57

    
58
/*
59
 * Read/writes the data to/from a given linear buffer.
60
 *
61
 * Returns the number of bytes handles or -errno in case of an error. Short
62
 * reads are only returned if the end of the file is reached.
63
 */
64
static size_t handle_aiocb_rw(RawWin32AIOData *aiocb)
65
{
66
    size_t offset = 0;
67
    int i;
68

    
69
    for (i = 0; i < aiocb->aio_niov; i++) {
70
        OVERLAPPED ov;
71
        DWORD ret, ret_count, len;
72

    
73
        memset(&ov, 0, sizeof(ov));
74
        ov.Offset = (aiocb->aio_offset + offset);
75
        ov.OffsetHigh = (aiocb->aio_offset + offset) >> 32;
76
        len = aiocb->aio_iov[i].iov_len;
77
        if (aiocb->aio_type & QEMU_AIO_WRITE) {
78
            ret = WriteFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
79
                            len, &ret_count, &ov);
80
        } else {
81
            ret = ReadFile(aiocb->hfile, aiocb->aio_iov[i].iov_base,
82
                           len, &ret_count, &ov);
83
        }
84
        if (!ret) {
85
            ret_count = 0;
86
        }
87
        if (ret_count != len) {
88
            offset += ret_count;
89
            break;
90
        }
91
        offset += len;
92
    }
93

    
94
    return offset;
95
}
96

    
97
static int aio_worker(void *arg)
98
{
99
    RawWin32AIOData *aiocb = arg;
100
    ssize_t ret = 0;
101
    size_t count;
102

    
103
    switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
104
    case QEMU_AIO_READ:
105
        count = handle_aiocb_rw(aiocb);
106
        if (count < aiocb->aio_nbytes && aiocb->bs->growable) {
107
            /* A short read means that we have reached EOF. Pad the buffer
108
             * with zeros for bytes after EOF. */
109
            iov_memset(aiocb->aio_iov, aiocb->aio_niov, count,
110
                      0, aiocb->aio_nbytes - count);
111

    
112
            count = aiocb->aio_nbytes;
113
        }
114
        if (count == aiocb->aio_nbytes) {
115
            ret = 0;
116
        } else {
117
            ret = -EINVAL;
118
        }
119
        break;
120
    case QEMU_AIO_WRITE:
121
        count = handle_aiocb_rw(aiocb);
122
        if (count == aiocb->aio_nbytes) {
123
            count = 0;
124
        } else {
125
            count = -EINVAL;
126
        }
127
        break;
128
    case QEMU_AIO_FLUSH:
129
        if (!FlushFileBuffers(aiocb->hfile)) {
130
            return -EIO;
131
        }
132
        break;
133
    default:
134
        fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
135
        ret = -EINVAL;
136
        break;
137
    }
138

    
139
    g_slice_free(RawWin32AIOData, aiocb);
140
    return ret;
141
}
142

    
143
static BlockDriverAIOCB *paio_submit(BlockDriverState *bs, HANDLE hfile,
144
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
145
        BlockDriverCompletionFunc *cb, void *opaque, int type)
146
{
147
    RawWin32AIOData *acb = g_slice_new(RawWin32AIOData);
148
    ThreadPool *pool;
149

    
150
    acb->bs = bs;
151
    acb->hfile = hfile;
152
    acb->aio_type = type;
153

    
154
    if (qiov) {
155
        acb->aio_iov = qiov->iov;
156
        acb->aio_niov = qiov->niov;
157
    }
158
    acb->aio_nbytes = nb_sectors * 512;
159
    acb->aio_offset = sector_num * 512;
160

    
161
    trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
162
    pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
163
    return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
164
}
165

    
166
int qemu_ftruncate64(int fd, int64_t length)
167
{
168
    LARGE_INTEGER li;
169
    DWORD dw;
170
    LONG high;
171
    HANDLE h;
172
    BOOL res;
173

    
174
    if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
175
        return -1;
176

    
177
    h = (HANDLE)_get_osfhandle(fd);
178

    
179
    /* get current position, ftruncate do not change position */
180
    li.HighPart = 0;
181
    li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
182
    if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
183
        return -1;
184
    }
185

    
186
    high = length >> 32;
187
    dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
188
    if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
189
        return -1;
190
    }
191
    res = SetEndOfFile(h);
192

    
193
    /* back to old position */
194
    SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
195
    return res ? 0 : -1;
196
}
197

    
198
static int set_sparse(int fd)
199
{
200
    DWORD returned;
201
    return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
202
                                 NULL, 0, NULL, 0, &returned, NULL);
203
}
204

    
205
static void raw_parse_flags(int flags, int *access_flags, DWORD *overlapped)
206
{
207
    assert(access_flags != NULL);
208
    assert(overlapped != NULL);
209

    
210
    if (flags & BDRV_O_RDWR) {
211
        *access_flags = GENERIC_READ | GENERIC_WRITE;
212
    } else {
213
        *access_flags = GENERIC_READ;
214
    }
215

    
216
    *overlapped = FILE_ATTRIBUTE_NORMAL;
217
    if (flags & BDRV_O_NATIVE_AIO) {
218
        *overlapped |= FILE_FLAG_OVERLAPPED;
219
    }
220
    if (flags & BDRV_O_NOCACHE) {
221
        *overlapped |= FILE_FLAG_NO_BUFFERING;
222
    }
223
}
224

    
225
static QemuOptsList raw_runtime_opts = {
226
    .name = "raw",
227
    .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
228
    .desc = {
229
        {
230
            .name = "filename",
231
            .type = QEMU_OPT_STRING,
232
            .help = "File name of the image",
233
        },
234
        { /* end of list */ }
235
    },
236
};
237

    
238
static int raw_open(BlockDriverState *bs, QDict *options, int flags,
239
                    Error **errp)
240
{
241
    BDRVRawState *s = bs->opaque;
242
    int access_flags;
243
    DWORD overlapped;
244
    QemuOpts *opts;
245
    Error *local_err = NULL;
246
    const char *filename;
247
    int ret;
248

    
249
    s->type = FTYPE_FILE;
250

    
251
    opts = qemu_opts_create_nofail(&raw_runtime_opts);
252
    qemu_opts_absorb_qdict(opts, options, &local_err);
253
    if (error_is_set(&local_err)) {
254
        qerror_report_err(local_err);
255
        error_free(local_err);
256
        ret = -EINVAL;
257
        goto fail;
258
    }
259

    
260
    filename = qemu_opt_get(opts, "filename");
261

    
262
    raw_parse_flags(flags, &access_flags, &overlapped);
263

    
264
    if ((flags & BDRV_O_NATIVE_AIO) && aio == NULL) {
265
        aio = win32_aio_init();
266
        if (aio == NULL) {
267
            ret = -EINVAL;
268
            goto fail;
269
        }
270
    }
271

    
272
    s->hfile = CreateFile(filename, access_flags,
273
                          FILE_SHARE_READ, NULL,
274
                          OPEN_EXISTING, overlapped, NULL);
275
    if (s->hfile == INVALID_HANDLE_VALUE) {
276
        int err = GetLastError();
277

    
278
        if (err == ERROR_ACCESS_DENIED) {
279
            ret = -EACCES;
280
        } else {
281
            ret = -EINVAL;
282
        }
283
        goto fail;
284
    }
285

    
286
    if (flags & BDRV_O_NATIVE_AIO) {
287
        ret = win32_aio_attach(aio, s->hfile);
288
        if (ret < 0) {
289
            CloseHandle(s->hfile);
290
            goto fail;
291
        }
292
        s->aio = aio;
293
    }
294

    
295
    ret = 0;
296
fail:
297
    qemu_opts_del(opts);
298
    return ret;
299
}
300

    
301
static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,
302
                         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
303
                         BlockDriverCompletionFunc *cb, void *opaque)
304
{
305
    BDRVRawState *s = bs->opaque;
306
    if (s->aio) {
307
        return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
308
                                nb_sectors, cb, opaque, QEMU_AIO_READ); 
309
    } else {
310
        return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
311
                           cb, opaque, QEMU_AIO_READ);
312
    }
313
}
314

    
315
static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,
316
                          int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
317
                          BlockDriverCompletionFunc *cb, void *opaque)
318
{
319
    BDRVRawState *s = bs->opaque;
320
    if (s->aio) {
321
        return win32_aio_submit(bs, s->aio, s->hfile, sector_num, qiov,
322
                                nb_sectors, cb, opaque, QEMU_AIO_WRITE); 
323
    } else {
324
        return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,
325
                           cb, opaque, QEMU_AIO_WRITE);
326
    }
327
}
328

    
329
static BlockDriverAIOCB *raw_aio_flush(BlockDriverState *bs,
330
                         BlockDriverCompletionFunc *cb, void *opaque)
331
{
332
    BDRVRawState *s = bs->opaque;
333
    return paio_submit(bs, s->hfile, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
334
}
335

    
336
static void raw_close(BlockDriverState *bs)
337
{
338
    BDRVRawState *s = bs->opaque;
339
    CloseHandle(s->hfile);
340
}
341

    
342
static int raw_truncate(BlockDriverState *bs, int64_t offset)
343
{
344
    BDRVRawState *s = bs->opaque;
345
    LONG low, high;
346
    DWORD dwPtrLow;
347

    
348
    low = offset;
349
    high = offset >> 32;
350

    
351
    /*
352
     * An error has occurred if the return value is INVALID_SET_FILE_POINTER
353
     * and GetLastError doesn't return NO_ERROR.
354
     */
355
    dwPtrLow = SetFilePointer(s->hfile, low, &high, FILE_BEGIN);
356
    if (dwPtrLow == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
357
        fprintf(stderr, "SetFilePointer error: %lu\n", GetLastError());
358
        return -EIO;
359
    }
360
    if (SetEndOfFile(s->hfile) == 0) {
361
        fprintf(stderr, "SetEndOfFile error: %lu\n", GetLastError());
362
        return -EIO;
363
    }
364
    return 0;
365
}
366

    
367
static int64_t raw_getlength(BlockDriverState *bs)
368
{
369
    BDRVRawState *s = bs->opaque;
370
    LARGE_INTEGER l;
371
    ULARGE_INTEGER available, total, total_free;
372
    DISK_GEOMETRY_EX dg;
373
    DWORD count;
374
    BOOL status;
375

    
376
    switch(s->type) {
377
    case FTYPE_FILE:
378
        l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
379
        if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
380
            return -EIO;
381
        break;
382
    case FTYPE_CD:
383
        if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
384
            return -EIO;
385
        l.QuadPart = total.QuadPart;
386
        break;
387
    case FTYPE_HARDDISK:
388
        status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
389
                                 NULL, 0, &dg, sizeof(dg), &count, NULL);
390
        if (status != 0) {
391
            l = dg.DiskSize;
392
        }
393
        break;
394
    default:
395
        return -EIO;
396
    }
397
    return l.QuadPart;
398
}
399

    
400
static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
401
{
402
    typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
403
                                              DWORD * high);
404
    get_compressed_t get_compressed;
405
    struct _stati64 st;
406
    const char *filename = bs->filename;
407
    /* WinNT support GetCompressedFileSize to determine allocate size */
408
    get_compressed =
409
        (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
410
                                            "GetCompressedFileSizeA");
411
    if (get_compressed) {
412
        DWORD high, low;
413
        low = get_compressed(filename, &high);
414
        if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
415
            return (((int64_t) high) << 32) + low;
416
        }
417
    }
418

    
419
    if (_stati64(filename, &st) < 0) {
420
        return -1;
421
    }
422
    return st.st_size;
423
}
424

    
425
static int raw_create(const char *filename, QEMUOptionParameter *options,
426
                      Error **errp)
427
{
428
    int fd;
429
    int64_t total_size = 0;
430

    
431
    /* Read out options */
432
    while (options && options->name) {
433
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
434
            total_size = options->value.n / 512;
435
        }
436
        options++;
437
    }
438

    
439
    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
440
                   0644);
441
    if (fd < 0)
442
        return -EIO;
443
    set_sparse(fd);
444
    ftruncate(fd, total_size * 512);
445
    qemu_close(fd);
446
    return 0;
447
}
448

    
449
static QEMUOptionParameter raw_create_options[] = {
450
    {
451
        .name = BLOCK_OPT_SIZE,
452
        .type = OPT_SIZE,
453
        .help = "Virtual disk size"
454
    },
455
    { NULL }
456
};
457

    
458
static BlockDriver bdrv_file = {
459
    .format_name        = "file",
460
    .protocol_name        = "file",
461
    .instance_size        = sizeof(BDRVRawState),
462
    .bdrv_file_open        = raw_open,
463
    .bdrv_close                = raw_close,
464
    .bdrv_create        = raw_create,
465
    .bdrv_has_zero_init = bdrv_has_zero_init_1,
466

    
467
    .bdrv_aio_readv     = raw_aio_readv,
468
    .bdrv_aio_writev    = raw_aio_writev,
469
    .bdrv_aio_flush     = raw_aio_flush,
470

    
471
    .bdrv_truncate        = raw_truncate,
472
    .bdrv_getlength        = raw_getlength,
473
    .bdrv_get_allocated_file_size
474
                        = raw_get_allocated_file_size,
475

    
476
    .create_options = raw_create_options,
477
};
478

    
479
/***********************************************/
480
/* host device */
481

    
482
static int find_cdrom(char *cdrom_name, int cdrom_name_size)
483
{
484
    char drives[256], *pdrv = drives;
485
    UINT type;
486

    
487
    memset(drives, 0, sizeof(drives));
488
    GetLogicalDriveStrings(sizeof(drives), drives);
489
    while(pdrv[0] != '\0') {
490
        type = GetDriveType(pdrv);
491
        switch(type) {
492
        case DRIVE_CDROM:
493
            snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
494
            return 0;
495
            break;
496
        }
497
        pdrv += lstrlen(pdrv) + 1;
498
    }
499
    return -1;
500
}
501

    
502
static int find_device_type(BlockDriverState *bs, const char *filename)
503
{
504
    BDRVRawState *s = bs->opaque;
505
    UINT type;
506
    const char *p;
507

    
508
    if (strstart(filename, "\\\\.\\", &p) ||
509
        strstart(filename, "//./", &p)) {
510
        if (stristart(p, "PhysicalDrive", NULL))
511
            return FTYPE_HARDDISK;
512
        snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
513
        type = GetDriveType(s->drive_path);
514
        switch (type) {
515
        case DRIVE_REMOVABLE:
516
        case DRIVE_FIXED:
517
            return FTYPE_HARDDISK;
518
        case DRIVE_CDROM:
519
            return FTYPE_CD;
520
        default:
521
            return FTYPE_FILE;
522
        }
523
    } else {
524
        return FTYPE_FILE;
525
    }
526
}
527

    
528
static int hdev_probe_device(const char *filename)
529
{
530
    if (strstart(filename, "/dev/cdrom", NULL))
531
        return 100;
532
    if (is_windows_drive(filename))
533
        return 100;
534
    return 0;
535
}
536

    
537
static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
538
                     Error **errp)
539
{
540
    BDRVRawState *s = bs->opaque;
541
    int access_flags, create_flags;
542
    int ret = 0;
543
    DWORD overlapped;
544
    char device_name[64];
545

    
546
    Error *local_err = NULL;
547
    const char *filename;
548

    
549
    QemuOpts *opts = qemu_opts_create_nofail(&raw_runtime_opts);
550
    qemu_opts_absorb_qdict(opts, options, &local_err);
551
    if (error_is_set(&local_err)) {
552
        qerror_report_err(local_err);
553
        error_free(local_err);
554
        ret = -EINVAL;
555
        goto done;
556
    }
557

    
558
    filename = qemu_opt_get(opts, "filename");
559

    
560
    if (strstart(filename, "/dev/cdrom", NULL)) {
561
        if (find_cdrom(device_name, sizeof(device_name)) < 0) {
562
            ret = -ENOENT;
563
            goto done;
564
        }
565
        filename = device_name;
566
    } else {
567
        /* transform drive letters into device name */
568
        if (((filename[0] >= 'a' && filename[0] <= 'z') ||
569
             (filename[0] >= 'A' && filename[0] <= 'Z')) &&
570
            filename[1] == ':' && filename[2] == '\0') {
571
            snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
572
            filename = device_name;
573
        }
574
    }
575
    s->type = find_device_type(bs, filename);
576

    
577
    raw_parse_flags(flags, &access_flags, &overlapped);
578

    
579
    create_flags = OPEN_EXISTING;
580

    
581
    s->hfile = CreateFile(filename, access_flags,
582
                          FILE_SHARE_READ, NULL,
583
                          create_flags, overlapped, NULL);
584
    if (s->hfile == INVALID_HANDLE_VALUE) {
585
        int err = GetLastError();
586

    
587
        if (err == ERROR_ACCESS_DENIED) {
588
            ret = -EACCES;
589
        } else {
590
            ret = -1;
591
        }
592
        goto done;
593
    }
594

    
595
done:
596
    qemu_opts_del(opts);
597
    return ret;
598
}
599

    
600
static BlockDriver bdrv_host_device = {
601
    .format_name        = "host_device",
602
    .protocol_name        = "host_device",
603
    .instance_size        = sizeof(BDRVRawState),
604
    .bdrv_probe_device        = hdev_probe_device,
605
    .bdrv_file_open        = hdev_open,
606
    .bdrv_close                = raw_close,
607

    
608
    .bdrv_aio_readv     = raw_aio_readv,
609
    .bdrv_aio_writev    = raw_aio_writev,
610
    .bdrv_aio_flush     = raw_aio_flush,
611

    
612
    .bdrv_getlength        = raw_getlength,
613
    .bdrv_get_allocated_file_size
614
                        = raw_get_allocated_file_size,
615
};
616

    
617
static void bdrv_file_init(void)
618
{
619
    bdrv_register(&bdrv_file);
620
    bdrv_register(&bdrv_host_device);
621
}
622

    
623
block_init(bdrv_file_init);