Statistics
| Branch: | Revision:

root / vl.c @ e8105ebb

History | View | Annotate | Download (154.3 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 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 <unistd.h>
25
#include <fcntl.h>
26
#include <signal.h>
27
#include <time.h>
28
#include <errno.h>
29
#include <sys/time.h>
30
#include <zlib.h>
31

    
32
/* Needed early for CONFIG_BSD etc. */
33
#include "config-host.h"
34

    
35
#ifndef _WIN32
36
#include <libgen.h>
37
#include <pwd.h>
38
#include <sys/times.h>
39
#include <sys/wait.h>
40
#include <termios.h>
41
#include <sys/mman.h>
42
#include <sys/ioctl.h>
43
#include <sys/resource.h>
44
#include <sys/socket.h>
45
#include <netinet/in.h>
46
#include <net/if.h>
47
#include <arpa/inet.h>
48
#include <dirent.h>
49
#include <netdb.h>
50
#include <sys/select.h>
51
#ifdef CONFIG_BSD
52
#include <sys/stat.h>
53
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
54
#include <libutil.h>
55
#else
56
#include <util.h>
57
#endif
58
#else
59
#ifdef __linux__
60
#include <pty.h>
61
#include <malloc.h>
62
#include <linux/rtc.h>
63
#include <sys/prctl.h>
64

    
65
/* For the benefit of older linux systems which don't supply it,
66
   we use a local copy of hpet.h. */
67
/* #include <linux/hpet.h> */
68
#include "hpet.h"
69

    
70
#include <linux/ppdev.h>
71
#include <linux/parport.h>
72
#endif
73
#ifdef __sun__
74
#include <sys/stat.h>
75
#include <sys/ethernet.h>
76
#include <sys/sockio.h>
77
#include <netinet/arp.h>
78
#include <netinet/in.h>
79
#include <netinet/in_systm.h>
80
#include <netinet/ip.h>
81
#include <netinet/ip_icmp.h> // must come after ip.h
82
#include <netinet/udp.h>
83
#include <netinet/tcp.h>
84
#include <net/if.h>
85
#include <syslog.h>
86
#include <stropts.h>
87
/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88
   discussion about Solaris header problems */
89
extern int madvise(caddr_t, size_t, int);
90
#endif
91
#endif
92
#endif
93

    
94
#if defined(__OpenBSD__)
95
#include <util.h>
96
#endif
97

    
98
#if defined(CONFIG_VDE)
99
#include <libvdeplug.h>
100
#endif
101

    
102
#ifdef _WIN32
103
#include <windows.h>
104
#include <mmsystem.h>
105
#endif
106

    
107
#ifdef CONFIG_SDL
108
#if defined(__APPLE__) || defined(main)
109
#include <SDL.h>
110
int qemu_main(int argc, char **argv, char **envp);
111
int main(int argc, char **argv)
112
{
113
    return qemu_main(argc, argv, NULL);
114
}
115
#undef main
116
#define main qemu_main
117
#endif
118
#endif /* CONFIG_SDL */
119

    
120
#ifdef CONFIG_COCOA
121
#undef main
122
#define main qemu_main
123
#endif /* CONFIG_COCOA */
124

    
125
#include "hw/hw.h"
126
#include "hw/boards.h"
127
#include "hw/usb.h"
128
#include "hw/pcmcia.h"
129
#include "hw/pc.h"
130
#include "hw/audiodev.h"
131
#include "hw/isa.h"
132
#include "hw/baum.h"
133
#include "hw/bt.h"
134
#include "hw/watchdog.h"
135
#include "hw/smbios.h"
136
#include "hw/xen.h"
137
#include "hw/qdev.h"
138
#include "hw/loader.h"
139
#include "bt-host.h"
140
#include "net.h"
141
#include "net/slirp.h"
142
#include "monitor.h"
143
#include "console.h"
144
#include "sysemu.h"
145
#include "gdbstub.h"
146
#include "qemu-timer.h"
147
#include "qemu-char.h"
148
#include "cache-utils.h"
149
#include "block.h"
150
#include "block_int.h"
151
#include "block-migration.h"
152
#include "dma.h"
153
#include "audio/audio.h"
154
#include "migration.h"
155
#include "kvm.h"
156
#include "balloon.h"
157
#include "qemu-option.h"
158
#include "qemu-config.h"
159
#include "qemu-objects.h"
160

    
161
#include "disas.h"
162

    
163
#include "exec-all.h"
164

    
165
#include "qemu_socket.h"
166

    
167
#include "slirp/libslirp.h"
168

    
169
#include "qemu-queue.h"
170

    
171
//#define DEBUG_NET
172
//#define DEBUG_SLIRP
173

    
174
#define DEFAULT_RAM_SIZE 128
175

    
176
#define MAX_VIRTIO_CONSOLES 1
177

    
178
static const char *data_dir;
179
const char *bios_name = NULL;
180
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
181
   to store the VM snapshots */
182
struct drivelist drives = QTAILQ_HEAD_INITIALIZER(drives);
183
struct driveoptlist driveopts = QTAILQ_HEAD_INITIALIZER(driveopts);
184
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
185
static DisplayState *display_state;
186
DisplayType display_type = DT_DEFAULT;
187
const char* keyboard_layout = NULL;
188
ram_addr_t ram_size;
189
int nb_nics;
190
NICInfo nd_table[MAX_NICS];
191
int vm_running;
192
int autostart;
193
static int rtc_utc = 1;
194
static int rtc_date_offset = -1; /* -1 means no change */
195
QEMUClock *rtc_clock;
196
int vga_interface_type = VGA_NONE;
197
#ifdef TARGET_SPARC
198
int graphic_width = 1024;
199
int graphic_height = 768;
200
int graphic_depth = 8;
201
#else
202
int graphic_width = 800;
203
int graphic_height = 600;
204
int graphic_depth = 15;
205
#endif
206
static int full_screen = 0;
207
#ifdef CONFIG_SDL
208
static int no_frame = 0;
209
#endif
210
int no_quit = 0;
211
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
212
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
213
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
214
#ifdef TARGET_I386
215
int win2k_install_hack = 0;
216
int rtc_td_hack = 0;
217
#endif
218
int usb_enabled = 0;
219
int singlestep = 0;
220
int smp_cpus = 1;
221
int max_cpus = 0;
222
int smp_cores = 1;
223
int smp_threads = 1;
224
const char *vnc_display;
225
int acpi_enabled = 1;
226
int no_hpet = 0;
227
int fd_bootchk = 1;
228
int no_reboot = 0;
229
int no_shutdown = 0;
230
int cursor_hide = 1;
231
int graphic_rotate = 0;
232
uint8_t irq0override = 1;
233
#ifndef _WIN32
234
int daemonize = 0;
235
#endif
236
const char *watchdog;
237
const char *option_rom[MAX_OPTION_ROMS];
238
int nb_option_roms;
239
int semihosting_enabled = 0;
240
#ifdef TARGET_ARM
241
int old_param = 0;
242
#endif
243
const char *qemu_name;
244
int alt_grab = 0;
245
int ctrl_grab = 0;
246
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
247
unsigned int nb_prom_envs = 0;
248
const char *prom_envs[MAX_PROM_ENVS];
249
#endif
250
int boot_menu;
251

    
252
int nb_numa_nodes;
253
uint64_t node_mem[MAX_NODES];
254
uint64_t node_cpumask[MAX_NODES];
255

    
256
static CPUState *cur_cpu;
257
static CPUState *next_cpu;
258
static int timer_alarm_pending = 1;
259
/* Conversion factor from emulated instructions to virtual clock ticks.  */
260
static int icount_time_shift;
261
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
262
#define MAX_ICOUNT_SHIFT 10
263
/* Compensate for varying guest execution speed.  */
264
static int64_t qemu_icount_bias;
265
static QEMUTimer *icount_rt_timer;
266
static QEMUTimer *icount_vm_timer;
267
static QEMUTimer *nographic_timer;
268

    
269
uint8_t qemu_uuid[16];
270

    
271
static QEMUBootSetHandler *boot_set_handler;
272
static void *boot_set_opaque;
273

    
274
static int default_serial = 1;
275
static int default_parallel = 1;
276
static int default_virtcon = 1;
277
static int default_monitor = 1;
278
static int default_vga = 1;
279
static int default_floppy = 1;
280
static int default_cdrom = 1;
281
static int default_sdcard = 1;
282

    
283
static struct {
284
    const char *driver;
285
    int *flag;
286
} default_list[] = {
287
    { .driver = "isa-serial",           .flag = &default_serial    },
288
    { .driver = "isa-parallel",         .flag = &default_parallel  },
289
    { .driver = "isa-fdc",              .flag = &default_floppy    },
290
    { .driver = "ide-drive",            .flag = &default_cdrom     },
291
    { .driver = "virtio-serial-pci",    .flag = &default_virtcon   },
292
    { .driver = "virtio-serial-s390",   .flag = &default_virtcon   },
293
    { .driver = "virtio-serial",        .flag = &default_virtcon   },
294
    { .driver = "VGA",                  .flag = &default_vga       },
295
    { .driver = "cirrus-vga",           .flag = &default_vga       },
296
    { .driver = "vmware-svga",          .flag = &default_vga       },
297
};
298

    
299
static int default_driver_check(QemuOpts *opts, void *opaque)
300
{
301
    const char *driver = qemu_opt_get(opts, "driver");
302
    int i;
303

    
304
    if (!driver)
305
        return 0;
306
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
307
        if (strcmp(default_list[i].driver, driver) != 0)
308
            continue;
309
        *(default_list[i].flag) = 0;
310
    }
311
    return 0;
312
}
313

    
314
/***********************************************************/
315
/* x86 ISA bus support */
316

    
317
target_phys_addr_t isa_mem_base = 0;
318
PicState2 *isa_pic;
319

    
320
/***********************************************************/
321
void hw_error(const char *fmt, ...)
322
{
323
    va_list ap;
324
    CPUState *env;
325

    
326
    va_start(ap, fmt);
327
    fprintf(stderr, "qemu: hardware error: ");
328
    vfprintf(stderr, fmt, ap);
329
    fprintf(stderr, "\n");
330
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
331
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
332
#ifdef TARGET_I386
333
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
334
#else
335
        cpu_dump_state(env, stderr, fprintf, 0);
336
#endif
337
    }
338
    va_end(ap);
339
    abort();
340
}
341

    
342
static void set_proc_name(const char *s)
343
{
344
#if defined(__linux__) && defined(PR_SET_NAME)
345
    char name[16];
346
    if (!s)
347
        return;
348
    name[sizeof(name) - 1] = 0;
349
    strncpy(name, s, sizeof(name));
350
    /* Could rewrite argv[0] too, but that's a bit more complicated.
351
       This simple way is enough for `top'. */
352
    prctl(PR_SET_NAME, name);
353
#endif            
354
}
355
 
356
/***************/
357
/* ballooning */
358

    
359
static QEMUBalloonEvent *qemu_balloon_event;
360
void *qemu_balloon_event_opaque;
361

    
362
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
363
{
364
    qemu_balloon_event = func;
365
    qemu_balloon_event_opaque = opaque;
366
}
367

    
368
int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
369
{
370
    if (qemu_balloon_event) {
371
        qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
372
        return 1;
373
    } else {
374
        return 0;
375
    }
376
}
377

    
378
int qemu_balloon_status(MonitorCompletion cb, void *opaque)
379
{
380
    if (qemu_balloon_event) {
381
        qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
382
        return 1;
383
    } else {
384
        return 0;
385
    }
386
}
387

    
388

    
389
/***********************************************************/
390
/* real time host monotonic timer */
391

    
392
/* compute with 96 bit intermediate result: (a*b)/c */
393
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
394
{
395
    union {
396
        uint64_t ll;
397
        struct {
398
#ifdef HOST_WORDS_BIGENDIAN
399
            uint32_t high, low;
400
#else
401
            uint32_t low, high;
402
#endif
403
        } l;
404
    } u, res;
405
    uint64_t rl, rh;
406

    
407
    u.ll = a;
408
    rl = (uint64_t)u.l.low * (uint64_t)b;
409
    rh = (uint64_t)u.l.high * (uint64_t)b;
410
    rh += (rl >> 32);
411
    res.l.high = rh / c;
412
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
413
    return res.ll;
414
}
415

    
416
static int64_t get_clock_realtime(void)
417
{
418
    struct timeval tv;
419

    
420
    gettimeofday(&tv, NULL);
421
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
422
}
423

    
424
#ifdef WIN32
425

    
426
static int64_t clock_freq;
427

    
428
static void init_get_clock(void)
429
{
430
    LARGE_INTEGER freq;
431
    int ret;
432
    ret = QueryPerformanceFrequency(&freq);
433
    if (ret == 0) {
434
        fprintf(stderr, "Could not calibrate ticks\n");
435
        exit(1);
436
    }
437
    clock_freq = freq.QuadPart;
438
}
439

    
440
static int64_t get_clock(void)
441
{
442
    LARGE_INTEGER ti;
443
    QueryPerformanceCounter(&ti);
444
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
445
}
446

    
447
#else
448

    
449
static int use_rt_clock;
450

    
451
static void init_get_clock(void)
452
{
453
    use_rt_clock = 0;
454
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
455
    || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
456
    {
457
        struct timespec ts;
458
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
459
            use_rt_clock = 1;
460
        }
461
    }
462
#endif
463
}
464

    
465
static int64_t get_clock(void)
466
{
467
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
468
        || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
469
    if (use_rt_clock) {
470
        struct timespec ts;
471
        clock_gettime(CLOCK_MONOTONIC, &ts);
472
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
473
    } else
474
#endif
475
    {
476
        /* XXX: using gettimeofday leads to problems if the date
477
           changes, so it should be avoided. */
478
        return get_clock_realtime();
479
    }
480
}
481
#endif
482

    
483
/* Return the virtual CPU time, based on the instruction counter.  */
484
static int64_t cpu_get_icount(void)
485
{
486
    int64_t icount;
487
    CPUState *env = cpu_single_env;;
488
    icount = qemu_icount;
489
    if (env) {
490
        if (!can_do_io(env))
491
            fprintf(stderr, "Bad clock read\n");
492
        icount -= (env->icount_decr.u16.low + env->icount_extra);
493
    }
494
    return qemu_icount_bias + (icount << icount_time_shift);
495
}
496

    
497
/***********************************************************/
498
/* guest cycle counter */
499

    
500
typedef struct TimersState {
501
    int64_t cpu_ticks_prev;
502
    int64_t cpu_ticks_offset;
503
    int64_t cpu_clock_offset;
504
    int32_t cpu_ticks_enabled;
505
    int64_t dummy;
506
} TimersState;
507

    
508
TimersState timers_state;
509

    
510
/* return the host CPU cycle counter and handle stop/restart */
511
int64_t cpu_get_ticks(void)
512
{
513
    if (use_icount) {
514
        return cpu_get_icount();
515
    }
516
    if (!timers_state.cpu_ticks_enabled) {
517
        return timers_state.cpu_ticks_offset;
518
    } else {
519
        int64_t ticks;
520
        ticks = cpu_get_real_ticks();
521
        if (timers_state.cpu_ticks_prev > ticks) {
522
            /* Note: non increasing ticks may happen if the host uses
523
               software suspend */
524
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
525
        }
526
        timers_state.cpu_ticks_prev = ticks;
527
        return ticks + timers_state.cpu_ticks_offset;
528
    }
529
}
530

    
531
/* return the host CPU monotonic timer and handle stop/restart */
532
static int64_t cpu_get_clock(void)
533
{
534
    int64_t ti;
535
    if (!timers_state.cpu_ticks_enabled) {
536
        return timers_state.cpu_clock_offset;
537
    } else {
538
        ti = get_clock();
539
        return ti + timers_state.cpu_clock_offset;
540
    }
541
}
542

    
543
/* enable cpu_get_ticks() */
544
void cpu_enable_ticks(void)
545
{
546
    if (!timers_state.cpu_ticks_enabled) {
547
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
548
        timers_state.cpu_clock_offset -= get_clock();
549
        timers_state.cpu_ticks_enabled = 1;
550
    }
551
}
552

    
553
/* disable cpu_get_ticks() : the clock is stopped. You must not call
554
   cpu_get_ticks() after that.  */
555
void cpu_disable_ticks(void)
556
{
557
    if (timers_state.cpu_ticks_enabled) {
558
        timers_state.cpu_ticks_offset = cpu_get_ticks();
559
        timers_state.cpu_clock_offset = cpu_get_clock();
560
        timers_state.cpu_ticks_enabled = 0;
561
    }
562
}
563

    
564
/***********************************************************/
565
/* timers */
566

    
567
#define QEMU_CLOCK_REALTIME 0
568
#define QEMU_CLOCK_VIRTUAL  1
569
#define QEMU_CLOCK_HOST     2
570

    
571
struct QEMUClock {
572
    int type;
573
    /* XXX: add frequency */
574
};
575

    
576
struct QEMUTimer {
577
    QEMUClock *clock;
578
    int64_t expire_time;
579
    QEMUTimerCB *cb;
580
    void *opaque;
581
    struct QEMUTimer *next;
582
};
583

    
584
struct qemu_alarm_timer {
585
    char const *name;
586
    unsigned int flags;
587

    
588
    int (*start)(struct qemu_alarm_timer *t);
589
    void (*stop)(struct qemu_alarm_timer *t);
590
    void (*rearm)(struct qemu_alarm_timer *t);
591
    void *priv;
592
};
593

    
594
#define ALARM_FLAG_DYNTICKS  0x1
595
#define ALARM_FLAG_EXPIRED   0x2
596

    
597
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
598
{
599
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
600
}
601

    
602
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
603
{
604
    if (!alarm_has_dynticks(t))
605
        return;
606

    
607
    t->rearm(t);
608
}
609

    
610
/* TODO: MIN_TIMER_REARM_US should be optimized */
611
#define MIN_TIMER_REARM_US 250
612

    
613
static struct qemu_alarm_timer *alarm_timer;
614

    
615
#ifdef _WIN32
616

    
617
struct qemu_alarm_win32 {
618
    MMRESULT timerId;
619
    unsigned int period;
620
} alarm_win32_data = {0, -1};
621

    
622
static int win32_start_timer(struct qemu_alarm_timer *t);
623
static void win32_stop_timer(struct qemu_alarm_timer *t);
624
static void win32_rearm_timer(struct qemu_alarm_timer *t);
625

    
626
#else
627

    
628
static int unix_start_timer(struct qemu_alarm_timer *t);
629
static void unix_stop_timer(struct qemu_alarm_timer *t);
630

    
631
#ifdef __linux__
632

    
633
static int dynticks_start_timer(struct qemu_alarm_timer *t);
634
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
635
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
636

    
637
static int hpet_start_timer(struct qemu_alarm_timer *t);
638
static void hpet_stop_timer(struct qemu_alarm_timer *t);
639

    
640
static int rtc_start_timer(struct qemu_alarm_timer *t);
641
static void rtc_stop_timer(struct qemu_alarm_timer *t);
642

    
643
#endif /* __linux__ */
644

    
645
#endif /* _WIN32 */
646

    
647
/* Correlation between real and virtual time is always going to be
648
   fairly approximate, so ignore small variation.
649
   When the guest is idle real and virtual time will be aligned in
650
   the IO wait loop.  */
