1/*
2 * QEMU host block devices
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later.  See the COPYING file in the top-level directory.
8 */
9
10#include "block/block.h"
11#include "sysemu/blockdev.h"
12#include "monitor/monitor.h"
13#include "qapi/qmp/qerror.h"
14#include "qemu/option.h"
15#include "qemu/config-file.h"
16#include "sysemu/sysemu.h"
17
18static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
19
20/*
21 * We automatically delete the drive when a device using it gets
22 * unplugged.  Questionable feature, but we can't just drop it.
23 * Device models call blockdev_mark_auto_del() to schedule the
24 * automatic deletion, and generic qdev code calls blockdev_auto_del()
25 * when deletion is actually safe.
26 */
27void blockdev_mark_auto_del(BlockDriverState *bs)
28{
29    DriveInfo *dinfo = drive_get_by_blockdev(bs);
30
31    dinfo->auto_del = 1;
32}
33
34void blockdev_auto_del(BlockDriverState *bs)
35{
36    DriveInfo *dinfo = drive_get_by_blockdev(bs);
37
38    if (dinfo->auto_del) {
39        drive_uninit(dinfo);
40    }
41}
42
43QemuOpts *drive_add(const char *file, const char *fmt, ...)
44{
45    va_list ap;
46    char optstr[1024];
47    QemuOpts *opts;
48
49    va_start(ap, fmt);
50    vsnprintf(optstr, sizeof(optstr), fmt, ap);
51    va_end(ap);
52
53    opts = qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
54    if (!opts) {
55        return NULL;
56    }
57    if (file)
58        qemu_opt_set(opts, "file", file);
59    return opts;
60}
61
62DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
63{
64    DriveInfo *dinfo;
65
66    /* seek interface, bus and unit */
67
68    QTAILQ_FOREACH(dinfo, &drives, next) {
69        if (dinfo->type == type &&
70	    dinfo->bus == bus &&
71	    dinfo->unit == unit)
72            return dinfo;
73    }
74
75    return NULL;
76}
77
78int drive_get_max_bus(BlockInterfaceType type)
79{
80    int max_bus;
81    DriveInfo *dinfo;
82
83    max_bus = -1;
84    QTAILQ_FOREACH(dinfo, &drives, next) {
85        if(dinfo->type == type &&
86           dinfo->bus > max_bus)
87            max_bus = dinfo->bus;
88    }
89    return max_bus;
90}
91
92DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
93{
94    DriveInfo *dinfo;
95
96    QTAILQ_FOREACH(dinfo, &drives, next) {
97        if (dinfo->bdrv == bs) {
98            return dinfo;
99        }
100    }
101    return NULL;
102}
103
104static void bdrv_format_print(void *opaque, const char *name)
105{
106    fprintf(stderr, " %s", name);
107}
108
109void drive_uninit(DriveInfo *dinfo)
110{
111    qemu_opts_del(dinfo->opts);
112    bdrv_delete(dinfo->bdrv);
113    QTAILQ_REMOVE(&drives, dinfo, next);
114    g_free(dinfo);
115}
116
117static int parse_block_error_action(const char *buf, int is_read)
118{
119    if (!strcmp(buf, "ignore")) {
120        return BLOCK_ERR_IGNORE;
121    } else if (!is_read && !strcmp(buf, "enospc")) {
122        return BLOCK_ERR_STOP_ENOSPC;
123    } else if (!strcmp(buf, "stop")) {
124        return BLOCK_ERR_STOP_ANY;
125    } else if (!strcmp(buf, "report")) {
126        return BLOCK_ERR_REPORT;
127    } else {
128        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
129            buf, is_read ? "read" : "write");
130        return -1;
131    }
132}
133
134DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi, int *fatal_error)
135{
136    const char *buf;
137    const char *file = NULL;
138    char devname[128];
139    const char *serial;
140    const char *mediastr = "";
141    BlockInterfaceType type;
142    enum { MEDIA_DISK, MEDIA_CDROM } media;
143    int bus_id, unit_id;
144    int cyls, heads, secs, translation;
145    BlockDriver *drv = NULL;
146    int max_devs;
147    int index;
148    int ro = 0;
149    int bdrv_flags = 0;
150    int on_read_error, on_write_error;
151    const char *devaddr;
152    DriveInfo *dinfo;
153    int snapshot = 0;
154    int ret;
155
156    *fatal_error = 1;
157
158    translation = BIOS_ATA_TRANSLATION_AUTO;
159
160    if (default_to_scsi) {
161        type = IF_SCSI;
162        max_devs = MAX_SCSI_DEVS;
163        pstrcpy(devname, sizeof(devname), "scsi");
164    } else {
165        type = IF_IDE;
166        max_devs = MAX_IDE_DEVS;
167        pstrcpy(devname, sizeof(devname), "ide");
168    }
169    media = MEDIA_DISK;
170
171    /* extract parameters */
172    bus_id  = qemu_opt_get_number(opts, "bus", 0);
173    unit_id = qemu_opt_get_number(opts, "unit", -1);
174    index   = qemu_opt_get_number(opts, "index", -1);
175
176    cyls  = qemu_opt_get_number(opts, "cyls", 0);
177    heads = qemu_opt_get_number(opts, "heads", 0);
178    secs  = qemu_opt_get_number(opts, "secs", 0);
179
180    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
181    ro = qemu_opt_get_bool(opts, "readonly", 0);
182
183    file = qemu_opt_get(opts, "file");
184    serial = qemu_opt_get(opts, "serial");
185
186    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
187        pstrcpy(devname, sizeof(devname), buf);
188        if (!strcmp(buf, "ide")) {
189	    type = IF_IDE;
190            max_devs = MAX_IDE_DEVS;
191        } else if (!strcmp(buf, "scsi")) {
192	    type = IF_SCSI;
193            max_devs = MAX_SCSI_DEVS;
194        } else if (!strcmp(buf, "floppy")) {
195	    type = IF_FLOPPY;
196            max_devs = 0;
197        } else if (!strcmp(buf, "pflash")) {
198	    type = IF_PFLASH;
199            max_devs = 0;
200	} else if (!strcmp(buf, "mtd")) {
201	    type = IF_MTD;
202            max_devs = 0;
203	} else if (!strcmp(buf, "sd")) {
204	    type = IF_SD;
205            max_devs = 0;
206        } else if (!strcmp(buf, "virtio")) {
207            type = IF_VIRTIO;
208            max_devs = 0;
209	} else if (!strcmp(buf, "xen")) {
210	    type = IF_XEN;
211            max_devs = 0;
212	} else if (!strcmp(buf, "none")) {
213	    type = IF_NONE;
214            max_devs = 0;
215	} else {
216            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
217            return NULL;
218	}
219    }
220
221    if (cyls || heads || secs) {
222        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
223            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
224	    return NULL;
225	}
226        if (heads < 1 || (type == IF_IDE && heads > 16)) {
227            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
228	    return NULL;
229	}
230        if (secs < 1 || (type == IF_IDE && secs > 63)) {
231            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
232	    return NULL;
233	}
234    }
235
236    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
237        if (!cyls) {
238            fprintf(stderr,
239                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
240                    buf);
241            return NULL;
242        }
243        if (!strcmp(buf, "none"))
244            translation = BIOS_ATA_TRANSLATION_NONE;
245        else if (!strcmp(buf, "lba"))
246            translation = BIOS_ATA_TRANSLATION_LBA;
247        else if (!strcmp(buf, "auto"))
248            translation = BIOS_ATA_TRANSLATION_AUTO;
249	else {
250            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
251	    return NULL;
252	}
253    }
254
255    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
256        if (!strcmp(buf, "disk")) {
257	    media = MEDIA_DISK;
258	} else if (!strcmp(buf, "cdrom")) {
259            if (cyls || secs || heads) {
260                fprintf(stderr,
261                        "qemu: '%s' invalid physical CHS format\n", buf);
262	        return NULL;
263            }
264	    media = MEDIA_CDROM;
265	} else {
266	    fprintf(stderr, "qemu: '%s' invalid media\n", buf);
267	    return NULL;
268	}
269    }
270
271    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
272        if (!strcmp(buf, "off") || !strcmp(buf, "none")) {
273            bdrv_flags |= BDRV_O_NOCACHE;
274        } else if (!strcmp(buf, "writeback")) {
275            bdrv_flags |= BDRV_O_CACHE_WB;
276        } else if (!strcmp(buf, "unsafe")) {
277            bdrv_flags |= BDRV_O_CACHE_WB;
278            bdrv_flags |= BDRV_O_NO_FLUSH;
279        } else if (!strcmp(buf, "writethrough")) {
280            /* this is the default */
281        } else {
282           fprintf(stderr, "qemu: invalid cache option\n");
283           return NULL;
284        }
285    }
286
287#ifdef CONFIG_LINUX_AIO
288    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
289        if (!strcmp(buf, "native")) {
290            bdrv_flags |= BDRV_O_NATIVE_AIO;
291        } else if (!strcmp(buf, "threads")) {
292            /* this is the default */
293        } else {
294           fprintf(stderr, "qemu: invalid aio option\n");
295           return NULL;
296        }
297    }
298#endif
299
300    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
301       if (strcmp(buf, "?") == 0) {
302            fprintf(stderr, "qemu: Supported formats:");
303            bdrv_iterate_format(bdrv_format_print, NULL);
304            fprintf(stderr, "\n");
305	    return NULL;
306        }
307        drv = bdrv_find_whitelisted_format(buf);
308        if (!drv) {
309            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
310            return NULL;
311        }
312    }
313
314    on_write_error = BLOCK_ERR_STOP_ENOSPC;
315    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
316        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
317            fprintf(stderr, "werror is no supported by this format\n");
318            return NULL;
319        }
320
321        on_write_error = parse_block_error_action(buf, 0);
322        if (on_write_error < 0) {
323            return NULL;
324        }
325    }
326
327    on_read_error = BLOCK_ERR_REPORT;
328    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
329        if (type != IF_IDE && type != IF_VIRTIO && type != IF_NONE) {
330            fprintf(stderr, "rerror is no supported by this format\n");
331            return NULL;
332        }
333
334        on_read_error = parse_block_error_action(buf, 1);
335        if (on_read_error < 0) {
336            return NULL;
337        }
338    }
339
340    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
341        if (type != IF_VIRTIO) {
342            fprintf(stderr, "addr is not supported\n");
343            return NULL;
344        }
345    }
346
347    /* compute bus and unit according index */
348
349    if (index != -1) {
350        if (bus_id != 0 || unit_id != -1) {
351            fprintf(stderr,
352                    "qemu: index cannot be used with bus and unit\n");
353            return NULL;
354        }
355        if (max_devs == 0)
356        {
357            unit_id = index;
358            bus_id = 0;
359        } else {
360            unit_id = index % max_devs;
361            bus_id = index / max_devs;
362        }
363    }
364
365    /* if user doesn't specify a unit_id,
366     * try to find the first free
367     */
368
369    if (unit_id == -1) {
370       unit_id = 0;
371       while (drive_get(type, bus_id, unit_id) != NULL) {
372           unit_id++;
373           if (max_devs && unit_id >= max_devs) {
374               unit_id -= max_devs;
375               bus_id++;
376           }
377       }
378    }
379
380    /* check unit id */
381
382    if (max_devs && unit_id >= max_devs) {
383        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
384                unit_id, max_devs - 1);
385        return NULL;
386    }
387
388    /*
389     * ignore multiple definitions
390     */
391
392    if (drive_get(type, bus_id, unit_id) != NULL) {
393        *fatal_error = 0;
394        return NULL;
395    }
396
397    /* init */
398
399    dinfo = g_malloc0(sizeof(*dinfo));
400    if ((buf = qemu_opts_id(opts)) != NULL) {
401        dinfo->id = g_strdup(buf);
402    } else {
403        /* no id supplied -> create one */
404        dinfo->id = g_malloc0(32);
405        if (type == IF_IDE || type == IF_SCSI)
406            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
407        if (max_devs)
408            snprintf(dinfo->id, 32, "%s%i%s%i",
409                     devname, bus_id, mediastr, unit_id);
410        else
411            snprintf(dinfo->id, 32, "%s%s%i",
412                     devname, mediastr, unit_id);
413    }
414    dinfo->bdrv = bdrv_new(dinfo->id);
415    dinfo->devaddr = devaddr;
416    dinfo->type = type;
417    dinfo->bus = bus_id;
418    dinfo->unit = unit_id;
419    dinfo->opts = opts;
420    if (serial)
421        strncpy(dinfo->serial, serial, sizeof(dinfo->serial) - 1);
422    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
423
424    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
425
426    switch(type) {
427    case IF_IDE:
428    case IF_SCSI:
429    case IF_XEN:
430    case IF_NONE:
431        switch(media) {
432	case MEDIA_DISK:
433            if (cyls != 0) {
434                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
435                bdrv_set_translation_hint(dinfo->bdrv, translation);
436            }
437	    break;
438	case MEDIA_CDROM:
439            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
440	    break;
441	}
442        break;
443    case IF_SD:
444        /* FIXME: This isn't really a floppy, but it's a reasonable
445           approximation.  */
446    case IF_FLOPPY:
447        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
448        break;
449    case IF_PFLASH:
450    case IF_MTD:
451        break;
452    case IF_VIRTIO:
453        /* add virtio block device */
454        opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);
455        qemu_opt_set(opts, "driver", "virtio-blk-pci");
456        qemu_opt_set(opts, "drive", dinfo->id);
457        if (devaddr)
458            qemu_opt_set(opts, "addr", devaddr);
459        break;
460    case IF_COUNT:
461        abort();
462    }
463    if (!file || !*file) {
464        *fatal_error = 0;
465        return NULL;
466    }
467    if (snapshot) {
468        /* always use cache=unsafe with snapshot */
469        bdrv_flags &= ~BDRV_O_CACHE_MASK;
470        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
471    }
472
473    if (media == MEDIA_CDROM) {
474        /* CDROM is fine for any interface, don't check.  */
475        ro = 1;
476    } else if (ro == 1) {
477        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY && type != IF_NONE) {
478            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
479            return NULL;
480        }
481    }
482
483    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
484
485    ret = bdrv_open(dinfo->bdrv, file, bdrv_flags, drv);
486    if (ret < 0) {
487        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
488                        file, strerror(-ret));
489        return NULL;
490    }
491
492    if (bdrv_key_required(dinfo->bdrv))
493        autostart = 0;
494    *fatal_error = 0;
495    return dinfo;
496}
497
498void do_commit(Monitor *mon, const QDict *qdict)
499{
500    const char *device = qdict_get_str(qdict, "device");
501    BlockDriverState *bs;
502
503    if (!strcmp(device, "all")) {
504        bdrv_commit_all();
505    } else {
506        bs = bdrv_find(device);
507        if (!bs) {
508            qerror_report(QERR_DEVICE_NOT_FOUND, device);
509            return;
510        }
511        bdrv_commit(bs);
512    }
513}
514
515static int eject_device(Monitor *mon, BlockDriverState *bs, int force)
516{
517    if (!force) {
518        if (!bdrv_is_removable(bs)) {
519            qerror_report(QERR_DEVICE_NOT_REMOVABLE,
520                           bdrv_get_device_name(bs));
521            return -1;
522        }
523        if (bdrv_is_locked(bs)) {
524            qerror_report(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
525            return -1;
526        }
527    }
528    bdrv_close(bs);
529    return 0;
530}
531
532int do_eject(Monitor *mon, const QDict *qdict, QObject **ret_data)
533{
534    BlockDriverState *bs;
535    int force = qdict_get_try_bool(qdict, "force", 0);
536    const char *filename = qdict_get_str(qdict, "device");
537
538    bs = bdrv_find(filename);
539    if (!bs) {
540        qerror_report(QERR_DEVICE_NOT_FOUND, filename);
541        return -1;
542    }
543    return eject_device(mon, bs, force);
544}
545
546int do_block_set_passwd(Monitor *mon, const QDict *qdict,
547                        QObject **ret_data)
548{
549    BlockDriverState *bs;
550    int err;
551
552    bs = bdrv_find(qdict_get_str(qdict, "device"));
553    if (!bs) {
554        qerror_report(QERR_DEVICE_NOT_FOUND, qdict_get_str(qdict, "device"));
555        return -1;
556    }
557
558    err = bdrv_set_key(bs, qdict_get_str(qdict, "password"));
559    if (err == -EINVAL) {
560        qerror_report(QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
561        return -1;
562    } else if (err < 0) {
563        qerror_report(QERR_INVALID_PASSWORD);
564        return -1;
565    }
566
567    return 0;
568}
569
570#ifndef CONFIG_ANDROID
571// Monitor support disabled on Android.
572int do_change_block(Monitor *mon, const char *device,
573                    const char *filename, const char *fmt)
574{
575    BlockDriverState *bs;
576    BlockDriver *drv = NULL;
577    int bdrv_flags;
578
579    bs = bdrv_find(device);
580    if (!bs) {
581        qerror_report(QERR_DEVICE_NOT_FOUND, device);
582        return -1;
583    }
584    if (fmt) {
585        drv = bdrv_find_whitelisted_format(fmt);
586        if (!drv) {
587            qerror_report(QERR_INVALID_BLOCK_FORMAT, fmt);
588            return -1;
589        }
590    }
591    if (eject_device(mon, bs, 0) < 0) {
592        return -1;
593    }
594    bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
595    bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
596    if (bdrv_open(bs, filename, bdrv_flags, drv) < 0) {
597        qerror_report(QERR_IO_ERROR);
598        return -1;
599    }
600    return monitor_read_bdrv_key_start(mon, bs, NULL, NULL);
601}
602#endif
603