651
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
652

    
653
static void icount_adjust(void)
654
{
655
    int64_t cur_time;
656
    int64_t cur_icount;
657
    int64_t delta;
658
    static int64_t last_delta;
659
    /* If the VM is not running, then do nothing.  */
660
    if (!vm_running)
661
        return;
662

    
663
    cur_time = cpu_get_clock();
664
    cur_icount = qemu_get_clock(vm_clock);
665
    delta = cur_icount - cur_time;
666
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
667
    if (delta > 0
668
        && last_delta + ICOUNT_WOBBLE < delta * 2
669
        && icount_time_shift > 0) {
670
        /* The guest is getting too far ahead.  Slow time down.  */
671
        icount_time_shift--;
672
    }
673
    if (delta < 0
674
        && last_delta - ICOUNT_WOBBLE > delta * 2
675
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
676
        /* The guest is getting too far behind.  Speed time up.  */
677
        icount_time_shift++;
678
    }
679
    last_delta = delta;
680
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
681
}
682

    
683
static void icount_adjust_rt(void * opaque)
684
{
685
    qemu_mod_timer(icount_rt_timer,
686
                   qemu_get_clock(rt_clock) + 1000);
687
    icount_adjust();
688
}
689

    
690
static void icount_adjust_vm(void * opaque)
691
{
692
    qemu_mod_timer(icount_vm_timer,
693
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
694
    icount_adjust();
695
}
696

    
697
static void init_icount_adjust(void)
698
{
699
    /* Have both realtime and virtual time triggers for speed adjustment.
700
       The realtime trigger catches emulated time passing too slowly,
701
       the virtual time trigger catches emulated time passing too fast.
702
       Realtime triggers occur even when idle, so use them less frequently
703
       than VM triggers.  */
704
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
705
    qemu_mod_timer(icount_rt_timer,
706
                   qemu_get_clock(rt_clock) + 1000);
707
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
708
    qemu_mod_timer(icount_vm_timer,
709
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
710
}
711

    
712
static struct qemu_alarm_timer alarm_timers[] = {
713
#ifndef _WIN32
714
#ifdef __linux__
715
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
716
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
717
    /* HPET - if available - is preferred */
718
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
719
    /* ...otherwise try RTC */
720
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
721
#endif
722
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
723
#else
724
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
725
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
726
    {"win32", 0, win32_start_timer,
727
     win32_stop_timer, NULL, &alarm_win32_data},
728
#endif
729
    {NULL, }
730
};
731

    
732
static void show_available_alarms(void)
733
{
734
    int i;
735

    
736
    printf("Available alarm timers, in order of precedence:\n");
737
    for (i = 0; alarm_timers[i].name; i++)
738
        printf("%s\n", alarm_timers[i].name);
739
}
740

    
741
static void configure_alarms(char const *opt)
742
{
743
    int i;
744
    int cur = 0;
745
    int count = ARRAY_SIZE(alarm_timers) - 1;
746
    char *arg;
747
    char *name;
748
    struct qemu_alarm_timer tmp;
749

    
750
    if (!strcmp(opt, "?")) {
751
        show_available_alarms();
752
        exit(0);
753
    }
754

    
755
    arg = qemu_strdup(opt);
756

    
757
    /* Reorder the array */
758
    name = strtok(arg, ",");
759
    while (name) {
760
        for (i = 0; i < count && alarm_timers[i].name; i++) {
761
            if (!strcmp(alarm_timers[i].name, name))
762
                break;
763
        }
764

    
765
        if (i == count) {
766
            fprintf(stderr, "Unknown clock %s\n", name);
767
            goto next;
768
        }
769

    
770
        if (i < cur)
771
            /* Ignore */
772
            goto next;
773

    
774
        /* Swap */
775
        tmp = alarm_timers[i];
776
        alarm_timers[i] = alarm_timers[cur];
777
        alarm_timers[cur] = tmp;
778

    
779
        cur++;
780
next:
781
        name = strtok(NULL, ",");
782
    }
783

    
784
    qemu_free(arg);
785

    
786
    if (cur) {
787
        /* Disable remaining timers */
788
        for (i = cur; i < count; i++)
789
            alarm_timers[i].name = NULL;
790
    } else {
791
        show_available_alarms();
792
        exit(1);
793
    }
794
}
795

    
796
#define QEMU_NUM_CLOCKS 3
797

    
798
QEMUClock *rt_clock;
799
QEMUClock *vm_clock;
800
QEMUClock *host_clock;
801

    
802
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
803

    
804
static QEMUClock *qemu_new_clock(int type)
805
{
806
    QEMUClock *clock;
807
    clock = qemu_mallocz(sizeof(QEMUClock));
808
    clock->type = type;
809
    return clock;
810
}
811

    
812
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
813
{
814
    QEMUTimer *ts;
815

    
816
    ts = qemu_mallocz(sizeof(QEMUTimer));
817
    ts->clock = clock;
818
    ts->cb = cb;
819
    ts->opaque = opaque;
820
    return ts;
821
}
822

    
823
void qemu_free_timer(QEMUTimer *ts)
824
{
825
    qemu_free(ts);
826
}
827

    
828
/* stop a timer, but do not dealloc it */
829
void qemu_del_timer(QEMUTimer *ts)
830
{
831
    QEMUTimer **pt, *t;
832

    
833
    /* NOTE: this code must be signal safe because
834
       qemu_timer_expired() can be called from a signal. */
835
    pt = &active_timers[ts->clock->type];
836
    for(;;) {
837
        t = *pt;
838
        if (!t)
839
            break;
840
        if (t == ts) {
841
            *pt = t->next;
842
            break;
843
        }
844
        pt = &t->next;
845
    }
846
}
847

    
848
/* modify the current timer so that it will be fired when current_time
849
   >= expire_time. The corresponding callback will be called. */
850
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
851
{
852
    QEMUTimer **pt, *t;
853

    
854
    qemu_del_timer(ts);
855

    
856
    /* add the timer in the sorted list */
857
    /* NOTE: this code must be signal safe because
858
       qemu_timer_expired() can be called from a signal. */
859
    pt = &active_timers[ts->clock->type];
860
    for(;;) {
861
        t = *pt;
862
        if (!t)
863
            break;
864
        if (t->expire_time > expire_time)
865
            break;
866
        pt = &t->next;
867
    }
868
    ts->expire_time = expire_time;
869
    ts->next = *pt;
870
    *pt = ts;
871

    
872
    /* Rearm if necessary  */
873
    if (pt == &active_timers[ts->clock->type]) {
874
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
875
            qemu_rearm_alarm_timer(alarm_timer);
876
        }
877
        /* Interrupt execution to force deadline recalculation.  */
878
        if (use_icount)
879
            qemu_notify_event();
880
    }
881
}
882

    
883
int qemu_timer_pending(QEMUTimer *ts)
884
{
885
    QEMUTimer *t;
886
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
887
        if (t == ts)
888
            return 1;
889
    }
890
    return 0;
891
}
892

    
893
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
894
{
895
    if (!timer_head)
896
        return 0;
897
    return (timer_head->expire_time <= current_time);
898
}
899

    
900
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
901
{
902
    QEMUTimer *ts;
903

    
904
    for(;;) {
905
        ts = *ptimer_head;
906
        if (!ts || ts->expire_time > current_time)
907
            break;
908
        /* remove timer from the list before calling the callback */
909
        *ptimer_head = ts->next;
910
        ts->next = NULL;
911

    
912
        /* run the callback (the timer list can be modified) */
913
        ts->cb(ts->opaque);
914
    }
915
}
916

    
917
int64_t qemu_get_clock(QEMUClock *clock)
918
{
919
    switch(clock->type) {
920
    case QEMU_CLOCK_REALTIME:
921
        return get_clock() / 1000000;
922
    default:
923
    case QEMU_CLOCK_VIRTUAL:
924
        if (use_icount) {
925
            return cpu_get_icount();
926
        } else {
927
            return cpu_get_clock();
928
        }
929
    case QEMU_CLOCK_HOST:
930
        return get_clock_realtime();
931
    }
932
}
933

    
934
static void init_clocks(void)
935
{
936
    init_get_clock();
937
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
938
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
939
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
940

    
941
    rtc_clock = host_clock;
942
}
943

    
944
/* save a timer */
945
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
946
{
947
    uint64_t expire_time;
948

    
949
    if (qemu_timer_pending(ts)) {
950
        expire_time = ts->expire_time;
951
    } else {
952
        expire_time = -1;
953
    }
954
    qemu_put_be64(f, expire_time);
955
}
956

    
957
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
958
{
959
    uint64_t expire_time;
960

    
961
    expire_time = qemu_get_be64(f);
962
    if (expire_time != -1) {
963
        qemu_mod_timer(ts, expire_time);
964
    } else {
965
        qemu_del_timer(ts);
966
    }
967
}
968

    
969
static const VMStateDescription vmstate_timers = {
970
    .name = "timer",
971
    .version_id = 2,
972
    .minimum_version_id = 1,
973
    .minimum_version_id_old = 1,
974
    .fields      = (VMStateField []) {
975
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
976
        VMSTATE_INT64(dummy, TimersState),
977
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
978
        VMSTATE_END_OF_LIST()
979
    }
980
};
981

    
982
static void qemu_event_increment(void);
983

    
984
#ifdef _WIN32
985
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
986
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
987
                                        DWORD_PTR dw2)
988
#else
989
static void host_alarm_handler(int host_signum)
990
#endif
991
{
992
#if 0
993
#define DISP_FREQ 1000
994
    {
995
        static int64_t delta_min = INT64_MAX;
996
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
997
        static int count;
998
        ti = qemu_get_clock(vm_clock);
999
        if (last_clock != 0) {
1000
            delta = ti - last_clock;
1001
            if (delta < delta_min)
1002
                delta_min = delta;
1003
            if (delta > delta_max)
1004
                delta_max = delta;
1005
            delta_cum += delta;
1006
            if (++count == DISP_FREQ) {
1007
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1008
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1009
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1010
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1011
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1012
                count = 0;
1013
                delta_min = INT64_MAX;
1014
                delta_max = 0;
1015
                delta_cum = 0;
1016
            }
1017
        }
1018
        last_clock = ti;
1019
    }
1020
#endif
1021
    if (alarm_has_dynticks(alarm_timer) ||
1022
        (!use_icount &&
1023
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1024
                               qemu_get_clock(vm_clock))) ||
1025
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1026
                           qemu_get_clock(rt_clock)) ||
1027
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1028
                           qemu_get_clock(host_clock))) {
1029
        qemu_event_increment();
1030
        if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1031

    
1032
#ifndef CONFIG_IOTHREAD
1033
        if (next_cpu) {
1034
            /* stop the currently executing cpu because a timer occured */
1035
            cpu_exit(next_cpu);
1036
        }
1037
#endif
1038
        timer_alarm_pending = 1;
1039
        qemu_notify_event();
1040
    }
1041
}
1042

    
1043
static int64_t qemu_next_deadline(void)
1044
{
1045
    /* To avoid problems with overflow limit this to 2^32.  */
1046
    int64_t delta = INT32_MAX;
1047

    
1048
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1049
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1050
                     qemu_get_clock(vm_clock);
1051
    }
1052
    if (active_timers[QEMU_CLOCK_HOST]) {
1053
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1054
                 qemu_get_clock(host_clock);
1055
        if (hdelta < delta)
1056
            delta = hdelta;
1057
    }
1058

    
1059
    if (delta < 0)
1060
        delta = 0;
1061

    
1062
    return delta;
1063
}
1064

    
1065
#if defined(__linux__)
1066
static uint64_t qemu_next_deadline_dyntick(void)
1067
{
1068
    int64_t delta;
1069
    int64_t rtdelta;
1070

    
1071
    if (use_icount)
1072
        delta = INT32_MAX;
1073
    else
1074
        delta = (qemu_next_deadline() + 999) / 1000;
1075

    
1076
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1077
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1078
                 qemu_get_clock(rt_clock))*1000;
1079
        if (rtdelta < delta)
1080
            delta = rtdelta;
1081
    }
1082

    
1083
    if (delta < MIN_TIMER_REARM_US)
1084
        delta = MIN_TIMER_REARM_US;
1085

    
1086
    return delta;
1087
}
1088
#endif
1089

    
1090
#ifndef _WIN32
1091

    
1092
/* Sets a specific flag */
1093
static int fcntl_setfl(int fd, int flag)
1094
{
1095
    int flags;
1096

    
1097
    flags = fcntl(fd, F_GETFL);
1098
    if (flags == -1)
1099
        return -errno;
1100

    
1101
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1102
        return -errno;
1103

    
1104
    return 0;
1105
}
1106

    
1107
#if defined(__linux__)
1108

    
1109
#define RTC_FREQ 1024
1110

    
1111
static void enable_sigio_timer(int fd)
1112
{
1113
    struct sigaction act;
1114

    
1115
    /* timer signal */
1116
    sigfillset(&act.sa_mask);
1117
    act.sa_flags = 0;
1118
    act.sa_handler = host_alarm_handler;
1119

    
1120
    sigaction(SIGIO, &act, NULL);
1121
    fcntl_setfl(fd, O_ASYNC);
1122
    fcntl(fd, F_SETOWN, getpid());
1123
}
1124

    
1125
static int hpet_start_timer(struct qemu_alarm_timer *t)
1126
{
1127
    struct hpet_info info;
1128
    int r, fd;
1129

    
1130
    fd = qemu_open("/dev/hpet", O_RDONLY);
1131
    if (fd < 0)
1132
        return -1;
1133

    
1134
    /* Set frequency */
1135
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1136
    if (r < 0) {
1137
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1138
                "error, but for better emulation accuracy type:\n"
1139
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1140
        goto fail;
1141
    }
1142

    
1143
    /* Check capabilities */
1144
    r = ioctl(fd, HPET_INFO, &info);
1145
    if (r < 0)
1146
        goto fail;
1147

    
1148
    /* Enable periodic mode */
1149
    r = ioctl(fd, HPET_EPI, 0);
1150
    if (info.hi_flags && (r < 0))
1151
        goto fail;
1152

    
1153
    /* Enable interrupt */
1154
    r = ioctl(fd, HPET_IE_ON, 0);
1155
    if (r < 0)
1156
        goto fail;
1157

    
1158
    enable_sigio_timer(fd);
1159
    t->priv = (void *)(long)fd;
1160

    
1161
    return 0;
1162
fail:
1163
    close(fd);
1164
    return -1;
1165
}
1166

    
1167
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1168
{
1169
    int fd = (long)t->priv;
1170

    
1171
    close(fd);
1172
}
1173

    
1174
static int rtc_start_timer(struct qemu_alarm_timer *t)
1175
{
1176
    int rtc_fd;
1177
    unsigned long current_rtc_freq = 0;
1178

    
1179
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1180
    if (rtc_fd < 0)
1181
        return -1;
1182
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1183
    if (current_rtc_freq != RTC_FREQ &&
1184
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1185
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1186
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1187
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1188
        goto fail;
1189
    }
1190
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1191
    fail:
1192
        close(rtc_fd);
1193
        return -1;
1194
    }
1195

    
1196
    enable_sigio_timer(rtc_fd);
1197

    
1198
    t->priv = (void *)(long)rtc_fd;
1199

    
1200
    return 0;
1201
}
1202

    
1203
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1204
{
1205
    int rtc_fd = (long)t->priv;
1206

    
1207
    close(rtc_fd);
1208
}
1209

    
1210
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1211
{
1212
    struct sigevent ev;
1213
    timer_t host_timer;
1214
    struct sigaction act;
1215

    
1216
    sigfillset(&act.sa_mask);
1217
    act.sa_flags = 0;
1218
    act.sa_handler = host_alarm_handler;
1219

    
1220
    sigaction(SIGALRM, &act, NULL);
1221

    
1222
    /* 
1223
     * Initialize ev struct to 0 to avoid valgrind complaining
1224
     * about uninitialized data in timer_create call
1225
     */
1226
    memset(&ev, 0, sizeof(ev));
1227
    ev.sigev_value.sival_int = 0;
1228
    ev.sigev_notify = SIGEV_SIGNAL;
1229
    ev.sigev_signo = SIGALRM;
1230

    
1231
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1232
        perror("timer_create");
1233

    
1234
        /* disable dynticks */
1235
        fprintf(stderr, "Dynamic Ticks disabled\n");
1236

    
1237
        return -1;
1238
    }
1239

    
1240
    t->priv = (void *)(long)host_timer;
1241

    
1242
    return 0;
1243
}
1244

    
1245
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1246
{
1247
    timer_t host_timer = (timer_t)(long)t->priv;
1248

    
1249
    timer_delete(host_timer);
1250
}
1251

    
1252
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1253
{
1254
    timer_t host_timer = (timer_t)(long)t->priv;
1255
    struct itimerspec timeout;
1256
    int64_t nearest_delta_us = INT64_MAX;
1257
    int64_t current_us;
1258

    
1259
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1260
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1261
        !active_timers[QEMU_CLOCK_HOST])
1262
        return;
1263

    
1264
    nearest_delta_us = qemu_next_deadline_dyntick();
1265

    
1266
    /* check whether a timer is already running */
1267
    if (timer_gettime(host_timer, &timeout)) {
1268
        perror("gettime");
1269
        fprintf(stderr, "Internal timer error: aborting\n");
1270
        exit(1);
1271
    }
1272
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1273
    if (current_us && current_us <= nearest_delta_us)
1274
        return;
1275

    
1276
    timeout.it_interval.tv_sec = 0;
1277
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1278
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1279
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1280
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1281
        perror("settime");
1282
        fprintf(stderr, "Internal timer error: aborting\n");
1283
        exit(1);
1284
    }
1285
}
1286

    
1287
#endif /* defined(__linux__) */
1288

    
1289
static int unix_start_timer(struct qemu_alarm_timer *t)
1290
{
1291
    struct sigaction act;
1292
    struct itimerval itv;
1293
    int err;
1294

    
1295
    /* timer signal */
1296
    sigfillset(&act.sa_mask);
1297
    act.sa_flags = 0;
1298
    act.sa_handler = host_alarm_handler;
1299

    
1300
    sigaction(SIGALRM, &act, NULL);
1301

    
1302
    itv.it_interval.tv_sec = 0;
1303
    /* for i386 kernel 2.6 to get 1 ms */
1304
    itv.it_interval.tv_usec = 999;
1305
    itv.it_value.tv_sec = 0;
1306
    itv.it_value.tv_usec = 10 * 1000;
1307

    
1308
    err = setitimer(ITIMER_REAL, &itv, NULL);
1309
    if (err)
1310
        return -1;
1311

    
1312
    return 0;
1313
}
1314

    
1315
static void unix_stop_timer(struct qemu_alarm_timer *t)
1316
{
1317
    struct itimerval itv;
1318

    
1319
    memset(&itv, 0, sizeof(itv));
1320
    setitimer(ITIMER_REAL, &itv, NULL);
1321
}
1322

    
1323
#endif /* !defined(_WIN32) */
1324

    
1325

    
1326
#ifdef _WIN32
1327

    
1328
static int win32_start_timer(struct qemu_alarm_timer *t)
1329
{
1330
    TIMECAPS tc;
1331
    struct qemu_alarm_win32 *data = t->priv;
1332
    UINT flags;
1333

    
1334
    memset(&tc, 0, sizeof(tc));
1335
    timeGetDevCaps(&tc, sizeof(tc));
1336

    
1337
    if (data->period < tc.wPeriodMin)
1338
        data->period = tc.wPeriodMin;
1339

    
1340
    timeBeginPeriod(data->period);
1341

    
1342
    flags = TIME_CALLBACK_FUNCTION;
1343
    if (alarm_has_dynticks(t))
1344
        flags |= TIME_ONESHOT;
1345
    else
1346
        flags |= TIME_PERIODIC;
1347

    
1348
    data->timerId = timeSetEvent(1,         // interval (ms)
1349
                        data->period,       // resolution
1350
                        host_alarm_handler, // function
1351
                        (DWORD)t,           // parameter
1352
                        flags);
1353

    
1354
    if (!data->timerId) {
1355
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1356
                GetLastError());
1357
        timeEndPeriod(data->period);
1358
        return -1;
1359
    }
1360

    
1361
    return 0;
1362
}
1363

    
1364
static void win32_stop_timer(struct qemu_alarm_timer *t)
1365
{
1366
    struct qemu_alarm_win32 *data = t->priv;
1367

    
1368
    timeKillEvent(data->timerId);
1369
    timeEndPeriod(data->period);
1370
}
1371

    
1372
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1373
{
1374
    struct qemu_alarm_win32 *data = t->priv;
1375

    
1376
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1377
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1378
        !active_timers[QEMU_CLOCK_HOST])
1379
        return;
1380

    
1381
    timeKillEvent(data->timerId);
1382

    
1383
    data->timerId = timeSetEvent(1,
1384
                        data->period,
1385
                        host_alarm_handler,
1386
                        (DWORD)t,
1387
                        TIME_ONESHOT | TIME_PERIODIC);
1388

    
1389
    if (!data->timerId) {
1390
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1391
                GetLastError());
1392

    
1393
        timeEndPeriod(data->period);
1394
        exit(1);
1395
    }
1396
}
1397

    
1398
#endif /* _WIN32 */
1399

    
1400
static int init_timer_alarm(void)
1401
{
1402
    struct qemu_alarm_timer *t = NULL;
1403
    int i, err = -1;
1404

    
1405
    for (i = 0; alarm_timers[i].name; i++) {
1406
        t = &alarm_timers[i];
1407

    
1408
        err = t->start(t);
1409
        if (!err)
1410
            break;
1411
    }
1412

    
1413
    if (err) {
1414
        err = -ENOENT;
1415
        goto fail;
1416
    }
1417

    
1418
    alarm_timer = t;
1419

    
1420
    return 0;
1421

    
1422
fail:
1423
    return err;
1424
}
1425

    
1426
static void quit_timers(void)
1427
{
1428
    alarm_timer->stop(alarm_timer);
1429
    alarm_timer = NULL;
1430
}
1431

    
1432
/***********************************************************/
1433
/* host time/date access */
1434
void qemu_get_timedate(struct tm *tm, int offset)
1435
{
1436
    time_t ti;
1437
    struct tm *ret;
1438

    
1439
    time(&ti);
1440
    ti += offset;
1441
    if (rtc_date_offset == -1) {
1442
        if (rtc_utc)
1443
            ret = gmtime(&ti);
1444
        else
1445
            ret = localtime(&ti);
1446
    } else {
1447
        ti -= rtc_date_offset;
1448
        ret = gmtime(&ti);
1449
    }
1450

    
1451
    memcpy(tm, ret, sizeof(struct tm));
1452
}
1453

    
1454
int qemu_timedate_diff(struct tm *tm)
1455
{
1456
    time_t seconds;
1457

    
1458
    if (rtc_date_offset == -1)
1459
        if (rtc_utc)
1460
            seconds = mktimegm(tm);
1461
        else
1462
            seconds = mktime(tm);
1463
    else
1464
        seconds = mktimegm(tm) + rtc_date_offset;
1465

    
1466
    return seconds - time(NULL);
1467
}
1468

    
1469
static void configure_rtc_date_offset(const char *startdate, int legacy)
1470
{
1471
    time_t rtc_start_date;
1472
    struct tm tm;
1473

    
1474
    if (!strcmp(startdate, "now") && legacy) {
1475
        rtc_date_offset = -1;
1476
    } else {
1477
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1478
                   &tm.tm_year,
1479
                   &tm.tm_mon,
1480
                   &tm.tm_mday,
1481
                   &tm.tm_hour,
1482
                   &tm.tm_min,
1483
                   &tm.tm_sec) == 6) {
1484
            /* OK */
1485
        } else if (sscanf(startdate, "%d-%d-%d",
1486
                          &tm.tm_year,
1487
                          &tm.tm_mon,
1488
                          &tm.tm_mday) == 3) {
1489
            tm.tm_hour = 0;
1490
            tm.tm_min = 0;
1491
            tm.tm_sec = 0;
1492
        } else {
1493
            goto date_fail;
1494
        }
1495
        tm.tm_year -= 1900;
1496
        tm.tm_mon--;
1497
        rtc_start_date = mktimegm(&tm);
1498
        if (rtc_start_date == -1) {
1499
        date_fail:
1500
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1501
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1502
            exit(1);
1503
        }
1504
        rtc_date_offset = time(NULL) - rtc_start_date;
1505
    }
1506
}
1507

    
1508
static void configure_rtc(QemuOpts *opts)
1509
{
1510
    const char *value;
1511

    
1512
    value = qemu_opt_get(opts, "base");
1513
    if (value) {
1514
        if (!strcmp(value, "utc")) {
1515
            rtc_utc = 1;
1516
        } else if (!strcmp(value, "localtime")) {
1517
            rtc_utc = 0;
1518
        } else {
1519
            configure_rtc_date_offset(value, 0);
1520
        }
1521
    }
1522
    value = qemu_opt_get(opts, "clock");
1523
    if (value) {
1524
        if (!strcmp(value, "host")) {
1525
            rtc_clock = host_clock;
1526
        } else if (!strcmp(value, "vm")) {
1527
            rtc_clock = vm_clock;
1528
        } else {
1529
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1530
            exit(1);
1531
        }
1532
    }
1533
#ifdef CONFIG_TARGET_I386
1534
    value = qemu_opt_get(opts, "driftfix");
1535
    if (value) {
1536
        if (!strcmp(buf, "slew")) {
1537
            rtc_td_hack = 1;
1538
        } else if (!strcmp(buf, "none")) {
1539
            rtc_td_hack = 0;
1540
        } else {
1541
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1542
            exit(1);
1543
        }
1544
    }
1545
#endif
1546
}
1547

    
1548
#ifdef _WIN32
1549
static void socket_cleanup(void)
1550
{
1551
    WSACleanup();
1552
}
1553

    
1554
static int socket_init(void)
1555
{
1556
    WSADATA Data;
1557
    int ret, err;
1558

    
1559
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1560
    if (ret != 0) {
1561
        err = WSAGetLastError();
1562
        fprintf(stderr, "WSAStartup: %d\n", err);
1563
        return -1;
1564
    }
1565
    atexit(socket_cleanup);
1566
    return 0;
1567
}
1568
#endif
1569

    
1570
/***********************************************************/
1571
/* Bluetooth support */
1572
static int nb_hcis;
1573
static int cur_hci;
1574
static struct HCIInfo *hci_table[MAX_NICS];
1575

    
1576
static struct bt_vlan_s {
1577
    struct bt_scatternet_s net;
1578
    int id;
1579
    struct bt_vlan_s *next;
1580
} *first_bt_vlan;
1581

    
1582
/* find or alloc a new bluetooth "VLAN" */
1583
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1584
{
1585
    struct bt_vlan_s **pvlan, *vlan;
1586
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1587
        if (vlan->id == id)
1588
            return &vlan->net;
1589
    }
1590
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1591
    vlan->id = id;
1592
    pvlan = &first_bt_vlan;
1593
    while (*pvlan != NULL)
1594
        pvlan = &(*pvlan)->next;
1595
    *pvlan = vlan;
1596
    return &vlan->net;
1597
}
1598

    
1599
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1600
{
1601
}
1602

    
1603
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1604
{
1605
    return -ENOTSUP;
1606
}
1607

    
1608
static struct HCIInfo null_hci = {
1609
    .cmd_send = null_hci_send,
1610
    .sco_send = null_hci_send,
1611
    .acl_send = null_hci_send,
1612
    .bdaddr_set = null_hci_addr_set,
1613
};
1614

    
1615
struct HCIInfo *qemu_next_hci(void)
1616
{
1617
    if (cur_hci == nb_hcis)
1618
        return &null_hci;
1619

    
1620
    return hci_table[cur_hci++];
1621
}
1622

    
1623
static struct HCIInfo *hci_init(const char *str)
1624
{
1625
    char *endp;
1626
    struct bt_scatternet_s *vlan = 0;
1627

    
1628
    if (!strcmp(str, "null"))
1629
        /* null */
1630
        return &null_hci;
1631
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1632
        /* host[:hciN] */
1633
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1634
    else if (!strncmp(str, "hci", 3)) {
1635
        /* hci[,vlan=n] */
1636
        if (str[3]) {
1637
            if (!strncmp(str + 3, ",vlan=", 6)) {
1638
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1639
                if (*endp)
1640
                    vlan = 0;
1641
            }
1642
        } else
1643
            vlan = qemu_find_bt_vlan(0);
1644
        if (vlan)
1645
           return bt_new_hci(vlan);
1646
    }
1647

    
1648
    fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);
1649

    
1650
    return 0;
1651
}
1652

    
1653
static int bt_hci_parse(const char *str)
1654
{
1655
    struct HCIInfo *hci;
1656
    bdaddr_t bdaddr;
1657

    
1658
    if (nb_hcis >= MAX_NICS) {
1659
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1660
        return -1;
1661
    }
1662

    
1663
    hci = hci_init(str);
1664
    if (!hci)
1665
        return -1;
1666

    
1667
    bdaddr.b[0] = 0x52;
1668
    bdaddr.b[1] = 0x54;
1669
    bdaddr.b[2] = 0x00;
1670
    bdaddr.b[3] = 0x12;
1671
    bdaddr.b[4] = 0x34;
1672
    bdaddr.b[5] = 0x56 + nb_hcis;
1673
    hci->bdaddr_set(hci, bdaddr.b);
1674

    
1675
    hci_table[nb_hcis++] = hci;
1676

    
1677
    return 0;
1678
}
1679

    
1680
static void bt_vhci_add(int vlan_id)
1681
{
1682
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1683

    
1684
    if (!vlan->slave)
1685
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1686
                        "an empty scatternet %i\n", vlan_id);
1687

    
1688
    bt_vhci_init(bt_new_hci(vlan));
1689
}
1690

    
1691
static struct bt_device_s *bt_device_add(const char *opt)
1692
{
1693
    struct bt_scatternet_s *vlan;
1694
    int vlan_id = 0;
1695
    char *endp = strstr(opt, ",vlan=");
1696
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1697
    char devname[10];
1698

    
1699
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1700

    
1701
    if (endp) {
1702
        vlan_id = strtol(endp + 6, &endp, 0);
1703
        if (*endp) {
1704
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1705
            return 0;
1706
        }
1707
    }
1708

    
1709
    vlan = qemu_find_bt_vlan(vlan_id);
1710

    
1711
    if (!vlan->slave)
1712
        fprintf(stderr, "qemu: warning: adding a slave device to "
1713
                        "an empty scatternet %i\n", vlan_id);
1714

    
1715
    if (!strcmp(devname, "keyboard"))
1716
        return bt_keyboard_init(vlan);
1717

    
1718
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1719
    return 0;
1720
}
1721

    
1722
static int bt_parse(const char *opt)
1723
{
1724
    const char *endp, *p;
1725
    int vlan;
1726

    
1727
    if (strstart(opt, "hci", &endp)) {
1728
        if (!*endp || *endp == ',') {
1729
            if (*endp)
1730
                if (!strstart(endp, ",vlan=", 0))
1731
                    opt = endp + 1;
1732

    
1733
            return bt_hci_parse(opt);
1734
       }
1735
    } else if (strstart(opt, "vhci", &endp)) {
1736
        if (!*endp || *endp == ',') {
1737
            if (*endp) {
1738
                if (strstart(endp, ",vlan=", &p)) {
1739
                    vlan = strtol(p, (char **) &endp, 0);
1740
                    if (*endp) {
1741
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1742
                        return 1;
1743
                    }
1744
                } else {
1745
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1746
                    return 1;
1747
                }
1748
            } else
1749
                vlan = 0;
1750

    
1751
            bt_vhci_add(vlan);
1752
            return 0;
1753
        }
1754
    } else if (strstart(opt, "device:", &endp))
1755
        return !bt_device_add(endp);
1756

    
1757
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1758
    return 1;
1759
}
1760

    
1761
/***********************************************************/
1762
/* QEMU Block devices */
1763

    
1764
#define HD_ALIAS "index=%d,media=disk"
1765
#define CDROM_ALIAS "index=2,media=cdrom"
1766
#define FD_ALIAS "index=%d,if=floppy"
1767
#define PFLASH_ALIAS "if=pflash"
1768
#define MTD_ALIAS "if=mtd"
1769
#define SD_ALIAS "index=0,if=sd"
1770

    
1771
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1772
{
1773
    va_list ap;
1774
    char optstr[1024];
1775
    QemuOpts *opts;
1776

    
1777
    va_start(ap, fmt);
1778
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1779
    va_end(ap);
1780

    
1781
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1782
    if (!opts) {
1783
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1784
                __FUNCTION__, optstr);
1785
        return NULL;
1786
    }
1787
    if (file)
1788
        qemu_opt_set(opts, "file", file);
1789
    return opts;
1790
}
1791

    
1792
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1793
{
1794
    DriveInfo *dinfo;
1795

    
1796
    /* seek interface, bus and unit */
1797

    
1798
    QTAILQ_FOREACH(dinfo, &drives, next) {
1799
        if (dinfo->type == type &&
1800
            dinfo->bus == bus &&
1801
            dinfo->unit == unit)
1802
            return dinfo;
1803
    }
1804

    
1805
    return NULL;
1806
}
1807

    
1808
DriveInfo *drive_get_by_id(const char *id)
1809
{
1810
    DriveInfo *dinfo;
1811

    
1812
    QTAILQ_FOREACH(dinfo, &drives, next) {
1813
        if (strcmp(id, dinfo->id))
1814
            continue;
1815
        return dinfo;
1816
    }
1817
    return NULL;
1818
}
1819

    
1820
int drive_get_max_bus(BlockInterfaceType type)
1821
{
1822
    int max_bus;
1823
    DriveInfo *dinfo;
1824

    
1825
    max_bus = -1;
1826
    QTAILQ_FOREACH(dinfo, &drives, next) {
1827
        if(dinfo->type == type &&
1828
           dinfo->bus > max_bus)
1829
            max_bus = dinfo->bus;
1830
    }
1831
    return max_bus;
1832
}
1833

    
1834
const char *drive_get_serial(BlockDriverState *bdrv)
1835
{
1836
    DriveInfo *dinfo;
1837

    
1838
    QTAILQ_FOREACH(dinfo, &drives, next) {
1839
        if (dinfo->bdrv == bdrv)
1840
            return dinfo->serial;
1841
    }
1842

    
1843
    return "\0";
1844
}
1845

    
1846
BlockInterfaceErrorAction drive_get_on_error(
1847
    BlockDriverState *bdrv, int is_read)
1848
{
1849
    DriveInfo *dinfo;
1850

    
1851
    QTAILQ_FOREACH(dinfo, &drives, next) {
1852
        if (dinfo->bdrv == bdrv)
1853
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1854
    }
1855

    
1856
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1857
}
1858

    
1859
static void bdrv_format_print(void *opaque, const char *name)
1860
{
1861
    fprintf(stderr, " %s", name);
1862
}
1863

    
1864
void drive_uninit(DriveInfo *dinfo)
1865
{
1866
    qemu_opts_del(dinfo->opts);
1867
    bdrv_delete(dinfo->bdrv);
1868
    QTAILQ_REMOVE(&drives, dinfo, next);
1869
    qemu_free(dinfo);
1870
}
1871

    
1872
static int parse_block_error_action(const char *buf, int is_read)
1873
{
1874
    if (!strcmp(buf, "ignore")) {
1875
        return BLOCK_ERR_IGNORE;
1876
    } else if (!is_read && !strcmp(buf, "enospc")) {
1877
        return BLOCK_ERR_STOP_ENOSPC;
1878
    } else if (!strcmp(buf, "stop")) {
1879
        return BLOCK_ERR_STOP_ANY;
1880
    } else if (!strcmp(buf, "report")) {
1881
        return BLOCK_ERR_REPORT;
1882
    } else {
1883
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1884
            buf, is_read ? "read" : "write");
1885
        return -1;
1886
    }
1887
}
1888

    
1889
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1890
                      int *fatal_error)
1891
{
1892
    const char *buf;
1893
    const char *file = NULL;
1894
    char devname[128];
1895
    const char *serial;
1896
    const char *mediastr = "";
1897
    BlockInterfaceType type;
1898
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1899
    int bus_id, unit_id;
1900
    int cyls, heads, secs, translation;
1901
    BlockDriver *drv = NULL;
1902
    QEMUMachine *machine = opaque;
1903
    int max_devs;
1904
    int index;
1905
    int cache;
1906
    int aio = 0;
1907
    int ro = 0;
1908
    int bdrv_flags;
1909
    int on_read_error, on_write_error;
1910
    const char *devaddr;
1911
    DriveInfo *dinfo;
1912
    int snapshot = 0;
1913

    
1914
    *fatal_error = 1;
1915

    
1916
    translation = BIOS_ATA_TRANSLATION_AUTO;
1917
    cache = 1;
1918

    
1919
    if (machine && machine->use_scsi) {
1920
        type = IF_SCSI;
1921
        max_devs = MAX_SCSI_DEVS;
1922
        pstrcpy(devname, sizeof(devname), "scsi");
1923
    } else {
1924
        type = IF_IDE;
1925
        max_devs = MAX_IDE_DEVS;
1926
        pstrcpy(devname, sizeof(devname), "ide");
1927
    }
1928
    media = MEDIA_DISK;
1929

    
1930
    /* extract parameters */
1931
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1932
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1933
    index   = qemu_opt_get_number(opts, "index", -1);
1934

    
1935
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1936
    heads = qemu_opt_get_number(opts, "heads", 0);
1937
    secs  = qemu_opt_get_number(opts, "secs", 0);
1938

    
1939
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1940
    ro = qemu_opt_get_bool(opts, "readonly", 0);
1941

    
1942
    file = qemu_opt_get(opts, "file");
1943
    serial = qemu_opt_get(opts, "serial");
1944

    
1945
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1946
        pstrcpy(devname, sizeof(devname), buf);
1947
        if (!strcmp(buf, "ide")) {
1948
            type = IF_IDE;
1949
            max_devs = MAX_IDE_DEVS;
1950
        } else if (!strcmp(buf, "scsi")) {
1951
            type = IF_SCSI;
1952
            max_devs = MAX_SCSI_DEVS;
1953
        } else if (!strcmp(buf, "floppy")) {
1954
            type = IF_FLOPPY;
1955
            max_devs = 0;
1956
        } else if (!strcmp(buf, "pflash")) {
1957
            type = IF_PFLASH;
1958
            max_devs = 0;
1959
        } else if (!strcmp(buf, "mtd")) {
1960
            type = IF_MTD;
1961
            max_devs = 0;
1962
        } else if (!strcmp(buf, "sd")) {
1963
            type = IF_SD;
1964
            max_devs = 0;
1965
        } else if (!strcmp(buf, "virtio")) {
1966
            type = IF_VIRTIO;
1967
            max_devs = 0;
1968
        } else if (!strcmp(buf, "xen")) {
1969
            type = IF_XEN;
1970
            max_devs = 0;
1971
        } else if (!strcmp(buf, "none")) {
1972
            type = IF_NONE;
1973
            max_devs = 0;
1974
        } else {
1975
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1976
            return NULL;
1977
        }
1978
    }
1979

    
1980
    if (cyls || heads || secs) {
1981
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1982
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1983
            return NULL;
1984
        }
1985
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
1986
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1987
            return NULL;
1988
        }
1989
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
1990
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1991
            return NULL;
1992
        }
1993
    }
1994

    
1995
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1996
        if (!cyls) {
1997
            fprintf(stderr,
1998
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
1999
                    buf);
2000
            return NULL;
2001
        }
2002
        if (!strcmp(buf, "none"))
2003
            translation = BIOS_ATA_TRANSLATION_NONE;
2004
        else if (!strcmp(buf, "lba"))
2005
            translation = BIOS_ATA_TRANSLATION_LBA;
2006
        else if (!strcmp(buf, "auto"))
2007
            translation = BIOS_ATA_TRANSLATION_AUTO;
2008
        else {
2009
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2010
            return NULL;
2011
        }
2012
    }
2013

    
2014
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2015
        if (!strcmp(buf, "disk")) {
2016
            media = MEDIA_DISK;
2017
        } else if (!strcmp(buf, "cdrom")) {
2018
            if (cyls || secs || heads) {
2019
                fprintf(stderr,
2020
                        "qemu: '%s' invalid physical CHS format\n", buf);
2021
                return NULL;
2022
            }
2023
            media = MEDIA_CDROM;
2024
        } else {
2025
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2026
            return NULL;
2027
        }
2028
    }
2029

    
2030
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2031
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2032
            cache = 0;
2033
        else if (!strcmp(buf, "writethrough"))
2034
            cache = 1;
2035
        else if (!strcmp(buf, "writeback"))
2036
            cache = 2;
2037
        else {
2038
           fprintf(stderr, "qemu: invalid cache option\n");
2039
           return NULL;
2040
        }
2041
    }
2042

    
2043
#ifdef CONFIG_LINUX_AIO
2044
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2045
        if (!strcmp(buf, "threads"))
2046
            aio = 0;
2047
        else if (!strcmp(buf, "native"))
2048
            aio = 1;
2049
        else {
2050
           fprintf(stderr, "qemu: invalid aio option\n");
2051
           return NULL;
2052
        }
2053
    }
2054
#endif
2055

    
2056
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2057
       if (strcmp(buf, "?") == 0) {
2058
            fprintf(stderr, "qemu: Supported formats:");
2059
            bdrv_iterate_format(bdrv_format_print, NULL);
2060
            fprintf(stderr, "\n");
2061
            return NULL;
2062
        }
2063
        drv = bdrv_find_whitelisted_format(buf);
2064
        if (!drv) {
2065
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2066
            return NULL;
2067
        }
2068
    }
2069

    
2070
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2071
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2072
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2073
            fprintf(stderr, "werror is no supported by this format\n");
2074
            return NULL;
2075
        }
2076

    
2077
        on_write_error = parse_block_error_action(buf, 0);
2078
        if (on_write_error < 0) {
2079
            return NULL;
2080
        }
2081
    }
2082

    
2083
    on_read_error = BLOCK_ERR_REPORT;
2084
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2085
        if (type != IF_IDE && type != IF_VIRTIO) {
2086
            fprintf(stderr, "rerror is no supported by this format\n");
2087
            return NULL;
2088
        }
2089

    
2090
        on_read_error = parse_block_error_action(buf, 1);
2091
        if (on_read_error < 0) {
2092
            return NULL;
2093
        }
2094
    }
2095

    
2096
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2097
        if (type != IF_VIRTIO) {
2098
            fprintf(stderr, "addr is not supported\n");
2099
            return NULL;
2100
        }
2101
    }
2102

    
2103
    /* compute bus and unit according index */
2104

    
2105
    if (index != -1) {
2106
        if (bus_id != 0 || unit_id != -1) {
2107
            fprintf(stderr,
2108
                    "qemu: index cannot be used with bus and unit\n");
2109
            return NULL;
2110
        }
2111
        if (max_devs == 0)
2112
        {
2113
            unit_id = index;
2114
            bus_id = 0;
2115
        } else {
2116
            unit_id = index % max_devs;
2117
            bus_id = index / max_devs;
2118
        }
2119
    }
2120

    
2121
    /* if user doesn't specify a unit_id,
2122
     * try to find the first free
2123
     */
2124

    
2125
    if (unit_id == -1) {
2126
       unit_id = 0;
2127
       while (drive_get(type, bus_id, unit_id) != NULL) {
2128
           unit_id++;
2129
           if (max_devs && unit_id >= max_devs) {
2130
               unit_id -= max_devs;
2131
               bus_id++;
2132
           }
2133
       }
2134
    }
2135

    
2136
    /* check unit id */
2137

    
2138
    if (max_devs && unit_id >= max_devs) {
2139
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2140
                unit_id, max_devs - 1);
2141
        return NULL;
2142
    }
2143

    
2144
    /*
2145
     * ignore multiple definitions
2146
     */
2147

    
2148
    if (drive_get(type, bus_id, unit_id) != NULL) {
2149
        *fatal_error = 0;
2150
        return NULL;
2151
    }
2152

    
2153
    /* init */
2154

    
2155
    dinfo = qemu_mallocz(sizeof(*dinfo));
2156
    if ((buf = qemu_opts_id(opts)) != NULL) {
2157
        dinfo->id = qemu_strdup(buf);
2158
    } else {
2159
        /* no id supplied -> create one */
2160
        dinfo->id = qemu_mallocz(32);
2161
        if (type == IF_IDE || type == IF_SCSI)
2162
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2163
        if (max_devs)
2164
            snprintf(dinfo->id, 32, "%s%i%s%i",
2165
                     devname, bus_id, mediastr, unit_id);
2166
        else
2167
            snprintf(dinfo->id, 32, "%s%s%i",
2168
                     devname, mediastr, unit_id);
2169
    }
2170
    dinfo->bdrv = bdrv_new(dinfo->id);
2171
    dinfo->devaddr = devaddr;
2172
    dinfo->type = type;
2173
    dinfo->bus = bus_id;
2174
    dinfo->unit = unit_id;
2175
    dinfo->on_read_error = on_read_error;
2176
    dinfo->on_write_error = on_write_error;
2177
    dinfo->opts = opts;
2178
    if (serial)
2179
        strncpy(dinfo->serial, serial, sizeof(serial));
2180
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2181

    
2182
    switch(type) {
2183
    case IF_IDE:
2184
    case IF_SCSI:
2185
    case IF_XEN:
2186
    case IF_NONE:
2187
        switch(media) {
2188
        case MEDIA_DISK:
2189
            if (cyls != 0) {
2190
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2191
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2192
            }
2193
            break;
2194
        case MEDIA_CDROM:
2195
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2196
            break;
2197
        }
2198
        break;
2199
    case IF_SD:
2200
        /* FIXME: This isn't really a floppy, but it's a reasonable
2201
           approximation.  */
2202
    case IF_FLOPPY:
2203
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2204
        break;
2205
    case IF_PFLASH:
2206
    case IF_MTD:
2207
        break;
2208
    case IF_VIRTIO:
2209
        /* add virtio block device */
2210
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2211
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
2212
        qemu_opt_set(opts, "drive", dinfo->id);
2213
        if (devaddr)
2214
            qemu_opt_set(opts, "addr", devaddr);
2215
        break;
2216
    case IF_COUNT:
2217
        abort();
2218
    }
2219
    if (!file) {
2220
        *fatal_error = 0;
2221
        return NULL;
2222
    }
2223
    bdrv_flags = 0;
2224
    if (snapshot) {
2225
        bdrv_flags |= BDRV_O_SNAPSHOT;
2226
        cache = 2; /* always use write-back with snapshot */
2227
    }
2228
    if (cache == 0) /* no caching */
2229
        bdrv_flags |= BDRV_O_NOCACHE;
2230
    else if (cache == 2) /* write-back */
2231
        bdrv_flags |= BDRV_O_CACHE_WB;
2232

    
2233
    if (aio == 1) {
2234
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2235
    } else {
2236
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2237
    }
2238

    
2239
    if (ro == 1) {
2240
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2241
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2242
            return NULL;
2243
        }
2244
    }
2245
    /* 
2246
     * cdrom is read-only. Set it now, after above interface checking
2247
     * since readonly attribute not explicitly required, so no error.
2248
     */
2249
    if (media == MEDIA_CDROM) {
2250
        ro = 1;
2251
    }
2252
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2253

    
2254
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2255
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2256
                        file, strerror(errno));
2257
        return NULL;
2258
    }
2259

    
2260
    if (bdrv_key_required(dinfo->bdrv))
2261
        autostart = 0;
2262
    *fatal_error = 0;
2263
    return dinfo;
2264
}
2265

    
2266
static int drive_init_func(QemuOpts *opts, void *opaque)
2267
{
2268
    QEMUMachine *machine = opaque;
2269
    int fatal_error = 0;
2270

    
2271
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2272
        if (fatal_error)
2273
            return 1;
2274
    }
2275
    return 0;
2276
}
2277

    
2278
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2279
{
2280
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2281
        qemu_opt_set(opts, "snapshot", "on");
2282
    }
2283
    return 0;
2284
}
2285

    
2286
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2287
{
2288
    boot_set_handler = func;
2289
    boot_set_opaque = opaque;
2290
}
2291

    
2292
int qemu_boot_set(const char *boot_devices)
2293
{
2294
    if (!boot_set_handler) {
2295
        return -EINVAL;
2296
    }
2297
    return boot_set_handler(boot_set_opaque, boot_devices);
2298
}
2299

    
2300
static int parse_bootdevices(char *devices)
2301
{
2302
    /* We just do some generic consistency checks */
2303
    const char *p;
2304
    int bitmap = 0;
2305

    
2306
    for (p = devices; *p != '\0'; p++) {
2307
        /* Allowed boot devices are:
2308
         * a-b: floppy disk drives
2309
         * c-f: IDE disk drives
2310
         * g-m: machine implementation dependant drives
2311
         * n-p: network devices
2312
         * It's up to each machine implementation to check if the given boot
2313
         * devices match the actual hardware implementation and firmware
2314
         * features.
2315
         */
2316
        if (*p < 'a' || *p > 'p') {
2317
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2318
            exit(1);
2319
        }
2320
        if (bitmap & (1 << (*p - 'a'))) {
2321
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2322
            exit(1);
2323
        }
2324
        bitmap |= 1 << (*p - 'a');
2325
    }
2326
    return bitmap;
2327
}
2328

    
2329
static void restore_boot_devices(void *opaque)
2330
{
2331
    char *standard_boot_devices = opaque;
2332

    
2333
    qemu_boot_set(standard_boot_devices);
2334

    
2335
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2336
    qemu_free(standard_boot_devices);
2337
}
2338

    
2339
static void numa_add(const char *optarg)
2340
{
2341
    char option[128];
2342
    char *endptr;
2343
    unsigned long long value, endvalue;
2344
    int nodenr;
2345

    
2346
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2347
    if (!strcmp(option, "node")) {
2348
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2349
            nodenr = nb_numa_nodes;
2350
        } else {
2351
            nodenr = strtoull(option, NULL, 10);
2352
        }
2353

    
2354
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2355
            node_mem[nodenr] = 0;
2356
        } else {
2357
            value = strtoull(option, &endptr, 0);
2358
            switch (*endptr) {
2359
            case 0: case 'M': case 'm':
2360
                value <<= 20;
2361
                break;
2362
            case 'G': case 'g':
2363
                value <<= 30;
2364
                break;
2365
            }
2366
            node_mem[nodenr] = value;
2367
        }
2368
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2369
            node_cpumask[nodenr] = 0;
2370
        } else {
2371
            value = strtoull(option, &endptr, 10);
2372
            if (value >= 64) {
2373
                value = 63;
2374
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2375
            } else {
2376
                if (*endptr == '-') {
2377
                    endvalue = strtoull(endptr+1, &endptr, 10);
2378
                    if (endvalue >= 63) {
2379
                        endvalue = 62;
2380
                        fprintf(stderr,
2381
                            "only 63 CPUs in NUMA mode supported.\n");
2382
                    }
2383
                    value = (2ULL << endvalue) - (1ULL << value);
2384
                } else {
2385
                    value = 1ULL << value;
2386
                }
2387
            }
2388
            node_cpumask[nodenr] = value;
2389
        }
2390
        nb_numa_nodes++;
2391
    }
2392
    return;
2393
}
2394

    
2395
static void smp_parse(const char *optarg)
2396
{
2397
    int smp, sockets = 0, threads = 0, cores = 0;
2398
    char *endptr;
2399
    char option[128];
2400

    
2401
    smp = strtoul(optarg, &endptr, 10);
2402
    if (endptr != optarg) {
2403
        if (*endptr == ',') {
2404
            endptr++;
2405
        }
2406
    }
2407
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2408
        sockets = strtoull(option, NULL, 10);
2409
    if (get_param_value(option, 128, "cores", endptr) != 0)
2410
        cores = strtoull(option, NULL, 10);
2411
    if (get_param_value(option, 128, "threads", endptr) != 0)
2412
        threads = strtoull(option, NULL, 10);
2413
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2414
        max_cpus = strtoull(option, NULL, 10);
2415

    
2416
    /* compute missing values, prefer sockets over cores over threads */
2417
    if (smp == 0 || sockets == 0) {
2418
        sockets = sockets > 0 ? sockets : 1;
2419
        cores = cores > 0 ? cores : 1;
2420
        threads = threads > 0 ? threads : 1;
2421
        if (smp == 0) {
2422
            smp = cores * threads * sockets;
2423
        }
2424
    } else {
2425
        if (cores == 0) {
2426
            threads = threads > 0 ? threads : 1;
2427
            cores = smp / (sockets * threads);
2428
        } else {
2429
            if (sockets) {
2430
                threads = smp / (cores * sockets);
2431
            }
2432
        }
2433
    }
2434
    smp_cpus = smp;
2435
    smp_cores = cores > 0 ? cores : 1;
2436
    smp_threads = threads > 0 ? threads : 1;
2437
    if (max_cpus == 0)
2438
        max_cpus = smp_cpus;
2439
}
2440

    
2441
/***********************************************************/
2442
/* USB devices */
2443

    
2444
static int usb_device_add(const char *devname, int is_hotplug)
2445
{
2446
    const char *p;
2447
    USBDevice *dev = NULL;
2448

    
2449
    if (!usb_enabled)
2450
        return -1;
2451

    
2452
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2453
    dev = usbdevice_create(devname);
2454
    if (dev)
2455
        goto done;
2456

    
2457
    /* the other ones */
2458
    if (strstart(devname, "host:", &p)) {
2459
        dev = usb_host_device_open(p);
2460
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2461
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2462
                        bt_new_hci(qemu_find_bt_vlan(0)));
2463
    } else {
2464
        return -1;
2465
    }
2466
    if (!dev)
2467
        return -1;
2468

    
2469
done:
2470
    return 0;
2471
}
2472

    
2473
static int usb_device_del(const char *devname)
2474
{
2475
    int bus_num, addr;
2476
    const char *p;
2477

    
2478
    if (strstart(devname, "host:", &p))
2479
        return usb_host_device_close(p);
2480

    
2481
    if (!usb_enabled)
2482
        return -1;
2483

    
2484
    p = strchr(devname, '.');
2485
    if (!p)
2486
        return -1;
2487
    bus_num = strtoul(devname, NULL, 0);
2488
    addr = strtoul(p + 1, NULL, 0);
2489

    
2490
    return usb_device_delete_addr(bus_num, addr);
2491
}
2492

    
2493
static int usb_parse(const char *cmdline)
2494
{
2495
    int r;
2496
    r = usb_device_add(cmdline, 0);
2497
    if (r < 0) {
2498
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2499
    }
2500
    return r;
2501
}
2502

    
2503
void do_usb_add(Monitor *mon, const QDict *qdict)
2504
{
2505
    const char *devname = qdict_get_str(qdict, "devname");
2506
    if (usb_device_add(devname, 1) < 0) {
2507
        qemu_error("could not add USB device '%s'\n", devname);
2508
    }
2509
}
2510

    
2511
void do_usb_del(Monitor *mon, const QDict *qdict)
2512
{
2513
    const char *devname = qdict_get_str(qdict, "devname");
2514
    if (usb_device_del(devname) < 0) {
2515
        qemu_error("could not delete USB device '%s'\n", devname);
2516
    }
2517
}
2518

    
2519
/***********************************************************/
2520
/* PCMCIA/Cardbus */
2521

    
2522
static struct pcmcia_socket_entry_s {
2523
    PCMCIASocket *socket;
2524
    struct pcmcia_socket_entry_s *next;
2525
} *pcmcia_sockets = 0;
2526

    
2527
void pcmcia_socket_register(PCMCIASocket *socket)
2528
{
2529
    struct pcmcia_socket_entry_s *entry;
2530

    
2531
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2532
    entry->socket = socket;
2533
    entry->next = pcmcia_sockets;
2534
    pcmcia_sockets = entry;
2535
}
2536

    
2537
void pcmcia_socket_unregister(PCMCIASocket *socket)
2538
{
2539
    struct pcmcia_socket_entry_s *entry, **ptr;
2540

    
2541
    ptr = &pcmcia_sockets;
2542
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2543
        if (entry->socket == socket) {
2544
            *ptr = entry->next;
2545
            qemu_free(entry);
2546
        }
2547
}
2548

    
2549
void pcmcia_info(Monitor *mon)
2550
{
2551
    struct pcmcia_socket_entry_s *iter;
2552

    
2553
    if (!pcmcia_sockets)
2554
        monitor_printf(mon, "No PCMCIA sockets\n");
2555

    
2556
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2557
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2558
                       iter->socket->attached ? iter->socket->card_string :
2559
                       "Empty");
2560
}
2561

    
2562
/***********************************************************/
2563
/* register display */
2564

    
2565
struct DisplayAllocator default_allocator = {
2566
    defaultallocator_create_displaysurface,
2567
    defaultallocator_resize_displaysurface,
2568
    defaultallocator_free_displaysurface
2569
};
2570

    
2571
void register_displaystate(DisplayState *ds)
2572
{
2573
    DisplayState **s;
2574
    s = &display_state;
2575
    while (*s != NULL)
2576
        s = &(*s)->next;
2577
    ds->next = NULL;
2578
    *s = ds;
2579
}
2580

    
2581
DisplayState *get_displaystate(void)
2582
{
2583
    return display_state;
2584
}
2585

    
2586
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2587
{
2588
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2589
    return ds->allocator;
2590
}
2591

    
2592
/* dumb display */
2593

    
2594
static void dumb_display_init(void)
2595
{
2596
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2597
    ds->allocator = &default_allocator;
2598
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2599
    register_displaystate(ds);
2600
}
2601

    
2602
/***********************************************************/
2603
/* I/O handling */
2604

    
2605
typedef struct IOHandlerRecord {
2606
    int fd;
2607
    IOCanRWHandler *fd_read_poll;
2608
    IOHandler *fd_read;
2609
    IOHandler *fd_write;
2610
    int deleted;
2611
    void *opaque;
2612
    /* temporary data */
2613
    struct pollfd *ufd;
2614
    struct IOHandlerRecord *next;
2615
} IOHandlerRecord;
2616

    
2617
static IOHandlerRecord *first_io_handler;
2618

    
2619
/* XXX: fd_read_poll should be suppressed, but an API change is
2620
   necessary in the character devices to suppress fd_can_read(). */
2621
int qemu_set_fd_handler2(int fd,
2622
                         IOCanRWHandler *fd_read_poll,
2623
                         IOHandler *fd_read,
2624
                         IOHandler *fd_write,
2625
                         void *opaque)
2626
{
2627
    IOHandlerRecord **pioh, *ioh;
2628

    
2629
    if (!fd_read && !fd_write) {
2630
        pioh = &first_io_handler;
2631
        for(;;) {
2632
            ioh = *pioh;
2633
            if (ioh == NULL)
2634
                break;
2635
            if (ioh->fd == fd) {
2636
                ioh->deleted = 1;
2637
                break;
2638
            }
2639
            pioh = &ioh->next;
2640
        }
2641
    } else {
2642
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2643
            if (ioh->fd == fd)
2644
                goto found;
2645
        }
2646
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2647
        ioh->next = first_io_handler;
2648
        first_io_handler = ioh;
2649
    found:
2650
        ioh->fd = fd;
2651
        ioh->fd_read_poll = fd_read_poll;
2652
        ioh->fd_read = fd_read;
2653
        ioh->fd_write = fd_write;
2654
        ioh->opaque = opaque;
2655
        ioh->deleted = 0;
2656
    }
2657
    return 0;
2658
}
2659

    
2660
int qemu_set_fd_handler(int fd,
2661
                        IOHandler *fd_read,
2662
                        IOHandler *fd_write,
2663
                        void *opaque)
2664
{
2665
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2666
}
2667

    
2668
#ifdef _WIN32
2669
/***********************************************************/
2670
/* Polling handling */
2671

    
2672
typedef struct PollingEntry {
2673
    PollingFunc *func;
2674
    void *opaque;
2675
    struct PollingEntry *next;
2676
} PollingEntry;
2677

    
2678
static PollingEntry *first_polling_entry;
2679

    
2680
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2681
{
2682
    PollingEntry **ppe, *pe;
2683
    pe = qemu_mallocz(sizeof(PollingEntry));
2684
    pe->func = func;
2685
    pe->opaque = opaque;
2686
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2687
    *ppe = pe;
2688
    return 0;
2689
}
2690

    
2691
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2692
{
2693
    PollingEntry **ppe, *pe;
2694
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2695
        pe = *ppe;
2696
        if (pe->func == func && pe->opaque == opaque) {
2697
            *ppe = pe->next;
2698
            qemu_free(pe);
2699
            break;
2700
        }
2701
    }
2702
}
2703

    
2704
/***********************************************************/
2705
/* Wait objects support */
2706
typedef struct WaitObjects {
2707
    int num;
2708
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2709
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2710
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2711
} WaitObjects;
2712

    
2713
static WaitObjects wait_objects = {0};
2714

    
2715
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2716
{
2717
    WaitObjects *w = &wait_objects;
2718

    
2719
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2720
        return -1;
2721
    w->events[w->num] = handle;
2722
    w->func[w->num] = func;
2723
    w->opaque[w->num] = opaque;
2724
    w->num++;
2725
    return 0;
2726
}
2727

    
2728
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2729
{
2730
    int i, found;
2731
    WaitObjects *w = &wait_objects;
2732

    
2733
    found = 0;
2734
    for (i = 0; i < w->num; i++) {
2735
        if (w->events[i] == handle)
2736
            found = 1;
2737
        if (found) {
2738
            w->events[i] = w->events[i + 1];
2739
            w->func[i] = w->func[i + 1];
2740
            w->opaque[i] = w->opaque[i + 1];
2741
        }
2742
    }
2743
    if (found)
2744
        w->num--;
2745
}
2746
#endif
2747

    
2748
/***********************************************************/
2749
/* ram save/restore */
2750

    
2751
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2752
#define RAM_SAVE_FLAG_COMPRESS        0x02
2753
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2754
#define RAM_SAVE_FLAG_PAGE        0x08
2755
#define RAM_SAVE_FLAG_EOS        0x10
2756

    
2757
static int is_dup_page(uint8_t *page, uint8_t ch)
2758
{
2759
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2760
    uint32_t *array = (uint32_t *)page;
2761
    int i;
2762

    
2763
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2764
        if (array[i] != val)
2765
            return 0;
2766
    }
2767

    
2768
    return 1;
2769
}
2770

    
2771
static int ram_save_block(QEMUFile *f)
2772
{
2773
    static ram_addr_t current_addr = 0;
2774
    ram_addr_t saved_addr = current_addr;
2775
    ram_addr_t addr = 0;
2776
    int found = 0;
2777

    
2778
    while (addr < last_ram_offset) {
2779
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2780
            uint8_t *p;
2781

    
2782
            cpu_physical_memory_reset_dirty(current_addr,
2783
                                            current_addr + TARGET_PAGE_SIZE,
2784
                                            MIGRATION_DIRTY_FLAG);
2785

    
2786
            p = qemu_get_ram_ptr(current_addr);
2787

    
2788
            if (is_dup_page(p, *p)) {
2789
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2790
                qemu_put_byte(f, *p);
2791
            } else {
2792
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2793
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2794
            }
2795

    
2796
            found = 1;
2797
            break;
2798
        }
2799
        addr += TARGET_PAGE_SIZE;
2800
        current_addr = (saved_addr + addr) % last_ram_offset;
2801
    }
2802

    
2803
    return found;
2804
}
2805

    
2806
static uint64_t bytes_transferred;
2807

    
2808
static ram_addr_t ram_save_remaining(void)
2809
{
2810
    ram_addr_t addr;
2811
    ram_addr_t count = 0;
2812

    
2813
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2814
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2815
            count++;
2816
    }
2817

    
2818
    return count;
2819
}
2820

    
2821
uint64_t ram_bytes_remaining(void)
2822
{
2823
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2824
}
2825

    
2826
uint64_t ram_bytes_transferred(void)
2827
{
2828
    return bytes_transferred;
2829
}
2830

    
2831
uint64_t ram_bytes_total(void)
2832
{
2833
    return last_ram_offset;
2834
}
2835

    
2836
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2837
{
2838
    ram_addr_t addr;
2839
    uint64_t bytes_transferred_last;
2840
    double bwidth = 0;
2841
    uint64_t expected_time = 0;
2842

    
2843
    if (stage < 0) {
2844
        cpu_physical_memory_set_dirty_tracking(0);
2845
        return 0;
2846
    }
2847

    
2848
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2849
        qemu_file_set_error(f);
2850
        return 0;
2851
    }
2852

    
2853
    if (stage == 1) {
2854
        bytes_transferred = 0;
2855

    
2856
        /* Make sure all dirty bits are set */
2857
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2858
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2859
                cpu_physical_memory_set_dirty(addr);
2860
        }
2861

    
2862
        /* Enable dirty memory tracking */
2863
        cpu_physical_memory_set_dirty_tracking(1);
2864

    
2865
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2866
    }
2867

    
2868
    bytes_transferred_last = bytes_transferred;
2869
    bwidth = get_clock();
2870

    
2871
    while (!qemu_file_rate_limit(f)) {
2872
        int ret;
2873

    
2874
        ret = ram_save_block(f);
2875
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2876
        if (ret == 0) /* no more blocks */
2877
            break;
2878
    }
2879

    
2880
    bwidth = get_clock() - bwidth;
2881
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2882

    
2883
    /* if we haven't transferred anything this round, force expected_time to a
2884
     * a very high value, but without crashing */
2885
    if (bwidth == 0)
2886
        bwidth = 0.000001;
2887

    
2888
    /* try transferring iterative blocks of memory */
2889
    if (stage == 3) {
2890
        /* flush all remaining blocks regardless of rate limiting */
2891
        while (ram_save_block(f) != 0) {
2892
            bytes_transferred += TARGET_PAGE_SIZE;
2893
        }
2894
        cpu_physical_memory_set_dirty_tracking(0);
2895
    }
2896

    
2897
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2898

    
2899
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2900

    
2901
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2902
}
2903

    
2904
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2905
{
2906
    ram_addr_t addr;
2907
    int flags;
2908

    
2909
    if (version_id != 3)
2910
        return -EINVAL;
2911

    
2912
    do {
2913
        addr = qemu_get_be64(f);
2914

    
2915
        flags = addr & ~TARGET_PAGE_MASK;
2916
        addr &= TARGET_PAGE_MASK;
2917

    
2918
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2919
            if (addr != last_ram_offset)
2920
                return -EINVAL;
2921
        }
2922

    
2923
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2924
            uint8_t ch = qemu_get_byte(f);
2925
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2926
#ifndef _WIN32
2927
            if (ch == 0 &&
2928
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2929
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2930
            }
2931
#endif
2932
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
2933
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2934
        }
2935
        if (qemu_file_has_error(f)) {
2936
            return -EIO;
2937
        }
2938
    } while (!(flags & RAM_SAVE_FLAG_EOS));
2939

    
2940
    return 0;
2941
}
2942

    
2943
void qemu_service_io(void)
2944
{
2945
    qemu_notify_event();
2946
}
2947

    
2948
/***********************************************************/
2949
/* machine registration */
2950

    
2951
static QEMUMachine *first_machine = NULL;
2952
QEMUMachine *current_machine = NULL;
2953

    
2954
int qemu_register_machine(QEMUMachine *m)
2955
{
2956
    QEMUMachine **pm;
2957
    pm = &first_machine;
2958
    while (*pm != NULL)
2959
        pm = &(*pm)->next;
2960
    m->next = NULL;
2961
    *pm = m;
2962
    return 0;
2963
}
2964

    
2965
static QEMUMachine *find_machine(const char *name)
2966
{
2967
    QEMUMachine *m;
2968

    
2969
    for(m = first_machine; m != NULL; m = m->next) {
2970
        if (!strcmp(m->name, name))
2971
            return m;
2972
        if (m->alias && !strcmp(m->alias, name))
2973
            return m;
2974
    }
2975
    return NULL;
2976
}
2977

    
2978
static QEMUMachine *find_default_machine(void)
2979
{
2980
    QEMUMachine *m;
2981

    
2982
    for(m = first_machine; m != NULL; m = m->next) {
2983
        if (m->is_default) {
2984
            return m;
2985
        }
2986
    }
2987
    return NULL;
2988
}
2989

    
2990
/***********************************************************/
2991
/* main execution loop */
2992

    
2993
static void gui_update(void *opaque)
2994
{
2995
    uint64_t interval = GUI_REFRESH_INTERVAL;
2996
    DisplayState *ds = opaque;
2997
    DisplayChangeListener *dcl = ds->listeners;
2998

    
2999
    dpy_refresh(ds);
3000

    
3001
    while (dcl != NULL) {
3002
        if (dcl->gui_timer_interval &&
3003
            dcl->gui_timer_interval < interval)
3004
            interval = dcl->gui_timer_interval;
3005
        dcl = dcl->next;
3006
    }
3007
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3008
}
3009

    
3010
static void nographic_update(void *opaque)
3011
{
3012
    uint64_t interval = GUI_REFRESH_INTERVAL;
3013

    
3014
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3015
}
3016

    
3017
struct vm_change_state_entry {
3018
    VMChangeStateHandler *cb;
3019
    void *opaque;
3020
    QLIST_ENTRY (vm_change_state_entry) entries;
3021
};
3022

    
3023
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3024

    
3025
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3026
                                                     void *opaque)
3027
{
3028
    VMChangeStateEntry *e;
3029

    
3030
    e = qemu_mallocz(sizeof (*e));
3031

    
3032
    e->cb = cb;
3033
    e->opaque = opaque;
3034
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3035
    return e;
3036
}
3037

    
3038
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3039
{
3040
    QLIST_REMOVE (e, entries);
3041
    qemu_free (e);
3042
}
3043

    
3044
static void vm_state_notify(int running, int reason)
3045
{
3046
    VMChangeStateEntry *e;
3047

    
3048
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3049
        e->cb(e->opaque, running, reason);
3050
    }
3051
}
3052

    
3053
static void resume_all_vcpus(void);
3054
static void pause_all_vcpus(void);
3055

    
3056
void vm_start(void)
3057
{
3058
    if (!vm_running) {
3059
        cpu_enable_ticks();
3060
        vm_running = 1;
3061
        vm_state_notify(1, 0);
3062
        qemu_rearm_alarm_timer(alarm_timer);
3063
        resume_all_vcpus();
3064
    }
3065
}
3066

    
3067
/* reset/shutdown handler */
3068

    
3069
typedef struct QEMUResetEntry {
3070
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3071
    QEMUResetHandler *func;
3072
    void *opaque;
3073
} QEMUResetEntry;
3074

    
3075
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3076
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3077
static int reset_requested;
3078
static int shutdown_requested;
3079
static int powerdown_requested;
3080
static int debug_requested;
3081
static int vmstop_requested;
3082

    
3083
int qemu_shutdown_requested(void)
3084
{
3085
    int r = shutdown_requested;
3086
    shutdown_requested = 0;
3087
    return r;
3088
}
3089

    
3090
int qemu_reset_requested(void)
3091
{
3092
    int r = reset_requested;
3093
    reset_requested = 0;
3094
    return r;
3095
}
3096

    
3097
int qemu_powerdown_requested(void)
3098
{
3099
    int r = powerdown_requested;
3100
    powerdown_requested = 0;
3101
    return r;
3102
}
3103

    
3104
static int qemu_debug_requested(void)
3105
{
3106
    int r = debug_requested;
3107
    debug_requested = 0;
3108
    return r;
3109
}
3110

    
3111
static int qemu_vmstop_requested(void)
3112
{
3113
    int r = vmstop_requested;
3114
    vmstop_requested = 0;
3115
    return r;
3116
}
3117

    
3118
static void do_vm_stop(int reason)
3119
{
3120
    if (vm_running) {
3121
        cpu_disable_ticks();
3122
        vm_running = 0;
3123
        pause_all_vcpus();
3124
        vm_state_notify(0, reason);
3125
    }
3126
}
3127

    
3128
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3129
{
3130
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3131

    
3132
    re->func = func;
3133
    re->opaque = opaque;
3134
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3135
}
3136

    
3137
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3138
{
3139
    QEMUResetEntry *re;
3140

    
3141
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3142
        if (re->func == func && re->opaque == opaque) {
3143
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3144
            qemu_free(re);
3145
            return;
3146
        }
3147
    }
3148
}
3149

    
3150
void qemu_system_reset(void)
3151
{
3152
    QEMUResetEntry *re, *nre;
3153

    
3154
    /* reset all devices */
3155
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3156
        re->func(re->opaque);
3157
    }
3158
}
3159

    
3160
void qemu_system_reset_request(void)
3161
{
3162
    if (no_reboot) {
3163
        shutdown_requested = 1;
3164
    } else {
3165
        reset_requested = 1;
3166
    }
3167
    qemu_notify_event();
3168
}
3169

    
3170
void qemu_system_shutdown_request(void)
3171
{
3172
    shutdown_requested = 1;
3173
    qemu_notify_event();
3174
}
3175

    
3176
void qemu_system_powerdown_request(void)
3177
{
3178
    powerdown_requested = 1;
3179
    qemu_notify_event();
3180
}
3181

    
3182
#ifdef CONFIG_IOTHREAD
3183
static void qemu_system_vmstop_request(int reason)
3184
{
3185
    vmstop_requested = reason;
3186
    qemu_notify_event();
3187
}
3188
#endif
3189

    
3190
#ifndef _WIN32
3191
static int io_thread_fd = -1;
3192

    
3193
static void qemu_event_increment(void)
3194
{
3195
    static const char byte = 0;
3196
    ssize_t ret;
3197

    
3198
    if (io_thread_fd == -1)
3199
        return;
3200

    
3201
    ret = write(io_thread_fd, &byte, sizeof(byte));
3202
    if (ret < 0 && (errno != EINTR && errno != EAGAIN)) {
3203
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3204
                strerror(errno));
3205
        exit (1);
3206
    }
3207
}
3208

    
3209
static void qemu_event_read(void *opaque)
3210
{
3211
    int fd = (unsigned long)opaque;
3212
    ssize_t len;
3213

    
3214
    /* Drain the notify pipe */
3215
    do {
3216
        char buffer[512];
3217
        len = read(fd, buffer, sizeof(buffer));
3218
    } while ((len == -1 && errno == EINTR) || len > 0);
3219
}
3220

    
3221
static int qemu_event_init(void)
3222
{
3223
    int err;
3224
    int fds[2];
3225

    
3226
    err = qemu_pipe(fds);
3227
    if (err == -1)
3228
        return -errno;
3229

    
3230
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3231
    if (err < 0)
3232
        goto fail;
3233

    
3234
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3235
    if (err < 0)
3236
        goto fail;
3237

    
3238
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3239
                         (void *)(unsigned long)fds[0]);
3240

    
3241
    io_thread_fd = fds[1];
3242
    return 0;
3243

    
3244
fail:
3245
    close(fds[0]);
3246
    close(fds[1]);
3247
    return err;
3248
}
3249
#else
3250
HANDLE qemu_event_handle;
3251

    
3252
static void dummy_event_handler(void *opaque)
3253
{
3254
}
3255

    
3256
static int qemu_event_init(void)
3257
{
3258
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3259
    if (!qemu_event_handle) {
3260
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3261
        return -1;
3262
    }
3263
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3264
    return 0;
3265
}
3266

    
3267
static void qemu_event_increment(void)
3268
{
3269
    if (!SetEvent(qemu_event_handle)) {
3270
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3271
                GetLastError());
3272
        exit (1);
3273
    }
3274
}
3275
#endif
3276

    
3277
static int cpu_can_run(CPUState *env)
3278
{
3279
    if (env->stop)
3280
        return 0;
3281
    if (env->stopped)
3282
        return 0;
3283
    return 1;
3284
}
3285

    
3286
#ifndef CONFIG_IOTHREAD
3287
static int qemu_init_main_loop(void)
3288
{
3289
    return qemu_event_init();
3290
}
3291

    
3292
void qemu_init_vcpu(void *_env)
3293
{
3294
    CPUState *env = _env;
3295

    
3296
    env->nr_cores = smp_cores;
3297
    env->nr_threads = smp_threads;
3298
    if (kvm_enabled())
3299
        kvm_init_vcpu(env);
3300
    return;
3301
}
3302

    
3303
int qemu_cpu_self(void *env)
3304
{
3305
    return 1;
3306
}
3307

    
3308
static void resume_all_vcpus(void)
3309
{
3310
}
3311

    
3312
static void pause_all_vcpus(void)
3313
{
3314
}
3315

    
3316
void qemu_cpu_kick(void *env)
3317
{
3318
    return;
3319
}
3320

    
3321
void qemu_notify_event(void)
3322
{
3323
    CPUState *env = cpu_single_env;
3324

    
3325
    if (env) {
3326
        cpu_exit(env);
3327
    }
3328
}
3329

    
3330
void qemu_mutex_lock_iothread(void) {}
3331
void qemu_mutex_unlock_iothread(void) {}
3332

    
3333
void vm_stop(int reason)
3334
{
3335
    do_vm_stop(reason);
3336
}
3337

    
3338
#else /* CONFIG_IOTHREAD */
3339

    
3340
#include "qemu-thread.h"
3341

    
3342
QemuMutex qemu_global_mutex;
3343
static QemuMutex qemu_fair_mutex;
3344

    
3345
static QemuThread io_thread;
3346

    
3347
static QemuThread *tcg_cpu_thread;
3348
static QemuCond *tcg_halt_cond;
3349

    
3350
static int qemu_system_ready;
3351
/* cpu creation */
3352
static QemuCond qemu_cpu_cond;
3353
/* system init */
3354
static QemuCond qemu_system_cond;
3355
static QemuCond qemu_pause_cond;
3356

    
3357
static void block_io_signals(void);
3358
static void unblock_io_signals(void);
3359
static int tcg_has_work(void);
3360

    
3361
static int qemu_init_main_loop(void)
3362
{
3363
    int ret;
3364

    
3365
    ret = qemu_event_init();
3366
    if (ret)
3367
        return ret;
3368

    
3369
    qemu_cond_init(&qemu_pause_cond);
3370
    qemu_mutex_init(&qemu_fair_mutex);
3371
    qemu_mutex_init(&qemu_global_mutex);
3372
    qemu_mutex_lock(&qemu_global_mutex);
3373

    
3374
    unblock_io_signals();
3375
    qemu_thread_self(&io_thread);
3376

    
3377
    return 0;
3378
}
3379

    
3380
static void qemu_wait_io_event(CPUState *env)
3381
{
3382
    while (!tcg_has_work())
3383
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3384

    
3385
    qemu_mutex_unlock(&qemu_global_mutex);
3386

    
3387
    /*
3388
     * Users of qemu_global_mutex can be starved, having no chance
3389
     * to acquire it since this path will get to it first.
3390
     * So use another lock to provide fairness.
3391
     */
3392
    qemu_mutex_lock(&qemu_fair_mutex);
3393
    qemu_mutex_unlock(&qemu_fair_mutex);
3394

    
3395
    qemu_mutex_lock(&qemu_global_mutex);
3396
    if (env->stop) {
3397
        env->stop = 0;
3398
        env->stopped = 1;
3399
        qemu_cond_signal(&qemu_pause_cond);
3400
    }
3401
}
3402

    
3403
static int qemu_cpu_exec(CPUState *env);
3404

    
3405
static void *kvm_cpu_thread_fn(void *arg)
3406
{
3407
    CPUState *env = arg;
3408

    
3409
    block_io_signals();
3410
    qemu_thread_self(env->thread);
3411
    if (kvm_enabled())
3412
        kvm_init_vcpu(env);
3413

    
3414
    /* signal CPU creation */
3415
    qemu_mutex_lock(&qemu_global_mutex);
3416
    env->created = 1;
3417
    qemu_cond_signal(&qemu_cpu_cond);
3418

    
3419
    /* and wait for machine initialization */
3420
    while (!qemu_system_ready)
3421
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3422

    
3423
    while (1) {
3424
        if (cpu_can_run(env))
3425
            qemu_cpu_exec(env);
3426
        qemu_wait_io_event(env);
3427
    }
3428

    
3429
    return NULL;
3430
}
3431

    
3432
static void tcg_cpu_exec(void);
3433

    
3434
static void *tcg_cpu_thread_fn(void *arg)
3435
{
3436
    CPUState *env = arg;
3437

    
3438
    block_io_signals();
3439
    qemu_thread_self(env->thread);
3440

    
3441
    /* signal CPU creation */
3442
    qemu_mutex_lock(&qemu_global_mutex);
3443
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3444
        env->created = 1;
3445
    qemu_cond_signal(&qemu_cpu_cond);
3446

    
3447
    /* and wait for machine initialization */
3448
    while (!qemu_system_ready)
3449
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3450

    
3451
    while (1) {
3452
        tcg_cpu_exec();
3453
        qemu_wait_io_event(cur_cpu);
3454
    }
3455

    
3456
    return NULL;
3457
}
3458

    
3459
void qemu_cpu_kick(void *_env)
3460
{
3461
    CPUState *env = _env;
3462
    qemu_cond_broadcast(env->halt_cond);
3463
    if (kvm_enabled())
3464
        qemu_thread_signal(env->thread, SIGUSR1);
3465
}
3466

    
3467
int qemu_cpu_self(void *_env)
3468
{
3469
    CPUState *env = _env;
3470
    QemuThread this;
3471
 
3472
    qemu_thread_self(&this);
3473
 
3474
    return qemu_thread_equal(&this, env->thread);
3475
}
3476

    
3477
static void cpu_signal(int sig)
3478
{
3479
    if (cpu_single_env)
3480
        cpu_exit(cpu_single_env);
3481
}
3482

    
3483
static void block_io_signals(void)
3484
{
3485
    sigset_t set;
3486
    struct sigaction sigact;
3487

    
3488
    sigemptyset(&set);
3489
    sigaddset(&set, SIGUSR2);
3490
    sigaddset(&set, SIGIO);
3491
    sigaddset(&set, SIGALRM);
3492
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3493

    
3494
    sigemptyset(&set);
3495
    sigaddset(&set, SIGUSR1);
3496
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3497

    
3498
    memset(&sigact, 0, sizeof(sigact));
3499
    sigact.sa_handler = cpu_signal;
3500
    sigaction(SIGUSR1, &sigact, NULL);
3501
}
3502

    
3503
static void unblock_io_signals(void)
3504
{
3505
    sigset_t set;
3506

    
3507
    sigemptyset(&set);
3508
    sigaddset(&set, SIGUSR2);
3509
    sigaddset(&set, SIGIO);
3510
    sigaddset(&set, SIGALRM);
3511
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3512

    
3513
    sigemptyset(&set);
3514
    sigaddset(&set, SIGUSR1);
3515
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3516
}
3517

    
3518
static void qemu_signal_lock(unsigned int msecs)
3519
{
3520
    qemu_mutex_lock(&qemu_fair_mutex);
3521

    
3522
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3523
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3524
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3525
            break;
3526
    }
3527
    qemu_mutex_unlock(&qemu_fair_mutex);
3528
}
3529

    
3530
void qemu_mutex_lock_iothread(void)
3531
{
3532
    if (kvm_enabled()) {
3533
        qemu_mutex_lock(&qemu_fair_mutex);
3534
        qemu_mutex_lock(&qemu_global_mutex);
3535
        qemu_mutex_unlock(&qemu_fair_mutex);
3536
    } else
3537
        qemu_signal_lock(100);
3538
}
3539

    
3540
void qemu_mutex_unlock_iothread(void)
3541
{
3542
    qemu_mutex_unlock(&qemu_global_mutex);
3543
}
3544

    
3545
static int all_vcpus_paused(void)
3546
{
3547
    CPUState *penv = first_cpu;
3548

    
3549
    while (penv) {
3550
        if (!penv->stopped)
3551
            return 0;
3552
        penv = (CPUState *)penv->next_cpu;
3553
    }
3554

    
3555
    return 1;
3556
}
3557

    
3558
static void pause_all_vcpus(void)
3559
{
3560
    CPUState *penv = first_cpu;
3561

    
3562
    while (penv) {
3563
        penv->stop = 1;
3564
        qemu_thread_signal(penv->thread, SIGUSR1);
3565
        qemu_cpu_kick(penv);
3566
        penv = (CPUState *)penv->next_cpu;
3567
    }
3568

    
3569
    while (!all_vcpus_paused()) {
3570
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3571
        penv = first_cpu;
3572
        while (penv) {
3573
            qemu_thread_signal(penv->thread, SIGUSR1);
3574
            penv = (CPUState *)penv->next_cpu;
3575
        }
3576
    }
3577
}
3578

    
3579
static void resume_all_vcpus(void)
3580
{
3581
    CPUState *penv = first_cpu;
3582

    
3583
    while (penv) {
3584
        penv->stop = 0;
3585
        penv->stopped = 0;
3586
        qemu_thread_signal(penv->thread, SIGUSR1);
3587
        qemu_cpu_kick(penv);
3588
        penv = (CPUState *)penv->next_cpu;
3589
    }
3590
}
3591

    
3592
static void tcg_init_vcpu(void *_env)
3593
{
3594
    CPUState *env = _env;
3595
    /* share a single thread for all cpus with TCG */
3596
    if (!tcg_cpu_thread) {
3597
        env->thread = qemu_mallocz(sizeof(QemuThread));
3598
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3599
        qemu_cond_init(env->halt_cond);
3600
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3601
        while (env->created == 0)
3602
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3603
        tcg_cpu_thread = env->thread;
3604
        tcg_halt_cond = env->halt_cond;
3605
    } else {
3606
        env->thread = tcg_cpu_thread;
3607
        env->halt_cond = tcg_halt_cond;
3608
    }
3609
}
3610

    
3611
static void kvm_start_vcpu(CPUState *env)
3612
{
3613
    env->thread = qemu_mallocz(sizeof(QemuThread));
3614
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3615
    qemu_cond_init(env->halt_cond);
3616
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3617
    while (env->created == 0)
3618
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3619
}
3620

    
3621
void qemu_init_vcpu(void *_env)
3622
{
3623
    CPUState *env = _env;
3624

    
3625
    env->nr_cores = smp_cores;
3626
    env->nr_threads = smp_threads;
3627
    if (kvm_enabled())
3628
        kvm_start_vcpu(env);
3629
    else
3630
        tcg_init_vcpu(env);
3631
}
3632

    
3633
void qemu_notify_event(void)
3634
{
3635
    qemu_event_increment();
3636
}
3637

    
3638
void vm_stop(int reason)
3639
{
3640
    QemuThread me;
3641
    qemu_thread_self(&me);
3642

    
3643
    if (!qemu_thread_equal(&me, &io_thread)) {
3644
        qemu_system_vmstop_request(reason);
3645
        /*
3646
         * FIXME: should not return to device code in case
3647
         * vm_stop() has been requested.
3648
         */
3649
        if (cpu_single_env) {
3650
            cpu_exit(cpu_single_env);
3651
            cpu_single_env->stop = 1;
3652
        }
3653
        return;
3654
    }
3655
    do_vm_stop(reason);
3656
}
3657

    
3658
#endif
3659

    
3660

    
3661
#ifdef _WIN32
3662
static void host_main_loop_wait(int *timeout)
3663
{
3664
    int ret, ret2, i;
3665
    PollingEntry *pe;
3666

    
3667

    
3668
    /* XXX: need to suppress polling by better using win32 events */
3669
    ret = 0;
3670
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3671
        ret |= pe->func(pe->opaque);
3672
    }
3673
    if (ret == 0) {
3674
        int err;
3675
        WaitObjects *w = &wait_objects;
3676

    
3677
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3678
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3679
            if (w->func[ret - WAIT_OBJECT_0])
3680
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3681

    
3682
            /* Check for additional signaled events */
3683
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3684

    
3685
                /* Check if event is signaled */
3686
                ret2 = WaitForSingleObject(w->events[i], 0);
3687
                if(ret2 == WAIT_OBJECT_0) {
3688
                    if (w->func[i])
3689
                        w->func[i](w->opaque[i]);
3690
                } else if (ret2 == WAIT_TIMEOUT) {
3691
                } else {
3692
                    err = GetLastError();
3693
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3694
                }
3695
            }
3696
        } else if (ret == WAIT_TIMEOUT) {
3697
        } else {
3698
            err = GetLastError();
3699
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3700
        }
3701
    }
3702

    
3703
    *timeout = 0;
3704
}
3705
#else
3706
static void host_main_loop_wait(int *timeout)
3707
{
3708
}
3709
#endif
3710

    
3711
void main_loop_wait(int timeout)
3712
{
3713
    IOHandlerRecord *ioh;
3714
    fd_set rfds, wfds, xfds;
3715
    int ret, nfds;
3716
    struct timeval tv;
3717

    
3718
    qemu_bh_update_timeout(&timeout);
3719

    
3720
    host_main_loop_wait(&timeout);
3721

    
3722
    /* poll any events */
3723
    /* XXX: separate device handlers from system ones */
3724
    nfds = -1;
3725
    FD_ZERO(&rfds);
3726
    FD_ZERO(&wfds);
3727
    FD_ZERO(&xfds);
3728
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3729
        if (ioh->deleted)
3730
            continue;
3731
        if (ioh->fd_read &&
3732
            (!ioh->fd_read_poll ||
3733
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3734
            FD_SET(ioh->fd, &rfds);
3735
            if (ioh->fd > nfds)
3736
                nfds = ioh->fd;
3737
        }
3738
        if (ioh->fd_write) {
3739
            FD_SET(ioh->fd, &wfds);
3740
            if (ioh->fd > nfds)
3741
                nfds = ioh->fd;
3742
        }
3743
    }
3744

    
3745
    tv.tv_sec = timeout / 1000;
3746
    tv.tv_usec = (timeout % 1000) * 1000;
3747

    
3748
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3749

    
3750
    qemu_mutex_unlock_iothread();
3751
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3752
    qemu_mutex_lock_iothread();
3753
    if (ret > 0) {
3754
        IOHandlerRecord **pioh;
3755

    
3756
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3757
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3758
                ioh->fd_read(ioh->opaque);
3759
            }
3760
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3761
                ioh->fd_write(ioh->opaque);
3762
            }
3763
        }
3764

    
3765
        /* remove deleted IO handlers */
3766
        pioh = &first_io_handler;
3767
        while (*pioh) {
3768
            ioh = *pioh;
3769
            if (ioh->deleted) {
3770
                *pioh = ioh->next;
3771
                qemu_free(ioh);
3772
            } else
3773
                pioh = &ioh->next;
3774
        }
3775
    }
3776

    
3777
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3778

    
3779
    /* rearm timer, if not periodic */
3780
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3781
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3782
        qemu_rearm_alarm_timer(alarm_timer);
3783
    }
3784

    
3785
    /* vm time timers */
3786
    if (vm_running) {
3787
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3788
            qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3789
                            qemu_get_clock(vm_clock));
3790
    }
3791

    
3792
    /* real time timers */
3793
    qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3794
                    qemu_get_clock(rt_clock));
3795

    
3796
    qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3797
                    qemu_get_clock(host_clock));
3798

    
3799
    /* Check bottom-halves last in case any of the earlier events triggered
3800
       them.  */
3801
    qemu_bh_poll();
3802

    
3803
}
3804

    
3805
static int qemu_cpu_exec(CPUState *env)
3806
{
3807
    int ret;
3808
#ifdef CONFIG_PROFILER
3809
    int64_t ti;
3810
#endif
3811

    
3812
#ifdef CONFIG_PROFILER
3813
    ti = profile_getclock();
3814
#endif
3815
    if (use_icount) {
3816
        int64_t count;
3817
        int decr;
3818
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3819
        env->icount_decr.u16.low = 0;
3820
        env->icount_extra = 0;
3821
        count = qemu_next_deadline();
3822
        count = (count + (1 << icount_time_shift) - 1)
3823
                >> icount_time_shift;
3824
        qemu_icount += count;
3825
        decr = (count > 0xffff) ? 0xffff : count;
3826
        count -= decr;
3827
        env->icount_decr.u16.low = decr;
3828
        env->icount_extra = count;
3829
    }
3830
    ret = cpu_exec(env);
3831
#ifdef CONFIG_PROFILER
3832
    qemu_time += profile_getclock() - ti;
3833
#endif
3834
    if (use_icount) {
3835
        /* Fold pending instructions back into the
3836
           instruction counter, and clear the interrupt flag.  */
3837
        qemu_icount -= (env->icount_decr.u16.low
3838
                        + env->icount_extra);
3839
        env->icount_decr.u32 = 0;
3840
        env->icount_extra = 0;
3841
    }
3842
    return ret;
3843
}
3844

    
3845
static void tcg_cpu_exec(void)
3846
{
3847
    int ret = 0;
3848

    
3849
    if (next_cpu == NULL)
3850
        next_cpu = first_cpu;
3851
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3852
        CPUState *env = cur_cpu = next_cpu;
3853

    
3854
        if (!vm_running)
3855
            break;
3856
        if (timer_alarm_pending) {
3857
            timer_alarm_pending = 0;
3858
            break;
3859
        }
3860
        if (cpu_can_run(env))
3861
            ret = qemu_cpu_exec(env);
3862
        if (ret == EXCP_DEBUG) {
3863
            gdb_set_stop_cpu(env);
3864
            debug_requested = 1;
3865
            break;
3866
        }
3867
    }
3868
}
3869

    
3870
static int cpu_has_work(CPUState *env)
3871
{
3872
    if (env->stop)
3873
        return 1;
3874
    if (env->stopped)
3875
        return 0;
3876
    if (!env->halted)
3877
        return 1;
3878
    if (qemu_cpu_has_work(env))
3879
        return 1;
3880
    return 0;
3881
}
3882

    
3883
static int tcg_has_work(void)
3884
{
3885
    CPUState *env;
3886

    
3887
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3888
        if (cpu_has_work(env))
3889
            return 1;
3890
    return 0;
3891
}
3892

    
3893
static int qemu_calculate_timeout(void)
3894
{
3895
#ifndef CONFIG_IOTHREAD
3896
    int timeout;
3897

    
3898
    if (!vm_running)
3899
        timeout = 5000;
3900
    else if (tcg_has_work())
3901
        timeout = 0;
3902
    else if (!use_icount)
3903
        timeout = 5000;
3904
    else {
3905
     /* XXX: use timeout computed from timers */
3906
        int64_t add;
3907
        int64_t delta;
3908
        /* Advance virtual time to the next event.  */
3909
        if (use_icount == 1) {
3910
            /* When not using an adaptive execution frequency
3911
               we tend to get badly out of sync with real time,
3912
               so just delay for a reasonable amount of time.  */
3913
            delta = 0;
3914
        } else {
3915
            delta = cpu_get_icount() - cpu_get_clock();
3916
        }
3917
        if (delta > 0) {
3918
            /* If virtual time is ahead of real time then just
3919
               wait for IO.  */
3920
            timeout = (delta / 1000000) + 1;
3921
        } else {
3922
            /* Wait for either IO to occur or the next
3923
               timer event.  */
3924
            add = qemu_next_deadline();
3925
            /* We advance the timer before checking for IO.
3926
               Limit the amount we advance so that early IO
3927
               activity won't get the guest too far ahead.  */
3928
            if (add > 10000000)
3929
                add = 10000000;
3930
            delta += add;
3931
            add = (add + (1 << icount_time_shift) - 1)
3932
                  >> icount_time_shift;
3933
            qemu_icount += add;
3934
            timeout = delta / 1000000;
3935
            if (timeout < 0)
3936
                timeout = 0;
3937
        }
3938
    }
3939

    
3940
    return timeout;
3941
#else /* CONFIG_IOTHREAD */
3942
    return 1000;
3943
#endif
3944
}
3945

    
3946
static int vm_can_run(void)
3947
{
3948
    if (powerdown_requested)
3949
        return 0;
3950
    if (reset_requested)
3951
        return 0;
3952
    if (shutdown_requested)
3953
        return 0;
3954
    if (debug_requested)
3955
        return 0;
3956
    return 1;
3957
}
3958

    
3959
qemu_irq qemu_system_powerdown;
3960

    
3961
static void main_loop(void)
3962
{
3963
    int r;
3964

    
3965
#ifdef CONFIG_IOTHREAD
3966
    qemu_system_ready = 1;
3967
    qemu_cond_broadcast(&qemu_system_cond);
3968
#endif
3969

    
3970
    for (;;) {
3971
        do {
3972
#ifdef CONFIG_PROFILER
3973
            int64_t ti;
3974
#endif
3975
#ifndef CONFIG_IOTHREAD
3976
            tcg_cpu_exec();
3977
#endif
3978
#ifdef CONFIG_PROFILER
3979
            ti = profile_getclock();
3980
#endif
3981
            main_loop_wait(qemu_calculate_timeout());
3982
#ifdef CONFIG_PROFILER
3983
            dev_time += profile_getclock() - ti;
3984
#endif
3985
        } while (vm_can_run());
3986

    
3987
        if (qemu_debug_requested()) {
3988
            monitor_protocol_event(QEVENT_DEBUG, NULL);
3989
            vm_stop(EXCP_DEBUG);
3990
        }
3991
        if (qemu_shutdown_requested()) {
3992
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3993
            if (no_shutdown) {
3994
                vm_stop(0);
3995
                no_shutdown = 0;
3996
            } else
3997
                break;
3998
        }
3999
        if (qemu_reset_requested()) {
4000
            monitor_protocol_event(QEVENT_RESET, NULL);
4001
            pause_all_vcpus();
4002
            qemu_system_reset();
4003
            resume_all_vcpus();
4004
        }
4005
        if (qemu_powerdown_requested()) {
4006
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4007
            qemu_irq_raise(qemu_system_powerdown);
4008
        }
4009
        if ((r = qemu_vmstop_requested())) {
4010
            monitor_protocol_event(QEVENT_STOP, NULL);
4011
            vm_stop(r);
4012
        }
4013
    }
4014
    pause_all_vcpus();
4015
}
4016

    
4017
static void version(void)
4018
{
4019
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4020
}
4021

    
4022
static void help(int exitcode)
4023
{
4024
    const char *options_help =
4025
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4026
           opt_help
4027
#define DEFHEADING(text) stringify(text) "\n"
4028
#include "qemu-options.h"
4029
#undef DEF
4030
#undef DEFHEADING
4031
#undef GEN_DOCS
4032
        ;
4033
    version();
4034
    printf("usage: %s [options] [disk_image]\n"
4035
           "\n"
4036
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4037
           "\n"
4038
           "%s\n"
4039
           "During emulation, the following keys are useful:\n"
4040
           "ctrl-alt-f      toggle full screen\n"
4041
           "ctrl-alt-n      switch to virtual console 'n'\n"
4042
           "ctrl-alt        toggle mouse and keyboard grab\n"
4043
           "\n"
4044
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
4045
           "qemu",
4046
           options_help);
4047
    exit(exitcode);
4048
}
4049

    
4050
#define HAS_ARG 0x0001
4051

    
4052
enum {
4053
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4054
    opt_enum,
4055
#define DEFHEADING(text)
4056
#include "qemu-options.h"
4057
#undef DEF
4058
#undef DEFHEADING
4059
#undef GEN_DOCS
4060
};
4061

    
4062
typedef struct QEMUOption {
4063
    const char *name;
4064
    int flags;
4065
    int index;
4066
} QEMUOption;
4067

    
4068
static const QEMUOption qemu_options[] = {
4069
    { "h", 0, QEMU_OPTION_h },
4070
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4071
    { option, opt_arg, opt_enum },
4072
#define DEFHEADING(text)
4073
#include "qemu-options.h"
4074
#undef DEF
4075
#undef DEFHEADING
4076
#undef GEN_DOCS
4077
    { NULL },
4078
};
4079

    
4080
#ifdef HAS_AUDIO
4081
struct soundhw soundhw[] = {
4082
#ifdef HAS_AUDIO_CHOICE
4083
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4084
    {
4085
        "pcspk",
4086
        "PC speaker",
4087
        0,
4088
        1,
4089
        { .init_isa = pcspk_audio_init }
4090
    },
4091
#endif
4092

    
4093
#ifdef CONFIG_SB16
4094
    {
4095
        "sb16",
4096
        "Creative Sound Blaster 16",
4097
        0,
4098
        1,
4099
        { .init_isa = SB16_init }
4100
    },
4101
#endif
4102

    
4103
#ifdef CONFIG_CS4231A
4104
    {
4105
        "cs4231a",
4106
        "CS4231A",
4107
        0,
4108
        1,
4109
        { .init_isa = cs4231a_init }
4110
    },
4111
#endif
4112

    
4113
#ifdef CONFIG_ADLIB
4114
    {
4115
        "adlib",
4116
#ifdef HAS_YMF262
4117
        "Yamaha YMF262 (OPL3)",
4118
#else
4119
        "Yamaha YM3812 (OPL2)",
4120
#endif
4121
        0,
4122
        1,
4123
        { .init_isa = Adlib_init }
4124
    },
4125
#endif
4126

    
4127
#ifdef CONFIG_GUS
4128
    {
4129
        "gus",
4130
        "Gravis Ultrasound GF1",
4131
        0,
4132
        1,
4133
        { .init_isa = GUS_init }
4134
    },
4135
#endif
4136

    
4137
#ifdef CONFIG_AC97
4138
    {
4139
        "ac97",
4140
        "Intel 82801AA AC97 Audio",
4141
        0,
4142
        0,
4143
        { .init_pci = ac97_init }
4144
    },
4145
#endif
4146

    
4147
#ifdef CONFIG_ES1370
4148
    {
4149
        "es1370",
4150
        "ENSONIQ AudioPCI ES1370",
4151
        0,
4152
        0,
4153
        { .init_pci = es1370_init }
4154
    },
4155
#endif
4156

    
4157
#endif /* HAS_AUDIO_CHOICE */
4158

    
4159
    { NULL, NULL, 0, 0, { NULL } }
4160
};
4161

    
4162
static void select_soundhw (const char *optarg)
4163
{
4164
    struct soundhw *c;
4165

    
4166
    if (*optarg == '?') {
4167
    show_valid_cards:
4168

    
4169
        printf ("Valid sound card names (comma separated):\n");
4170
        for (c = soundhw; c->name; ++c) {
4171
            printf ("%-11s %s\n", c->name, c->descr);
4172
        }
4173
        printf ("\n-soundhw all will enable all of the above\n");
4174
        exit (*optarg != '?');
4175
    }
4176
    else {
4177
        size_t l;
4178
        const char *p;
4179
        char *e;
4180
        int bad_card = 0;
4181

    
4182
        if (!strcmp (optarg, "all")) {
4183
            for (c = soundhw; c->name; ++c) {
4184
                c->enabled = 1;
4185
            }
4186
            return;
4187
        }
4188

    
4189
        p = optarg;
4190
        while (*p) {
4191
            e = strchr (p, ',');
4192
            l = !e ? strlen (p) : (size_t) (e - p);
4193

    
4194
            for (c = soundhw; c->name; ++c) {
4195
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4196
                    c->enabled = 1;
4197
                    break;
4198
                }
4199
            }
4200

    
4201
            if (!c->name) {
4202
                if (l > 80) {
4203
                    fprintf (stderr,
4204
                             "Unknown sound card name (too big to show)\n");
4205
                }
4206
                else {
4207
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4208
                             (int) l, p);
4209
                }
4210
                bad_card = 1;
4211
            }
4212
            p += l + (e != NULL);
4213
        }
4214

    
4215
        if (bad_card)
4216
            goto show_valid_cards;
4217
    }
4218
}
4219
#endif
4220

    
4221
static void select_vgahw (const char *p)
4222
{
4223
    const char *opts;
4224

    
4225
    default_vga = 0;
4226
    vga_interface_type = VGA_NONE;
4227
    if (strstart(p, "std", &opts)) {
4228
        vga_interface_type = VGA_STD;
4229
    } else if (strstart(p, "cirrus", &opts)) {
4230
        vga_interface_type = VGA_CIRRUS;
4231
    } else if (strstart(p, "vmware", &opts)) {
4232
        vga_interface_type = VGA_VMWARE;
4233
    } else if (strstart(p, "xenfb", &opts)) {
4234
        vga_interface_type = VGA_XENFB;
4235
    } else if (!strstart(p, "none", &opts)) {
4236
    invalid_vga:
4237
        fprintf(stderr, "Unknown vga type: %s\n", p);
4238
        exit(1);
4239
    }
4240
    while (*opts) {
4241
        const char *nextopt;
4242

    
4243
        if (strstart(opts, ",retrace=", &nextopt)) {
4244
            opts = nextopt;
4245
            if (strstart(opts, "dumb", &nextopt))
4246
                vga_retrace_method = VGA_RETRACE_DUMB;
4247
            else if (strstart(opts, "precise", &nextopt))
4248
                vga_retrace_method = VGA_RETRACE_PRECISE;
4249
            else goto invalid_vga;
4250
        } else goto invalid_vga;
4251
        opts = nextopt;
4252
    }
4253
}
4254

    
4255
#ifdef TARGET_I386
4256
static int balloon_parse(const char *arg)
4257
{
4258
    QemuOpts *opts;
4259

    
4260
    if (strcmp(arg, "none") == 0) {
4261
        return 0;
4262
    }
4263

    
4264
    if (!strncmp(arg, "virtio", 6)) {
4265
        if (arg[6] == ',') {
4266
            /* have params -> parse them */
4267
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4268
            if (!opts)
4269
                return  -1;
4270
        } else {
4271
            /* create empty opts */
4272
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4273
        }
4274
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4275
        return 0;
4276
    }
4277

    
4278
    return -1;
4279
}
4280
#endif
4281

    
4282
#ifdef _WIN32
4283
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4284
{
4285
    exit(STATUS_CONTROL_C_EXIT);
4286
    return TRUE;
4287
}
4288
#endif
4289

    
4290
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4291
{
4292
    int ret;
4293

    
4294
    if(strlen(str) != 36)
4295
        return -1;
4296

    
4297
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4298
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4299
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4300

    
4301
    if(ret != 16)
4302
        return -1;
4303

    
4304
#ifdef TARGET_I386
4305
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4306
#endif
4307

    
4308
    return 0;
4309
}
4310

    
4311
#ifndef _WIN32
4312

    
4313
static void termsig_handler(int signal)
4314
{
4315
    qemu_system_shutdown_request();
4316
}
4317

    
4318
static void sigchld_handler(int signal)
4319
{
4320
    waitpid(-1, NULL, WNOHANG);
4321
}
4322

    
4323
static void sighandler_setup(void)
4324
{
4325
    struct sigaction act;
4326

    
4327
    memset(&act, 0, sizeof(act));
4328
    act.sa_handler = termsig_handler;
4329
    sigaction(SIGINT,  &act, NULL);
4330
    sigaction(SIGHUP,  &act, NULL);
4331
    sigaction(SIGTERM, &act, NULL);
4332

    
4333
    act.sa_handler = sigchld_handler;
4334
    act.sa_flags = SA_NOCLDSTOP;
4335
    sigaction(SIGCHLD, &act, NULL);
4336
}
4337

    
4338
#endif
4339

    
4340
#ifdef _WIN32
4341
/* Look for support files in the same directory as the executable.  */
4342
static char *find_datadir(const char *argv0)
4343
{
4344
    char *p;
4345
    char buf[MAX_PATH];
4346
    DWORD len;
4347

    
4348
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4349
    if (len == 0) {
4350
        return NULL;
4351
    }
4352

    
4353
    buf[len] = 0;
4354
    p = buf + len - 1;
4355
    while (p != buf && *p != '\\')
4356
        p--;
4357
    *p = 0;
4358
    if (access(buf, R_OK) == 0) {
4359
        return qemu_strdup(buf);
4360
    }
4361
    return NULL;
4362
}
4363
#else /* !_WIN32 */
4364

    
4365
/* Find a likely location for support files using the location of the binary.
4366
   For installed binaries this will be "$bindir/../share/qemu".  When
4367
   running from the build tree this will be "$bindir/../pc-bios".  */
4368
#define SHARE_SUFFIX "/share/qemu"
4369
#define BUILD_SUFFIX "/pc-bios"
4370
static char *find_datadir(const char *argv0)
4371
{
4372
    char *dir;
4373
    char *p = NULL;
4374
    char *res;
4375
    char buf[PATH_MAX];
4376
    size_t max_len;
4377

    
4378
#if defined(__linux__)
4379
    {
4380
        int len;
4381
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4382
        if (len > 0) {
4383
            buf[len] = 0;
4384
            p = buf;
4385
        }
4386
    }
4387
#elif defined(__FreeBSD__)
4388
    {
4389
        int len;
4390
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4391
        if (len > 0) {
4392
            buf[len] = 0;
4393
            p = buf;
4394
        }
4395
    }
4396
#endif
4397
    /* If we don't have any way of figuring out the actual executable
4398
       location then try argv[0].  */
4399
    if (!p) {
4400
        p = realpath(argv0, buf);
4401
        if (!p) {
4402
            return NULL;
4403
        }
4404
    }
4405
    dir = dirname(p);
4406
    dir = dirname(dir);
4407

    
4408
    max_len = strlen(dir) +
4409
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4410
    res = qemu_mallocz(max_len);
4411
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4412
    if (access(res, R_OK)) {
4413
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4414
        if (access(res, R_OK)) {
4415
            qemu_free(res);
4416
            res = NULL;
4417
        }
4418
    }
4419

    
4420
    return res;
4421
}
4422
#undef SHARE_SUFFIX
4423
#undef BUILD_SUFFIX
4424
#endif
4425

    
4426
char *qemu_find_file(int type, const char *name)
4427
{
4428
    int len;
4429
    const char *subdir;
4430
    char *buf;
4431

    
4432
    /* If name contains path separators then try it as a straight path.  */
4433
    if ((strchr(name, '/') || strchr(name, '\\'))
4434
        && access(name, R_OK) == 0) {
4435
        return qemu_strdup(name);
4436
    }
4437
    switch (type) {
4438
    case QEMU_FILE_TYPE_BIOS:
4439
        subdir = "";
4440
        break;
4441
    case QEMU_FILE_TYPE_KEYMAP:
4442
        subdir = "keymaps/";
4443
        break;
4444
    default:
4445
        abort();
4446
    }
4447
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4448
    buf = qemu_mallocz(len);
4449
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4450
    if (access(buf, R_OK)) {
4451
        qemu_free(buf);
4452
        return NULL;
4453
    }
4454
    return buf;
4455
}
4456

    
4457
static int device_help_func(QemuOpts *opts, void *opaque)
4458
{
4459
    return qdev_device_help(opts);
4460
}
4461

    
4462
static int device_init_func(QemuOpts *opts, void *opaque)
4463
{
4464
    DeviceState *dev;
4465

    
4466
    dev = qdev_device_add(opts);
4467
    if (!dev)
4468
        return -1;
4469
    return 0;
4470
}
4471

    
4472
static int chardev_init_func(QemuOpts *opts, void *opaque)
4473
{
4474
    CharDriverState *chr;
4475

    
4476
    chr = qemu_chr_open_opts(opts, NULL);
4477
    if (!chr)
4478
        return -1;
4479
    return 0;
4480
}
4481

    
4482
static int mon_init_func(QemuOpts *opts, void *opaque)
4483
{
4484
    CharDriverState *chr;
4485
    const char *chardev;
4486
    const char *mode;
4487
    int flags;
4488

    
4489
    mode = qemu_opt_get(opts, "mode");
4490
    if (mode == NULL) {
4491
        mode = "readline";
4492
    }
4493
    if (strcmp(mode, "readline") == 0) {
4494
        flags = MONITOR_USE_READLINE;
4495
    } else if (strcmp(mode, "control") == 0) {
4496
        flags = MONITOR_USE_CONTROL;
4497
    } else {
4498
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4499
        exit(1);
4500
    }
4501

    
4502
    if (qemu_opt_get_bool(opts, "default", 0))
4503
        flags |= MONITOR_IS_DEFAULT;
4504

    
4505
    chardev = qemu_opt_get(opts, "chardev");
4506
    chr = qemu_chr_find(chardev);
4507
    if (chr == NULL) {
4508
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4509
        exit(1);
4510
    }
4511

    
4512
    monitor_init(chr, flags);
4513
    return 0;
4514
}
4515

    
4516
static void monitor_parse(const char *optarg, const char *mode)
4517
{
4518
    static int monitor_device_index = 0;
4519
    QemuOpts *opts;
4520
    const char *p;
4521
    char label[32];
4522
    int def = 0;
4523

    
4524
    if (strstart(optarg, "chardev:", &p)) {
4525
        snprintf(label, sizeof(label), "%s", p);
4526
    } else {
4527
        if (monitor_device_index) {
4528
            snprintf(label, sizeof(label), "monitor%d",
4529
                     monitor_device_index);
4530
        } else {
4531
            snprintf(label, sizeof(label), "monitor");
4532
            def = 1;
4533
        }
4534
        opts = qemu_chr_parse_compat(label, optarg);
4535
        if (!opts) {
4536
            fprintf(stderr, "parse error: %s\n", optarg);
4537
            exit(1);
4538
        }
4539
    }
4540

    
4541
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4542
    if (!opts) {
4543
        fprintf(stderr, "duplicate chardev: %s\n", label);
4544
        exit(1);
4545
    }
4546
    qemu_opt_set(opts, "mode", mode);
4547
    qemu_opt_set(opts, "chardev", label);
4548
    if (def)
4549
        qemu_opt_set(opts, "default", "on");
4550
    monitor_device_index++;
4551
}
4552

    
4553
struct device_config {
4554
    enum {
4555
        DEV_USB,       /* -usbdevice     */
4556
        DEV_BT,        /* -bt            */
4557
        DEV_SERIAL,    /* -serial        */
4558
        DEV_PARALLEL,  /* -parallel      */
4559
        DEV_VIRTCON,   /* -virtioconsole */
4560
        DEV_DEBUGCON,  /* -debugcon */
4561
    } type;
4562
    const char *cmdline;
4563
    QTAILQ_ENTRY(device_config) next;
4564
};
4565
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4566

    
4567
static void add_device_config(int type, const char *cmdline)
4568
{
4569
    struct device_config *conf;
4570

    
4571
    conf = qemu_mallocz(sizeof(*conf));
4572
    conf->type = type;
4573
    conf->cmdline = cmdline;
4574
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4575
}
4576

    
4577
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4578
{
4579
    struct device_config *conf;
4580
    int rc;
4581

    
4582
    QTAILQ_FOREACH(conf, &device_configs, next) {
4583
        if (conf->type != type)
4584
            continue;
4585
        rc = func(conf->cmdline);
4586
        if (0 != rc)
4587
            return rc;
4588
    }
4589
    return 0;
4590
}
4591

    
4592
static int serial_parse(const char *devname)
4593
{
4594
    static int index = 0;
4595
    char label[32];
4596

    
4597
    if (strcmp(devname, "none") == 0)
4598
        return 0;
4599
    if (index == MAX_SERIAL_PORTS) {
4600
        fprintf(stderr, "qemu: too many serial ports\n");
4601
        exit(1);
4602
    }
4603
    snprintf(label, sizeof(label), "serial%d", index);
4604
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
4605
    if (!serial_hds[index]) {
4606
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4607
                devname, strerror(errno));
4608
        return -1;
4609
    }
4610
    index++;
4611
    return 0;
4612
}
4613

    
4614
static int parallel_parse(const char *devname)
4615
{
4616
    static int index = 0;
4617
    char label[32];
4618

    
4619
    if (strcmp(devname, "none") == 0)
4620
        return 0;
4621
    if (index == MAX_PARALLEL_PORTS) {
4622
        fprintf(stderr, "qemu: too many parallel ports\n");
4623
        exit(1);
4624
    }
4625
    snprintf(label, sizeof(label), "parallel%d", index);
4626
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4627
    if (!parallel_hds[index]) {
4628
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4629
                devname, strerror(errno));
4630
        return -1;
4631
    }
4632
    index++;
4633
    return 0;
4634
}
4635

    
4636
static int virtcon_parse(const char *devname)
4637
{
4638
    static int index = 0;
4639
    char label[32];
4640
    QemuOpts *bus_opts, *dev_opts;
4641

    
4642
    if (strcmp(devname, "none") == 0)
4643
        return 0;
4644
    if (index == MAX_VIRTIO_CONSOLES) {
4645
        fprintf(stderr, "qemu: too many virtio consoles\n");
4646
        exit(1);
4647
    }
4648

    
4649
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4650
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4651

    
4652
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4653
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4654

    
4655
    snprintf(label, sizeof(label), "virtcon%d", index);
4656
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4657
    if (!virtcon_hds[index]) {
4658
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4659
                devname, strerror(errno));
4660
        return -1;
4661
    }
4662
    qemu_opt_set(dev_opts, "chardev", label);
4663

    
4664
    index++;
4665
    return 0;
4666
}
4667

    
4668
static int debugcon_parse(const char *devname)
4669
{   
4670
    QemuOpts *opts;
4671

    
4672
    if (!qemu_chr_open("debugcon", devname, NULL)) {
4673
        exit(1);
4674
    }
4675
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4676
    if (!opts) {
4677
        fprintf(stderr, "qemu: already have a debugcon device\n");
4678
        exit(1);
4679
    }
4680
    qemu_opt_set(opts, "driver", "isa-debugcon");
4681
    qemu_opt_set(opts, "chardev", "debugcon");
4682
    return 0;
4683
}
4684

    
4685
static const QEMUOption *lookup_opt(int argc, char **argv,
4686
                                    const char **poptarg, int *poptind)
4687
{
4688
    const QEMUOption *popt;
4689
    int optind = *poptind;
4690
    char *r = argv[optind];
4691
    const char *optarg;
4692

    
4693
    optind++;
4694
    /* Treat --foo the same as -foo.  */
4695
    if (r[1] == '-')
4696
        r++;
4697
    popt = qemu_options;
4698
    for(;;) {
4699
        if (!popt->name) {
4700
            fprintf(stderr, "%s: invalid option -- '%s'\n",
4701
                    argv[0], r);
4702
            exit(1);
4703
        }
4704
        if (!strcmp(popt->name, r + 1))
4705
            break;
4706
        popt++;
4707
    }
4708
    if (popt->flags & HAS_ARG) {
4709
        if (optind >= argc) {
4710
            fprintf(stderr, "%s: option '%s' requires an argument\n",
4711
                    argv[0], r);
4712
            exit(1);
4713
        }
4714
        optarg = argv[optind++];
4715
    } else {
4716
        optarg = NULL;
4717
    }
4718

    
4719
    *poptarg = optarg;
4720
    *poptind = optind;
4721

    
4722
    return popt;
4723
}
4724

    
4725
int main(int argc, char **argv, char **envp)
4726
{
4727
    const char *gdbstub_dev = NULL;
4728
    uint32_t boot_devices_bitmap = 0;
4729
    int i;
4730
    int snapshot, linux_boot, net_boot;
4731
    const char *initrd_filename;
4732
    const char *kernel_filename, *kernel_cmdline;
4733
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4734
    DisplayState *ds;
4735
    DisplayChangeListener *dcl;
4736
    int cyls, heads, secs, translation;
4737
    QemuOpts *hda_opts = NULL, *opts;
4738
    int optind;
4739
    const char *optarg;
4740
    const char *loadvm = NULL;
4741
    QEMUMachine *machine;
4742
    const char *cpu_model;
4743
#ifndef _WIN32
4744
    int fds[2];
4745
#endif
4746
    int tb_size;
4747
    const char *pid_file = NULL;
4748
    const char *incoming = NULL;
4749
#ifndef _WIN32
4750
    int fd = 0;
4751
    struct passwd *pwd = NULL;
4752
    const char *chroot_dir = NULL;
4753
    const char *run_as = NULL;
4754
#endif
4755
    CPUState *env;
4756
    int show_vnc_port = 0;
4757
    int defconfig = 1;
4758

    
4759
    init_clocks();
4760

    
4761
    qemu_errors_to_file(stderr);
4762
    qemu_cache_utils_init(envp);
4763

    
4764
    QLIST_INIT (&vm_change_state_head);
4765
#ifndef _WIN32
4766
    {
4767
        struct sigaction act;
4768
        sigfillset(&act.sa_mask);
4769
        act.sa_flags = 0;
4770
        act.sa_handler = SIG_IGN;
4771
        sigaction(SIGPIPE, &act, NULL);
4772
    }
4773
#else
4774
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4775
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4776
       QEMU to run on a single CPU */
4777
    {
4778
        HANDLE h;
4779
        DWORD mask, smask;
4780
        int i;
4781
        h = GetCurrentProcess();
4782
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4783
            for(i = 0; i < 32; i++) {
4784
                if (mask & (1 << i))
4785
                    break;
4786
            }
4787
            if (i != 32) {
4788
                mask = 1 << i;
4789
                SetProcessAffinityMask(h, mask);
4790
            }
4791
        }
4792
    }
4793
#endif
4794

    
4795
    module_call_init(MODULE_INIT_MACHINE);
4796
    machine = find_default_machine();
4797
    cpu_model = NULL;
4798
    initrd_filename = NULL;
4799
    ram_size = 0;
4800
    snapshot = 0;
4801
    kernel_filename = NULL;
4802
    kernel_cmdline = "";
4803
    cyls = heads = secs = 0;
4804
    translation = BIOS_ATA_TRANSLATION_AUTO;
4805

    
4806
    for (i = 0; i < MAX_NODES; i++) {
4807
        node_mem[i] = 0;
4808
        node_cpumask[i] = 0;
4809
    }
4810

    
4811
    nb_numa_nodes = 0;
4812
    nb_nics = 0;
4813

    
4814
    tb_size = 0;
4815
    autostart= 1;
4816

    
4817
    /* first pass of option parsing */
4818
    optind = 1;
4819
    while (optind < argc) {
4820
        if (argv[optind][0] != '-') {
4821
            /* disk image */
4822
            optind++;
4823
            continue;
4824
        } else {
4825
            const QEMUOption *popt;
4826

    
4827
            popt = lookup_opt(argc, argv, &optarg, &optind);
4828
            switch (popt->index) {
4829
            case QEMU_OPTION_nodefconfig:
4830
                defconfig=0;
4831
                break;
4832
            }
4833
        }
4834
    }
4835

    
4836
    if (defconfig) {
4837
        FILE *fp;
4838
        fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4839
        if (fp) {
4840
            if (qemu_config_parse(fp) != 0) {
4841
                exit(1);
4842
            }
4843
            fclose(fp);
4844
        }
4845

    
4846
        fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4847
        if (fp) {
4848
            if (qemu_config_parse(fp) != 0) {
4849
                exit(1);
4850
            }
4851
            fclose(fp);
4852
        }
4853
    }
4854

    
4855
    /* second pass of option parsing */
4856
    optind = 1;
4857
    for(;;) {
4858
        if (optind >= argc)
4859
            break;
4860
        if (argv[optind][0] != '-') {
4861
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4862
        } else {
4863
            const QEMUOption *popt;
4864

    
4865
            popt = lookup_opt(argc, argv, &optarg, &optind);
4866
            switch(popt->index) {
4867
            case QEMU_OPTION_M:
4868
                machine = find_machine(optarg);
4869
                if (!machine) {
4870
                    QEMUMachine *m;
4871
                    printf("Supported machines are:\n");
4872
                    for(m = first_machine; m != NULL; m = m->next) {
4873
                        if (m->alias)
4874
                            printf("%-10s %s (alias of %s)\n",
4875
                                   m->alias, m->desc, m->name);
4876
                        printf("%-10s %s%s\n",
4877
                               m->name, m->desc,
4878
                               m->is_default ? " (default)" : "");
4879
                    }
4880
                    exit(*optarg != '?');
4881
                }
4882
                break;
4883
            case QEMU_OPTION_cpu:
4884
                /* hw initialization will check this */
4885
                if (*optarg == '?') {
4886
/* XXX: implement xxx_cpu_list for targets that still miss it */
4887
#if defined(cpu_list)
4888
                    cpu_list(stdout, &fprintf);
4889
#endif
4890
                    exit(0);
4891
                } else {
4892
                    cpu_model = optarg;
4893
                }
4894
                break;
4895
            case QEMU_OPTION_initrd:
4896
                initrd_filename = optarg;
4897
                break;
4898
            case QEMU_OPTION_hda:
4899
                if (cyls == 0)
4900
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
4901
                else
4902
                    hda_opts = drive_add(optarg, HD_ALIAS
4903
                             ",cyls=%d,heads=%d,secs=%d%s",
4904
                             0, cyls, heads, secs,
4905
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4906
                                 ",trans=lba" :
4907
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4908
                                 ",trans=none" : "");
4909
                 break;
4910
            case QEMU_OPTION_hdb:
4911
            case QEMU_OPTION_hdc:
4912
            case QEMU_OPTION_hdd:
4913
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4914
                break;
4915
            case QEMU_OPTION_drive:
4916
                drive_add(NULL, "%s", optarg);
4917
                break;
4918
            case QEMU_OPTION_set:
4919
                if (qemu_set_option(optarg) != 0)
4920
                    exit(1);
4921
                break;
4922
            case QEMU_OPTION_global:
4923
                if (qemu_global_option(optarg) != 0)
4924
                    exit(1);
4925
                break;
4926
            case QEMU_OPTION_mtdblock:
4927
                drive_add(optarg, MTD_ALIAS);
4928
                break;
4929
            case QEMU_OPTION_sd:
4930
                drive_add(optarg, SD_ALIAS);
4931
                break;
4932
            case QEMU_OPTION_pflash:
4933
                drive_add(optarg, PFLASH_ALIAS);
4934
                break;
4935
            case QEMU_OPTION_snapshot:
4936
                snapshot = 1;
4937
                break;
4938
            case QEMU_OPTION_hdachs:
4939
                {
4940
                    const char *p;
4941
                    p = optarg;
4942
                    cyls = strtol(p, (char **)&p, 0);
4943
                    if (cyls < 1 || cyls > 16383)
4944
                        goto chs_fail;
4945
                    if (*p != ',')
4946
                        goto chs_fail;
4947
                    p++;
4948
                    heads = strtol(p, (char **)&p, 0);
4949
                    if (heads < 1 || heads > 16)
4950
                        goto chs_fail;
4951