Statistics
| Branch: | Revision:

root / vl.c @ cc84de95

History | View | Annotate | Download (156.8 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
#ifdef SIGRTMIN
275
#define SIG_IPI (SIGRTMIN+4)
276
#else
277
#define SIG_IPI SIGUSR1
278
#endif
279

    
280
static int default_serial = 1;
281
static int default_parallel = 1;
282
static int default_virtcon = 1;
283
static int default_monitor = 1;
284
static int default_vga = 1;
285
static int default_floppy = 1;
286
static int default_cdrom = 1;
287
static int default_sdcard = 1;
288

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

    
305
static int default_driver_check(QemuOpts *opts, void *opaque)
306
{
307
    const char *driver = qemu_opt_get(opts, "driver");
308
    int i;
309

    
310
    if (!driver)
311
        return 0;
312
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
313
        if (strcmp(default_list[i].driver, driver) != 0)
314
            continue;
315
        *(default_list[i].flag) = 0;
316
    }
317
    return 0;
318
}
319

    
320
/***********************************************************/
321
/* x86 ISA bus support */
322

    
323
target_phys_addr_t isa_mem_base = 0;
324
PicState2 *isa_pic;
325

    
326
/***********************************************************/
327
void hw_error(const char *fmt, ...)
328
{
329
    va_list ap;
330
    CPUState *env;
331

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

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

    
365
static QEMUBalloonEvent *qemu_balloon_event;
366
void *qemu_balloon_event_opaque;
367

    
368
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
369
{
370
    qemu_balloon_event = func;
371
    qemu_balloon_event_opaque = opaque;
372
}
373

    
374
int qemu_balloon(ram_addr_t target, MonitorCompletion cb, void *opaque)
375
{
376
    if (qemu_balloon_event) {
377
        qemu_balloon_event(qemu_balloon_event_opaque, target, cb, opaque);
378
        return 1;
379
    } else {
380
        return 0;
381
    }
382
}
383

    
384
int qemu_balloon_status(MonitorCompletion cb, void *opaque)
385
{
386
    if (qemu_balloon_event) {
387
        qemu_balloon_event(qemu_balloon_event_opaque, 0, cb, opaque);
388
        return 1;
389
    } else {
390
        return 0;
391
    }
392
}
393

    
394

    
395
/***********************************************************/
396
/* real time host monotonic timer */
397

    
398
/* compute with 96 bit intermediate result: (a*b)/c */
399
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
400
{
401
    union {
402
        uint64_t ll;
403
        struct {
404
#ifdef HOST_WORDS_BIGENDIAN
405
            uint32_t high, low;
406
#else
407
            uint32_t low, high;
408
#endif
409
        } l;
410
    } u, res;
411
    uint64_t rl, rh;
412

    
413
    u.ll = a;
414
    rl = (uint64_t)u.l.low * (uint64_t)b;
415
    rh = (uint64_t)u.l.high * (uint64_t)b;
416
    rh += (rl >> 32);
417
    res.l.high = rh / c;
418
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
419
    return res.ll;
420
}
421

    
422
static int64_t get_clock_realtime(void)
423
{
424
    struct timeval tv;
425

    
426
    gettimeofday(&tv, NULL);
427
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
428
}
429

    
430
#ifdef WIN32
431

    
432
static int64_t clock_freq;
433

    
434
static void init_get_clock(void)
435
{
436
    LARGE_INTEGER freq;
437
    int ret;
438
    ret = QueryPerformanceFrequency(&freq);
439
    if (ret == 0) {
440
        fprintf(stderr, "Could not calibrate ticks\n");
441
        exit(1);
442
    }
443
    clock_freq = freq.QuadPart;
444
}
445

    
446
static int64_t get_clock(void)
447
{
448
    LARGE_INTEGER ti;
449
    QueryPerformanceCounter(&ti);
450
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
451
}
452

    
453
#else
454

    
455
static int use_rt_clock;
456

    
457
static void init_get_clock(void)
458
{
459
    use_rt_clock = 0;
460
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
461
    || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
462
    {
463
        struct timespec ts;
464
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
465
            use_rt_clock = 1;
466
        }
467
    }
468
#endif
469
}
470

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

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

    
503
/***********************************************************/
504
/* guest cycle counter */
505

    
506
typedef struct TimersState {
507
    int64_t cpu_ticks_prev;
508
    int64_t cpu_ticks_offset;
509
    int64_t cpu_clock_offset;
510
    int32_t cpu_ticks_enabled;
511
    int64_t dummy;
512
} TimersState;
513

    
514
TimersState timers_state;
515

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

    
537
/* return the host CPU monotonic timer and handle stop/restart */
538
static int64_t cpu_get_clock(void)
539
{
540
    int64_t ti;
541
    if (!timers_state.cpu_ticks_enabled) {
542
        return timers_state.cpu_clock_offset;
543
    } else {
544
        ti = get_clock();
545
        return ti + timers_state.cpu_clock_offset;
546
    }
547
}
548

    
549
/* enable cpu_get_ticks() */
550
void cpu_enable_ticks(void)
551
{
552
    if (!timers_state.cpu_ticks_enabled) {
553
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
554
        timers_state.cpu_clock_offset -= get_clock();
555
        timers_state.cpu_ticks_enabled = 1;
556
    }
557
}
558

    
559
/* disable cpu_get_ticks() : the clock is stopped. You must not call
560
   cpu_get_ticks() after that.  */
561
void cpu_disable_ticks(void)
562
{
563
    if (timers_state.cpu_ticks_enabled) {
564
        timers_state.cpu_ticks_offset = cpu_get_ticks();
565
        timers_state.cpu_clock_offset = cpu_get_clock();
566
        timers_state.cpu_ticks_enabled = 0;
567
    }
568
}
569

    
570
/***********************************************************/
571
/* timers */
572

    
573
#define QEMU_CLOCK_REALTIME 0
574
#define QEMU_CLOCK_VIRTUAL  1
575
#define QEMU_CLOCK_HOST     2
576

    
577
struct QEMUClock {
578
    int type;
579
    /* XXX: add frequency */
580
};
581

    
582
struct QEMUTimer {
583
    QEMUClock *clock;
584
    int64_t expire_time;
585
    QEMUTimerCB *cb;
586
    void *opaque;
587
    struct QEMUTimer *next;
588
};
589

    
590
struct qemu_alarm_timer {
591
    char const *name;
592
    unsigned int flags;
593

    
594
    int (*start)(struct qemu_alarm_timer *t);
595
    void (*stop)(struct qemu_alarm_timer *t);
596
    void (*rearm)(struct qemu_alarm_timer *t);
597
    void *priv;
598
};
599

    
600
#define ALARM_FLAG_DYNTICKS  0x1
601
#define ALARM_FLAG_EXPIRED   0x2
602

    
603
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
604
{
605
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
606
}
607

    
608
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
609
{
610
    if (!alarm_has_dynticks(t))
611
        return;
612

    
613
    t->rearm(t);
614
}
615

    
616
/* TODO: MIN_TIMER_REARM_US should be optimized */
617
#define MIN_TIMER_REARM_US 250
618

    
619
static struct qemu_alarm_timer *alarm_timer;
620

    
621
#ifdef _WIN32
622

    
623
struct qemu_alarm_win32 {
624
    MMRESULT timerId;
625
    unsigned int period;
626
} alarm_win32_data = {0, -1};
627

    
628
static int win32_start_timer(struct qemu_alarm_timer *t);
629
static void win32_stop_timer(struct qemu_alarm_timer *t);
630
static void win32_rearm_timer(struct qemu_alarm_timer *t);
631

    
632
#else
633

    
634
static int unix_start_timer(struct qemu_alarm_timer *t);
635
static void unix_stop_timer(struct qemu_alarm_timer *t);
636

    
637
#ifdef __linux__
638

    
639
static int dynticks_start_timer(struct qemu_alarm_timer *t);
640
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
641
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
642

    
643
static int hpet_start_timer(struct qemu_alarm_timer *t);
644
static void hpet_stop_timer(struct qemu_alarm_timer *t);
645

    
646
static int rtc_start_timer(struct qemu_alarm_timer *t);
647
static void rtc_stop_timer(struct qemu_alarm_timer *t);
648

    
649
#endif /* __linux__ */
650

    
651
#endif /* _WIN32 */
652

    
653
/* Correlation between real and virtual time is always going to be
654
   fairly approximate, so ignore small variation.
655
   When the guest is idle real and virtual time will be aligned in
656
   the IO wait loop.  */
657
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
658

    
659
static void icount_adjust(void)
660
{
661
    int64_t cur_time;
662
    int64_t cur_icount;
663
    int64_t delta;
664
    static int64_t last_delta;
665
    /* If the VM is not running, then do nothing.  */
666
    if (!vm_running)
667
        return;
668

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

    
689
static void icount_adjust_rt(void * opaque)
690
{
691
    qemu_mod_timer(icount_rt_timer,
692
                   qemu_get_clock(rt_clock) + 1000);
693
    icount_adjust();
694
}
695

    
696
static void icount_adjust_vm(void * opaque)
697
{
698
    qemu_mod_timer(icount_vm_timer,
699
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
700
    icount_adjust();
701
}
702

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

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

    
738
static void show_available_alarms(void)
739
{
740
    int i;
741

    
742
    printf("Available alarm timers, in order of precedence:\n");
743
    for (i = 0; alarm_timers[i].name; i++)
744
        printf("%s\n", alarm_timers[i].name);
745
}
746

    
747
static void configure_alarms(char const *opt)
748
{
749
    int i;
750
    int cur = 0;
751
    int count = ARRAY_SIZE(alarm_timers) - 1;
752
    char *arg;
753
    char *name;
754
    struct qemu_alarm_timer tmp;
755

    
756
    if (!strcmp(opt, "?")) {
757
        show_available_alarms();
758
        exit(0);
759
    }
760

    
761
    arg = qemu_strdup(opt);
762

    
763
    /* Reorder the array */
764
    name = strtok(arg, ",");
765
    while (name) {
766
        for (i = 0; i < count && alarm_timers[i].name; i++) {
767
            if (!strcmp(alarm_timers[i].name, name))
768
                break;
769
        }
770

    
771
        if (i == count) {
772
            fprintf(stderr, "Unknown clock %s\n", name);
773
            goto next;
774
        }
775

    
776
        if (i < cur)
777
            /* Ignore */
778
            goto next;
779

    
780
        /* Swap */
781
        tmp = alarm_timers[i];
782
        alarm_timers[i] = alarm_timers[cur];
783
        alarm_timers[cur] = tmp;
784

    
785
        cur++;
786
next:
787
        name = strtok(NULL, ",");
788
    }
789

    
790
    qemu_free(arg);
791

    
792
    if (cur) {
793
        /* Disable remaining timers */
794
        for (i = cur; i < count; i++)
795
            alarm_timers[i].name = NULL;
796
    } else {
797
        show_available_alarms();
798
        exit(1);
799
    }
800
}
801

    
802
#define QEMU_NUM_CLOCKS 3
803

    
804
QEMUClock *rt_clock;
805
QEMUClock *vm_clock;
806
QEMUClock *host_clock;
807

    
808
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
809

    
810
static QEMUClock *qemu_new_clock(int type)
811
{
812
    QEMUClock *clock;
813
    clock = qemu_mallocz(sizeof(QEMUClock));
814
    clock->type = type;
815
    return clock;
816
}
817

    
818
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
819
{
820
    QEMUTimer *ts;
821

    
822
    ts = qemu_mallocz(sizeof(QEMUTimer));
823
    ts->clock = clock;
824
    ts->cb = cb;
825
    ts->opaque = opaque;
826
    return ts;
827
}
828

    
829
void qemu_free_timer(QEMUTimer *ts)
830
{
831
    qemu_free(ts);
832
}
833

    
834
/* stop a timer, but do not dealloc it */
835
void qemu_del_timer(QEMUTimer *ts)
836
{
837
    QEMUTimer **pt, *t;
838

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

    
854
/* modify the current timer so that it will be fired when current_time
855
   >= expire_time. The corresponding callback will be called. */
856
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
857
{
858
    QEMUTimer **pt, *t;
859

    
860
    qemu_del_timer(ts);
861

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

    
878
    /* Rearm if necessary  */
879
    if (pt == &active_timers[ts->clock->type]) {
880
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
881
            qemu_rearm_alarm_timer(alarm_timer);
882
        }
883
        /* Interrupt execution to force deadline recalculation.  */
884
        if (use_icount)
885
            qemu_notify_event();
886
    }
887
}
888

    
889
int qemu_timer_pending(QEMUTimer *ts)
890
{
891
    QEMUTimer *t;
892
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
893
        if (t == ts)
894
            return 1;
895
    }
896
    return 0;
897
}
898

    
899
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
900
{
901
    if (!timer_head)
902
        return 0;
903
    return (timer_head->expire_time <= current_time);
904
}
905

    
906
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
907
{
908
    QEMUTimer *ts;
909

    
910
    for(;;) {
911
        ts = *ptimer_head;
912
        if (!ts || ts->expire_time > current_time)
913
            break;
914
        /* remove timer from the list before calling the callback */
915
        *ptimer_head = ts->next;
916
        ts->next = NULL;
917

    
918
        /* run the callback (the timer list can be modified) */
919
        ts->cb(ts->opaque);
920
    }
921
}
922

    
923
int64_t qemu_get_clock(QEMUClock *clock)
924
{
925
    switch(clock->type) {
926
    case QEMU_CLOCK_REALTIME:
927
        return get_clock() / 1000000;
928
    default:
929
    case QEMU_CLOCK_VIRTUAL:
930
        if (use_icount) {
931
            return cpu_get_icount();
932
        } else {
933
            return cpu_get_clock();
934
        }
935
    case QEMU_CLOCK_HOST:
936
        return get_clock_realtime();
937
    }
938
}
939

    
940
int64_t qemu_get_clock_ns(QEMUClock *clock)
941
{
942
    switch(clock->type) {
943
    case QEMU_CLOCK_REALTIME:
944
        return get_clock();
945
    default:
946
    case QEMU_CLOCK_VIRTUAL:
947
        if (use_icount) {
948
            return cpu_get_icount();
949
        } else {
950
            return cpu_get_clock();
951
        }
952
    case QEMU_CLOCK_HOST:
953
        return get_clock_realtime();
954
    }
955
}
956

    
957
static void init_clocks(void)
958
{
959
    init_get_clock();
960
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
961
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
962
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
963

    
964
    rtc_clock = host_clock;
965
}
966

    
967
/* save a timer */
968
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
969
{
970
    uint64_t expire_time;
971

    
972
    if (qemu_timer_pending(ts)) {
973
        expire_time = ts->expire_time;
974
    } else {
975
        expire_time = -1;
976
    }
977
    qemu_put_be64(f, expire_time);
978
}
979

    
980
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
981
{
982
    uint64_t expire_time;
983

    
984
    expire_time = qemu_get_be64(f);
985
    if (expire_time != -1) {
986
        qemu_mod_timer(ts, expire_time);
987
    } else {
988
        qemu_del_timer(ts);
989
    }
990
}
991

    
992
static const VMStateDescription vmstate_timers = {
993
    .name = "timer",
994
    .version_id = 2,
995
    .minimum_version_id = 1,
996
    .minimum_version_id_old = 1,
997
    .fields      = (VMStateField []) {
998
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
999
        VMSTATE_INT64(dummy, TimersState),
1000
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1001
        VMSTATE_END_OF_LIST()
1002
    }
1003
};
1004

    
1005
static void qemu_event_increment(void);
1006

    
1007
#ifdef _WIN32
1008
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1009
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1010
                                        DWORD_PTR dw2)
1011
#else
1012
static void host_alarm_handler(int host_signum)
1013
#endif
1014
{
1015
#if 0
1016
#define DISP_FREQ 1000
1017
    {
1018
        static int64_t delta_min = INT64_MAX;
1019
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1020
        static int count;
1021
        ti = qemu_get_clock(vm_clock);
1022
        if (last_clock != 0) {
1023
            delta = ti - last_clock;
1024
            if (delta < delta_min)
1025
                delta_min = delta;
1026
            if (delta > delta_max)
1027
                delta_max = delta;
1028
            delta_cum += delta;
1029
            if (++count == DISP_FREQ) {
1030
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1031
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1032
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1033
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1034
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1035
                count = 0;
1036
                delta_min = INT64_MAX;
1037
                delta_max = 0;
1038
                delta_cum = 0;
1039
            }
1040
        }
1041
        last_clock = ti;
1042
    }
1043
#endif
1044
    if (alarm_has_dynticks(alarm_timer) ||
1045
        (!use_icount &&
1046
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1047
                               qemu_get_clock(vm_clock))) ||
1048
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1049
                           qemu_get_clock(rt_clock)) ||
1050
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1051
                           qemu_get_clock(host_clock))) {
1052
        qemu_event_increment();
1053
        if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1054

    
1055
#ifndef CONFIG_IOTHREAD
1056
        if (next_cpu) {
1057
            /* stop the currently executing cpu because a timer occured */
1058
            cpu_exit(next_cpu);
1059
        }
1060
#endif
1061
        timer_alarm_pending = 1;
1062
        qemu_notify_event();
1063
    }
1064
}
1065

    
1066
static int64_t qemu_next_deadline(void)
1067
{
1068
    /* To avoid problems with overflow limit this to 2^32.  */
1069
    int64_t delta = INT32_MAX;
1070

    
1071
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1072
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1073
                     qemu_get_clock(vm_clock);
1074
    }
1075
    if (active_timers[QEMU_CLOCK_HOST]) {
1076
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1077
                 qemu_get_clock(host_clock);
1078
        if (hdelta < delta)
1079
            delta = hdelta;
1080
    }
1081

    
1082
    if (delta < 0)
1083
        delta = 0;
1084

    
1085
    return delta;
1086
}
1087

    
1088
#if defined(__linux__)
1089
static uint64_t qemu_next_deadline_dyntick(void)
1090
{
1091
    int64_t delta;
1092
    int64_t rtdelta;
1093

    
1094
    if (use_icount)
1095
        delta = INT32_MAX;
1096
    else
1097
        delta = (qemu_next_deadline() + 999) / 1000;
1098

    
1099
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1100
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1101
                 qemu_get_clock(rt_clock))*1000;
1102
        if (rtdelta < delta)
1103
            delta = rtdelta;
1104
    }
1105

    
1106
    if (delta < MIN_TIMER_REARM_US)
1107
        delta = MIN_TIMER_REARM_US;
1108

    
1109
    return delta;
1110
}
1111
#endif
1112

    
1113
#ifndef _WIN32
1114

    
1115
/* Sets a specific flag */
1116
static int fcntl_setfl(int fd, int flag)
1117
{
1118
    int flags;
1119

    
1120
    flags = fcntl(fd, F_GETFL);
1121
    if (flags == -1)
1122
        return -errno;
1123

    
1124
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1125
        return -errno;
1126

    
1127
    return 0;
1128
}
1129

    
1130
#if defined(__linux__)
1131

    
1132
#define RTC_FREQ 1024
1133

    
1134
static void enable_sigio_timer(int fd)
1135
{
1136
    struct sigaction act;
1137

    
1138
    /* timer signal */
1139
    sigfillset(&act.sa_mask);
1140
    act.sa_flags = 0;
1141
    act.sa_handler = host_alarm_handler;
1142

    
1143
    sigaction(SIGIO, &act, NULL);
1144
    fcntl_setfl(fd, O_ASYNC);
1145
    fcntl(fd, F_SETOWN, getpid());
1146
}
1147

    
1148
static int hpet_start_timer(struct qemu_alarm_timer *t)
1149
{
1150
    struct hpet_info info;
1151
    int r, fd;
1152

    
1153
    fd = qemu_open("/dev/hpet", O_RDONLY);
1154
    if (fd < 0)
1155
        return -1;
1156

    
1157
    /* Set frequency */
1158
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1159
    if (r < 0) {
1160
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1161
                "error, but for better emulation accuracy type:\n"
1162
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1163
        goto fail;
1164
    }
1165

    
1166
    /* Check capabilities */
1167
    r = ioctl(fd, HPET_INFO, &info);
1168
    if (r < 0)
1169
        goto fail;
1170

    
1171
    /* Enable periodic mode */
1172
    r = ioctl(fd, HPET_EPI, 0);
1173
    if (info.hi_flags && (r < 0))
1174
        goto fail;
1175

    
1176
    /* Enable interrupt */
1177
    r = ioctl(fd, HPET_IE_ON, 0);
1178
    if (r < 0)
1179
        goto fail;
1180

    
1181
    enable_sigio_timer(fd);
1182
    t->priv = (void *)(long)fd;
1183

    
1184
    return 0;
1185
fail:
1186
    close(fd);
1187
    return -1;
1188
}
1189

    
1190
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1191
{
1192
    int fd = (long)t->priv;
1193

    
1194
    close(fd);
1195
}
1196

    
1197
static int rtc_start_timer(struct qemu_alarm_timer *t)
1198
{
1199
    int rtc_fd;
1200
    unsigned long current_rtc_freq = 0;
1201

    
1202
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1203
    if (rtc_fd < 0)
1204
        return -1;
1205
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1206
    if (current_rtc_freq != RTC_FREQ &&
1207
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1208
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1209
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1210
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1211
        goto fail;
1212
    }
1213
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1214
    fail:
1215
        close(rtc_fd);
1216
        return -1;
1217
    }
1218

    
1219
    enable_sigio_timer(rtc_fd);
1220

    
1221
    t->priv = (void *)(long)rtc_fd;
1222

    
1223
    return 0;
1224
}
1225

    
1226
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1227
{
1228
    int rtc_fd = (long)t->priv;
1229

    
1230
    close(rtc_fd);
1231
}
1232

    
1233
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1234
{
1235
    struct sigevent ev;
1236
    timer_t host_timer;
1237
    struct sigaction act;
1238

    
1239
    sigfillset(&act.sa_mask);
1240
    act.sa_flags = 0;
1241
    act.sa_handler = host_alarm_handler;
1242

    
1243
    sigaction(SIGALRM, &act, NULL);
1244

    
1245
    /* 
1246
     * Initialize ev struct to 0 to avoid valgrind complaining
1247
     * about uninitialized data in timer_create call
1248
     */
1249
    memset(&ev, 0, sizeof(ev));
1250
    ev.sigev_value.sival_int = 0;
1251
    ev.sigev_notify = SIGEV_SIGNAL;
1252
    ev.sigev_signo = SIGALRM;
1253

    
1254
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1255
        perror("timer_create");
1256

    
1257
        /* disable dynticks */
1258
        fprintf(stderr, "Dynamic Ticks disabled\n");
1259

    
1260
        return -1;
1261
    }
1262

    
1263
    t->priv = (void *)(long)host_timer;
1264

    
1265
    return 0;
1266
}
1267

    
1268
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1269
{
1270
    timer_t host_timer = (timer_t)(long)t->priv;
1271

    
1272
    timer_delete(host_timer);
1273
}
1274

    
1275
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1276
{
1277
    timer_t host_timer = (timer_t)(long)t->priv;
1278
    struct itimerspec timeout;
1279
    int64_t nearest_delta_us = INT64_MAX;
1280
    int64_t current_us;
1281

    
1282
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1283
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1284
        !active_timers[QEMU_CLOCK_HOST])
1285
        return;
1286

    
1287
    nearest_delta_us = qemu_next_deadline_dyntick();
1288

    
1289
    /* check whether a timer is already running */
1290
    if (timer_gettime(host_timer, &timeout)) {
1291
        perror("gettime");
1292
        fprintf(stderr, "Internal timer error: aborting\n");
1293
        exit(1);
1294
    }
1295
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1296
    if (current_us && current_us <= nearest_delta_us)
1297
        return;
1298

    
1299
    timeout.it_interval.tv_sec = 0;
1300
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1301
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1302
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1303
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1304
        perror("settime");
1305
        fprintf(stderr, "Internal timer error: aborting\n");
1306
        exit(1);
1307
    }
1308
}
1309

    
1310
#endif /* defined(__linux__) */
1311

    
1312
static int unix_start_timer(struct qemu_alarm_timer *t)
1313
{
1314
    struct sigaction act;
1315
    struct itimerval itv;
1316
    int err;
1317

    
1318
    /* timer signal */
1319
    sigfillset(&act.sa_mask);
1320
    act.sa_flags = 0;
1321
    act.sa_handler = host_alarm_handler;
1322

    
1323
    sigaction(SIGALRM, &act, NULL);
1324

    
1325
    itv.it_interval.tv_sec = 0;
1326
    /* for i386 kernel 2.6 to get 1 ms */
1327
    itv.it_interval.tv_usec = 999;
1328
    itv.it_value.tv_sec = 0;
1329
    itv.it_value.tv_usec = 10 * 1000;
1330

    
1331
    err = setitimer(ITIMER_REAL, &itv, NULL);
1332
    if (err)
1333
        return -1;
1334

    
1335
    return 0;
1336
}
1337

    
1338
static void unix_stop_timer(struct qemu_alarm_timer *t)
1339
{
1340
    struct itimerval itv;
1341

    
1342
    memset(&itv, 0, sizeof(itv));
1343
    setitimer(ITIMER_REAL, &itv, NULL);
1344
}
1345

    
1346
#endif /* !defined(_WIN32) */
1347

    
1348

    
1349
#ifdef _WIN32
1350

    
1351
static int win32_start_timer(struct qemu_alarm_timer *t)
1352
{
1353
    TIMECAPS tc;
1354
    struct qemu_alarm_win32 *data = t->priv;
1355
    UINT flags;
1356

    
1357
    memset(&tc, 0, sizeof(tc));
1358
    timeGetDevCaps(&tc, sizeof(tc));
1359

    
1360
    if (data->period < tc.wPeriodMin)
1361
        data->period = tc.wPeriodMin;
1362

    
1363
    timeBeginPeriod(data->period);
1364

    
1365
    flags = TIME_CALLBACK_FUNCTION;
1366
    if (alarm_has_dynticks(t))
1367
        flags |= TIME_ONESHOT;
1368
    else
1369
        flags |= TIME_PERIODIC;
1370

    
1371
    data->timerId = timeSetEvent(1,         // interval (ms)
1372
                        data->period,       // resolution
1373
                        host_alarm_handler, // function
1374
                        (DWORD)t,           // parameter
1375
                        flags);
1376

    
1377
    if (!data->timerId) {
1378
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1379
                GetLastError());
1380
        timeEndPeriod(data->period);
1381
        return -1;
1382
    }
1383

    
1384
    return 0;
1385
}
1386

    
1387
static void win32_stop_timer(struct qemu_alarm_timer *t)
1388
{
1389
    struct qemu_alarm_win32 *data = t->priv;
1390

    
1391
    timeKillEvent(data->timerId);
1392
    timeEndPeriod(data->period);
1393
}
1394

    
1395
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1396
{
1397
    struct qemu_alarm_win32 *data = t->priv;
1398

    
1399
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1400
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1401
        !active_timers[QEMU_CLOCK_HOST])
1402
        return;
1403

    
1404
    timeKillEvent(data->timerId);
1405

    
1406
    data->timerId = timeSetEvent(1,
1407
                        data->period,
1408
                        host_alarm_handler,
1409
                        (DWORD)t,
1410
                        TIME_ONESHOT | TIME_PERIODIC);
1411

    
1412
    if (!data->timerId) {
1413
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1414
                GetLastError());
1415

    
1416
        timeEndPeriod(data->period);
1417
        exit(1);
1418
    }
1419
}
1420

    
1421
#endif /* _WIN32 */
1422

    
1423
static int init_timer_alarm(void)
1424
{
1425
    struct qemu_alarm_timer *t = NULL;
1426
    int i, err = -1;
1427

    
1428
    for (i = 0; alarm_timers[i].name; i++) {
1429
        t = &alarm_timers[i];
1430

    
1431
        err = t->start(t);
1432
        if (!err)
1433
            break;
1434
    }
1435

    
1436
    if (err) {
1437
        err = -ENOENT;
1438
        goto fail;
1439
    }
1440

    
1441
    alarm_timer = t;
1442

    
1443
    return 0;
1444

    
1445
fail:
1446
    return err;
1447
}
1448

    
1449
static void quit_timers(void)
1450
{
1451
    alarm_timer->stop(alarm_timer);
1452
    alarm_timer = NULL;
1453
}
1454

    
1455
/***********************************************************/
1456
/* host time/date access */
1457
void qemu_get_timedate(struct tm *tm, int offset)
1458
{
1459
    time_t ti;
1460
    struct tm *ret;
1461

    
1462
    time(&ti);
1463
    ti += offset;
1464
    if (rtc_date_offset == -1) {
1465
        if (rtc_utc)
1466
            ret = gmtime(&ti);
1467
        else
1468
            ret = localtime(&ti);
1469
    } else {
1470
        ti -= rtc_date_offset;
1471
        ret = gmtime(&ti);
1472
    }
1473

    
1474
    memcpy(tm, ret, sizeof(struct tm));
1475
}
1476

    
1477
int qemu_timedate_diff(struct tm *tm)
1478
{
1479
    time_t seconds;
1480

    
1481
    if (rtc_date_offset == -1)
1482
        if (rtc_utc)
1483
            seconds = mktimegm(tm);
1484
        else
1485
            seconds = mktime(tm);
1486
    else
1487
        seconds = mktimegm(tm) + rtc_date_offset;
1488

    
1489
    return seconds - time(NULL);
1490
}
1491

    
1492
static void configure_rtc_date_offset(const char *startdate, int legacy)
1493
{
1494
    time_t rtc_start_date;
1495
    struct tm tm;
1496

    
1497
    if (!strcmp(startdate, "now") && legacy) {
1498
        rtc_date_offset = -1;
1499
    } else {
1500
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1501
                   &tm.tm_year,
1502
                   &tm.tm_mon,
1503
                   &tm.tm_mday,
1504
                   &tm.tm_hour,
1505
                   &tm.tm_min,
1506
                   &tm.tm_sec) == 6) {
1507
            /* OK */
1508
        } else if (sscanf(startdate, "%d-%d-%d",
1509
                          &tm.tm_year,
1510
                          &tm.tm_mon,
1511
                          &tm.tm_mday) == 3) {
1512
            tm.tm_hour = 0;
1513
            tm.tm_min = 0;
1514
            tm.tm_sec = 0;
1515
        } else {
1516
            goto date_fail;
1517
        }
1518
        tm.tm_year -= 1900;
1519
        tm.tm_mon--;
1520
        rtc_start_date = mktimegm(&tm);
1521
        if (rtc_start_date == -1) {
1522
        date_fail:
1523
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1524
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1525
            exit(1);
1526
        }
1527
        rtc_date_offset = time(NULL) - rtc_start_date;
1528
    }
1529
}
1530

    
1531
static void configure_rtc(QemuOpts *opts)
1532
{
1533
    const char *value;
1534

    
1535
    value = qemu_opt_get(opts, "base");
1536
    if (value) {
1537
        if (!strcmp(value, "utc")) {
1538
            rtc_utc = 1;
1539
        } else if (!strcmp(value, "localtime")) {
1540
            rtc_utc = 0;
1541
        } else {
1542
            configure_rtc_date_offset(value, 0);
1543
        }
1544
    }
1545
    value = qemu_opt_get(opts, "clock");
1546
    if (value) {
1547
        if (!strcmp(value, "host")) {
1548
            rtc_clock = host_clock;
1549
        } else if (!strcmp(value, "vm")) {
1550
            rtc_clock = vm_clock;
1551
        } else {
1552
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1553
            exit(1);
1554
        }
1555
    }
1556
#ifdef CONFIG_TARGET_I386
1557
    value = qemu_opt_get(opts, "driftfix");
1558
    if (value) {
1559
        if (!strcmp(buf, "slew")) {
1560
            rtc_td_hack = 1;
1561
        } else if (!strcmp(buf, "none")) {
1562
            rtc_td_hack = 0;
1563
        } else {
1564
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1565
            exit(1);
1566
        }
1567
    }
1568
#endif
1569
}
1570

    
1571
#ifdef _WIN32
1572
static void socket_cleanup(void)
1573
{
1574
    WSACleanup();
1575
}
1576

    
1577
static int socket_init(void)
1578
{
1579
    WSADATA Data;
1580
    int ret, err;
1581

    
1582
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1583
    if (ret != 0) {
1584
        err = WSAGetLastError();
1585
        fprintf(stderr, "WSAStartup: %d\n", err);
1586
        return -1;
1587
    }
1588
    atexit(socket_cleanup);
1589
    return 0;
1590
}
1591
#endif
1592

    
1593
/***********************************************************/
1594
/* Bluetooth support */
1595
static int nb_hcis;
1596
static int cur_hci;
1597
static struct HCIInfo *hci_table[MAX_NICS];
1598

    
1599
static struct bt_vlan_s {
1600
    struct bt_scatternet_s net;
1601
    int id;
1602
    struct bt_vlan_s *next;
1603
} *first_bt_vlan;
1604

    
1605
/* find or alloc a new bluetooth "VLAN" */
1606
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1607
{
1608
    struct bt_vlan_s **pvlan, *vlan;
1609
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1610
        if (vlan->id == id)
1611
            return &vlan->net;
1612
    }
1613
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1614
    vlan->id = id;
1615
    pvlan = &first_bt_vlan;
1616
    while (*pvlan != NULL)
1617
        pvlan = &(*pvlan)->next;
1618
    *pvlan = vlan;
1619
    return &vlan->net;
1620
}
1621

    
1622
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1623
{
1624
}
1625

    
1626
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1627
{
1628
    return -ENOTSUP;
1629
}
1630

    
1631
static struct HCIInfo null_hci = {
1632
    .cmd_send = null_hci_send,
1633
    .sco_send = null_hci_send,
1634
    .acl_send = null_hci_send,
1635
    .bdaddr_set = null_hci_addr_set,
1636
};
1637

    
1638
struct HCIInfo *qemu_next_hci(void)
1639
{
1640
    if (cur_hci == nb_hcis)
1641
        return &null_hci;
1642

    
1643
    return hci_table[cur_hci++];
1644
}
1645

    
1646
static struct HCIInfo *hci_init(const char *str)
1647
{
1648
    char *endp;
1649
    struct bt_scatternet_s *vlan = 0;
1650

    
1651
    if (!strcmp(str, "null"))
1652
        /* null */
1653
        return &null_hci;
1654
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1655
        /* host[:hciN] */
1656
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1657
    else if (!strncmp(str, "hci", 3)) {
1658
        /* hci[,vlan=n] */
1659
        if (str[3]) {
1660
            if (!strncmp(str + 3, ",vlan=", 6)) {
1661
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1662
                if (*endp)
1663
                    vlan = 0;
1664
            }
1665
        } else
1666
            vlan = qemu_find_bt_vlan(0);
1667
        if (vlan)
1668
           return bt_new_hci(vlan);
1669
    }
1670

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

    
1673
    return 0;
1674
}
1675

    
1676
static int bt_hci_parse(const char *str)
1677
{
1678
    struct HCIInfo *hci;
1679
    bdaddr_t bdaddr;
1680

    
1681
    if (nb_hcis >= MAX_NICS) {
1682
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1683
        return -1;
1684
    }
1685

    
1686
    hci = hci_init(str);
1687
    if (!hci)
1688
        return -1;
1689

    
1690
    bdaddr.b[0] = 0x52;
1691
    bdaddr.b[1] = 0x54;
1692
    bdaddr.b[2] = 0x00;
1693
    bdaddr.b[3] = 0x12;
1694
    bdaddr.b[4] = 0x34;
1695
    bdaddr.b[5] = 0x56 + nb_hcis;
1696
    hci->bdaddr_set(hci, bdaddr.b);
1697

    
1698
    hci_table[nb_hcis++] = hci;
1699

    
1700
    return 0;
1701
}
1702

    
1703
static void bt_vhci_add(int vlan_id)
1704
{
1705
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1706

    
1707
    if (!vlan->slave)
1708
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1709
                        "an empty scatternet %i\n", vlan_id);
1710

    
1711
    bt_vhci_init(bt_new_hci(vlan));
1712
}
1713

    
1714
static struct bt_device_s *bt_device_add(const char *opt)
1715
{
1716
    struct bt_scatternet_s *vlan;
1717
    int vlan_id = 0;
1718
    char *endp = strstr(opt, ",vlan=");
1719
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1720
    char devname[10];
1721

    
1722
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1723

    
1724
    if (endp) {
1725
        vlan_id = strtol(endp + 6, &endp, 0);
1726
        if (*endp) {
1727
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1728
            return 0;
1729
        }
1730
    }
1731

    
1732
    vlan = qemu_find_bt_vlan(vlan_id);
1733

    
1734
    if (!vlan->slave)
1735
        fprintf(stderr, "qemu: warning: adding a slave device to "
1736
                        "an empty scatternet %i\n", vlan_id);
1737

    
1738
    if (!strcmp(devname, "keyboard"))
1739
        return bt_keyboard_init(vlan);
1740

    
1741
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1742
    return 0;
1743
}
1744

    
1745
static int bt_parse(const char *opt)
1746
{
1747
    const char *endp, *p;
1748
    int vlan;
1749

    
1750
    if (strstart(opt, "hci", &endp)) {
1751
        if (!*endp || *endp == ',') {
1752
            if (*endp)
1753
                if (!strstart(endp, ",vlan=", 0))
1754
                    opt = endp + 1;
1755

    
1756
            return bt_hci_parse(opt);
1757
       }
1758
    } else if (strstart(opt, "vhci", &endp)) {
1759
        if (!*endp || *endp == ',') {
1760
            if (*endp) {
1761
                if (strstart(endp, ",vlan=", &p)) {
1762
                    vlan = strtol(p, (char **) &endp, 0);
1763
                    if (*endp) {
1764
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1765
                        return 1;
1766
                    }
1767
                } else {
1768
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1769
                    return 1;
1770
                }
1771
            } else
1772
                vlan = 0;
1773

    
1774
            bt_vhci_add(vlan);
1775
            return 0;
1776
        }
1777
    } else if (strstart(opt, "device:", &endp))
1778
        return !bt_device_add(endp);
1779

    
1780
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1781
    return 1;
1782
}
1783

    
1784
/***********************************************************/
1785
/* QEMU Block devices */
1786

    
1787
#define HD_ALIAS "index=%d,media=disk"
1788
#define CDROM_ALIAS "index=2,media=cdrom"
1789
#define FD_ALIAS "index=%d,if=floppy"
1790
#define PFLASH_ALIAS "if=pflash"
1791
#define MTD_ALIAS "if=mtd"
1792
#define SD_ALIAS "index=0,if=sd"
1793

    
1794
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1795
{
1796
    va_list ap;
1797
    char optstr[1024];
1798
    QemuOpts *opts;
1799

    
1800
    va_start(ap, fmt);
1801
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1802
    va_end(ap);
1803

    
1804
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1805
    if (!opts) {
1806
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1807
                __FUNCTION__, optstr);
1808
        return NULL;
1809
    }
1810
    if (file)
1811
        qemu_opt_set(opts, "file", file);
1812
    return opts;
1813
}
1814

    
1815
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1816
{
1817
    DriveInfo *dinfo;
1818

    
1819
    /* seek interface, bus and unit */
1820

    
1821
    QTAILQ_FOREACH(dinfo, &drives, next) {
1822
        if (dinfo->type == type &&
1823
            dinfo->bus == bus &&
1824
            dinfo->unit == unit)
1825
            return dinfo;
1826
    }
1827

    
1828
    return NULL;
1829
}
1830

    
1831
DriveInfo *drive_get_by_id(const char *id)
1832
{
1833
    DriveInfo *dinfo;
1834

    
1835
    QTAILQ_FOREACH(dinfo, &drives, next) {
1836
        if (strcmp(id, dinfo->id))
1837
            continue;
1838
        return dinfo;
1839
    }
1840
    return NULL;
1841
}
1842

    
1843
int drive_get_max_bus(BlockInterfaceType type)
1844
{
1845
    int max_bus;
1846
    DriveInfo *dinfo;
1847

    
1848
    max_bus = -1;
1849
    QTAILQ_FOREACH(dinfo, &drives, next) {
1850
        if(dinfo->type == type &&
1851
           dinfo->bus > max_bus)
1852
            max_bus = dinfo->bus;
1853
    }
1854
    return max_bus;
1855
}
1856

    
1857
const char *drive_get_serial(BlockDriverState *bdrv)
1858
{
1859
    DriveInfo *dinfo;
1860

    
1861
    QTAILQ_FOREACH(dinfo, &drives, next) {
1862
        if (dinfo->bdrv == bdrv)
1863
            return dinfo->serial;
1864
    }
1865

    
1866
    return "\0";
1867
}
1868

    
1869
BlockInterfaceErrorAction drive_get_on_error(
1870
    BlockDriverState *bdrv, int is_read)
1871
{
1872
    DriveInfo *dinfo;
1873

    
1874
    QTAILQ_FOREACH(dinfo, &drives, next) {
1875
        if (dinfo->bdrv == bdrv)
1876
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1877
    }
1878

    
1879
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1880
}
1881

    
1882
static void bdrv_format_print(void *opaque, const char *name)
1883
{
1884
    fprintf(stderr, " %s", name);
1885
}
1886

    
1887
void drive_uninit(DriveInfo *dinfo)
1888
{
1889
    qemu_opts_del(dinfo->opts);
1890
    bdrv_delete(dinfo->bdrv);
1891
    QTAILQ_REMOVE(&drives, dinfo, next);
1892
    qemu_free(dinfo);
1893
}
1894

    
1895
static int parse_block_error_action(const char *buf, int is_read)
1896
{
1897
    if (!strcmp(buf, "ignore")) {
1898
        return BLOCK_ERR_IGNORE;
1899
    } else if (!is_read && !strcmp(buf, "enospc")) {
1900
        return BLOCK_ERR_STOP_ENOSPC;
1901
    } else if (!strcmp(buf, "stop")) {
1902
        return BLOCK_ERR_STOP_ANY;
1903
    } else if (!strcmp(buf, "report")) {
1904
        return BLOCK_ERR_REPORT;
1905
    } else {
1906
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1907
            buf, is_read ? "read" : "write");
1908
        return -1;
1909
    }
1910
}
1911

    
1912
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1913
                      int *fatal_error)
1914
{
1915
    const char *buf;
1916
    const char *file = NULL;
1917
    char devname[128];
1918
    const char *serial;
1919
    const char *mediastr = "";
1920
    BlockInterfaceType type;
1921
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1922
    int bus_id, unit_id;
1923
    int cyls, heads, secs, translation;
1924
    BlockDriver *drv = NULL;
1925
    QEMUMachine *machine = opaque;
1926
    int max_devs;
1927
    int index;
1928
    int cache;
1929
    int aio = 0;
1930
    int ro = 0;
1931
    int bdrv_flags;
1932
    int on_read_error, on_write_error;
1933
    const char *devaddr;
1934
    DriveInfo *dinfo;
1935
    int snapshot = 0;
1936

    
1937
    *fatal_error = 1;
1938

    
1939
    translation = BIOS_ATA_TRANSLATION_AUTO;
1940
    cache = 1;
1941

    
1942
    if (machine && machine->use_scsi) {
1943
        type = IF_SCSI;
1944
        max_devs = MAX_SCSI_DEVS;
1945
        pstrcpy(devname, sizeof(devname), "scsi");
1946
    } else {
1947
        type = IF_IDE;
1948
        max_devs = MAX_IDE_DEVS;
1949
        pstrcpy(devname, sizeof(devname), "ide");
1950
    }
1951
    media = MEDIA_DISK;
1952

    
1953
    /* extract parameters */
1954
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1955
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1956
    index   = qemu_opt_get_number(opts, "index", -1);
1957

    
1958
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1959
    heads = qemu_opt_get_number(opts, "heads", 0);
1960
    secs  = qemu_opt_get_number(opts, "secs", 0);
1961

    
1962
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1963
    ro = qemu_opt_get_bool(opts, "readonly", 0);
1964

    
1965
    file = qemu_opt_get(opts, "file");
1966
    serial = qemu_opt_get(opts, "serial");
1967

    
1968
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1969
        pstrcpy(devname, sizeof(devname), buf);
1970
        if (!strcmp(buf, "ide")) {
1971
            type = IF_IDE;
1972
            max_devs = MAX_IDE_DEVS;
1973
        } else if (!strcmp(buf, "scsi")) {
1974
            type = IF_SCSI;
1975
            max_devs = MAX_SCSI_DEVS;
1976
        } else if (!strcmp(buf, "floppy")) {
1977
            type = IF_FLOPPY;
1978
            max_devs = 0;
1979
        } else if (!strcmp(buf, "pflash")) {
1980
            type = IF_PFLASH;
1981
            max_devs = 0;
1982
        } else if (!strcmp(buf, "mtd")) {
1983
            type = IF_MTD;
1984
            max_devs = 0;
1985
        } else if (!strcmp(buf, "sd")) {
1986
            type = IF_SD;
1987
            max_devs = 0;
1988
        } else if (!strcmp(buf, "virtio")) {
1989
            type = IF_VIRTIO;
1990
            max_devs = 0;
1991
        } else if (!strcmp(buf, "xen")) {
1992
            type = IF_XEN;
1993
            max_devs = 0;
1994
        } else if (!strcmp(buf, "none")) {
1995
            type = IF_NONE;
1996
            max_devs = 0;
1997
        } else {
1998
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1999
            return NULL;
2000
        }
2001
    }
2002

    
2003
    if (cyls || heads || secs) {
2004
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2005
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2006
            return NULL;
2007
        }
2008
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
2009
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2010
            return NULL;
2011
        }
2012
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
2013
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2014
            return NULL;
2015
        }
2016
    }
2017

    
2018
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2019
        if (!cyls) {
2020
            fprintf(stderr,
2021
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2022
                    buf);
2023
            return NULL;
2024
        }
2025
        if (!strcmp(buf, "none"))
2026
            translation = BIOS_ATA_TRANSLATION_NONE;
2027
        else if (!strcmp(buf, "lba"))
2028
            translation = BIOS_ATA_TRANSLATION_LBA;
2029
        else if (!strcmp(buf, "auto"))
2030
            translation = BIOS_ATA_TRANSLATION_AUTO;
2031
        else {
2032
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2033
            return NULL;
2034
        }
2035
    }
2036

    
2037
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2038
        if (!strcmp(buf, "disk")) {
2039
            media = MEDIA_DISK;
2040
        } else if (!strcmp(buf, "cdrom")) {
2041
            if (cyls || secs || heads) {
2042
                fprintf(stderr,
2043
                        "qemu: '%s' invalid physical CHS format\n", buf);
2044
                return NULL;
2045
            }
2046
            media = MEDIA_CDROM;
2047
        } else {
2048
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2049
            return NULL;
2050
        }
2051
    }
2052

    
2053
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2054
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2055
            cache = 0;
2056
        else if (!strcmp(buf, "writethrough"))
2057
            cache = 1;
2058
        else if (!strcmp(buf, "writeback"))
2059
            cache = 2;
2060
        else {
2061
           fprintf(stderr, "qemu: invalid cache option\n");
2062
           return NULL;
2063
        }
2064
    }
2065

    
2066
#ifdef CONFIG_LINUX_AIO
2067
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2068
        if (!strcmp(buf, "threads"))
2069
            aio = 0;
2070
        else if (!strcmp(buf, "native"))
2071
            aio = 1;
2072
        else {
2073
           fprintf(stderr, "qemu: invalid aio option\n");
2074
           return NULL;
2075
        }
2076
    }
2077
#endif
2078

    
2079
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2080
       if (strcmp(buf, "?") == 0) {
2081
            fprintf(stderr, "qemu: Supported formats:");
2082
            bdrv_iterate_format(bdrv_format_print, NULL);
2083
            fprintf(stderr, "\n");
2084
            return NULL;
2085
        }
2086
        drv = bdrv_find_whitelisted_format(buf);
2087
        if (!drv) {
2088
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2089
            return NULL;
2090
        }
2091
    }
2092

    
2093
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2094
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2095
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2096
            fprintf(stderr, "werror is no supported by this format\n");
2097
            return NULL;
2098
        }
2099

    
2100
        on_write_error = parse_block_error_action(buf, 0);
2101
        if (on_write_error < 0) {
2102
            return NULL;
2103
        }
2104
    }
2105

    
2106
    on_read_error = BLOCK_ERR_REPORT;
2107
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2108
        if (type != IF_IDE && type != IF_VIRTIO) {
2109
            fprintf(stderr, "rerror is no supported by this format\n");
2110
            return NULL;
2111
        }
2112

    
2113
        on_read_error = parse_block_error_action(buf, 1);
2114
        if (on_read_error < 0) {
2115
            return NULL;
2116
        }
2117
    }
2118

    
2119
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2120
        if (type != IF_VIRTIO) {
2121
            fprintf(stderr, "addr is not supported\n");
2122
            return NULL;
2123
        }
2124
    }
2125

    
2126
    /* compute bus and unit according index */
2127

    
2128
    if (index != -1) {
2129
        if (bus_id != 0 || unit_id != -1) {
2130
            fprintf(stderr,
2131
                    "qemu: index cannot be used with bus and unit\n");
2132
            return NULL;
2133
        }
2134
        if (max_devs == 0)
2135
        {
2136
            unit_id = index;
2137
            bus_id = 0;
2138
        } else {
2139
            unit_id = index % max_devs;
2140
            bus_id = index / max_devs;
2141
        }
2142
    }
2143

    
2144
    /* if user doesn't specify a unit_id,
2145
     * try to find the first free
2146
     */
2147

    
2148
    if (unit_id == -1) {
2149
       unit_id = 0;
2150
       while (drive_get(type, bus_id, unit_id) != NULL) {
2151
           unit_id++;
2152
           if (max_devs && unit_id >= max_devs) {
2153
               unit_id -= max_devs;
2154
               bus_id++;
2155
           }
2156
       }
2157
    }
2158

    
2159
    /* check unit id */
2160

    
2161
    if (max_devs && unit_id >= max_devs) {
2162
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2163
                unit_id, max_devs - 1);
2164
        return NULL;
2165
    }
2166

    
2167
    /*
2168
     * ignore multiple definitions
2169
     */
2170

    
2171
    if (drive_get(type, bus_id, unit_id) != NULL) {
2172
        *fatal_error = 0;
2173
        return NULL;
2174
    }
2175

    
2176
    /* init */
2177

    
2178
    dinfo = qemu_mallocz(sizeof(*dinfo));
2179
    if ((buf = qemu_opts_id(opts)) != NULL) {
2180
        dinfo->id = qemu_strdup(buf);
2181
    } else {
2182
        /* no id supplied -> create one */
2183
        dinfo->id = qemu_mallocz(32);
2184
        if (type == IF_IDE || type == IF_SCSI)
2185
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2186
        if (max_devs)
2187
            snprintf(dinfo->id, 32, "%s%i%s%i",
2188
                     devname, bus_id, mediastr, unit_id);
2189
        else
2190
            snprintf(dinfo->id, 32, "%s%s%i",
2191
                     devname, mediastr, unit_id);
2192
    }
2193
    dinfo->bdrv = bdrv_new(dinfo->id);
2194
    dinfo->devaddr = devaddr;
2195
    dinfo->type = type;
2196
    dinfo->bus = bus_id;
2197
    dinfo->unit = unit_id;
2198
    dinfo->on_read_error = on_read_error;
2199
    dinfo->on_write_error = on_write_error;
2200
    dinfo->opts = opts;
2201
    if (serial)
2202
        strncpy(dinfo->serial, serial, sizeof(serial));
2203
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2204

    
2205
    switch(type) {
2206
    case IF_IDE:
2207
    case IF_SCSI:
2208
    case IF_XEN:
2209
    case IF_NONE:
2210
        switch(media) {
2211
        case MEDIA_DISK:
2212
            if (cyls != 0) {
2213
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2214
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2215
            }
2216
            break;
2217
        case MEDIA_CDROM:
2218
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2219
            break;
2220
        }
2221
        break;
2222
    case IF_SD:
2223
        /* FIXME: This isn't really a floppy, but it's a reasonable
2224
           approximation.  */
2225
    case IF_FLOPPY:
2226
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2227
        break;
2228
    case IF_PFLASH:
2229
    case IF_MTD:
2230
        break;
2231
    case IF_VIRTIO:
2232
        /* add virtio block device */
2233
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2234
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
2235
        qemu_opt_set(opts, "drive", dinfo->id);
2236
        if (devaddr)
2237
            qemu_opt_set(opts, "addr", devaddr);
2238
        break;
2239
    case IF_COUNT:
2240
        abort();
2241
    }
2242
    if (!file) {
2243
        *fatal_error = 0;
2244
        return NULL;
2245
    }
2246
    bdrv_flags = 0;
2247
    if (snapshot) {
2248
        bdrv_flags |= BDRV_O_SNAPSHOT;
2249
        cache = 2; /* always use write-back with snapshot */
2250
    }
2251
    if (cache == 0) /* no caching */
2252
        bdrv_flags |= BDRV_O_NOCACHE;
2253
    else if (cache == 2) /* write-back */
2254
        bdrv_flags |= BDRV_O_CACHE_WB;
2255

    
2256
    if (aio == 1) {
2257
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2258
    } else {
2259
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2260
    }
2261

    
2262
    if (ro == 1) {
2263
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2264
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2265
            return NULL;
2266
        }
2267
    }
2268
    /* 
2269
     * cdrom is read-only. Set it now, after above interface checking
2270
     * since readonly attribute not explicitly required, so no error.
2271
     */
2272
    if (media == MEDIA_CDROM) {
2273
        ro = 1;
2274
    }
2275
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2276

    
2277
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2278
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2279
                        file, strerror(errno));
2280
        return NULL;
2281
    }
2282

    
2283
    if (bdrv_key_required(dinfo->bdrv))
2284
        autostart = 0;
2285
    *fatal_error = 0;
2286
    return dinfo;
2287
}
2288

    
2289
static int drive_init_func(QemuOpts *opts, void *opaque)
2290
{
2291
    QEMUMachine *machine = opaque;
2292
    int fatal_error = 0;
2293

    
2294
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2295
        if (fatal_error)
2296
            return 1;
2297
    }
2298
    return 0;
2299
}
2300

    
2301
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2302
{
2303
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2304
        qemu_opt_set(opts, "snapshot", "on");
2305
    }
2306
    return 0;
2307
}
2308

    
2309
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2310
{
2311
    boot_set_handler = func;
2312
    boot_set_opaque = opaque;
2313
}
2314

    
2315
int qemu_boot_set(const char *boot_devices)
2316
{
2317
    if (!boot_set_handler) {
2318
        return -EINVAL;
2319
    }
2320
    return boot_set_handler(boot_set_opaque, boot_devices);
2321
}
2322

    
2323
static int parse_bootdevices(char *devices)
2324
{
2325
    /* We just do some generic consistency checks */
2326
    const char *p;
2327
    int bitmap = 0;
2328

    
2329
    for (p = devices; *p != '\0'; p++) {
2330
        /* Allowed boot devices are:
2331
         * a-b: floppy disk drives
2332
         * c-f: IDE disk drives
2333
         * g-m: machine implementation dependant drives
2334
         * n-p: network devices
2335
         * It's up to each machine implementation to check if the given boot
2336
         * devices match the actual hardware implementation and firmware
2337
         * features.
2338
         */
2339
        if (*p < 'a' || *p > 'p') {
2340
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2341
            exit(1);
2342
        }
2343
        if (bitmap & (1 << (*p - 'a'))) {
2344
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2345
            exit(1);
2346
        }
2347
        bitmap |= 1 << (*p - 'a');
2348
    }
2349
    return bitmap;
2350
}
2351

    
2352
static void restore_boot_devices(void *opaque)
2353
{
2354
    char *standard_boot_devices = opaque;
2355

    
2356
    qemu_boot_set(standard_boot_devices);
2357

    
2358
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2359
    qemu_free(standard_boot_devices);
2360
}
2361

    
2362
static void numa_add(const char *optarg)
2363
{
2364
    char option[128];
2365
    char *endptr;
2366
    unsigned long long value, endvalue;
2367
    int nodenr;
2368

    
2369
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2370
    if (!strcmp(option, "node")) {
2371
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2372
            nodenr = nb_numa_nodes;
2373
        } else {
2374
            nodenr = strtoull(option, NULL, 10);
2375
        }
2376

    
2377
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2378
            node_mem[nodenr] = 0;
2379
        } else {
2380
            value = strtoull(option, &endptr, 0);
2381
            switch (*endptr) {
2382
            case 0: case 'M': case 'm':
2383
                value <<= 20;
2384
                break;
2385
            case 'G': case 'g':
2386
                value <<= 30;
2387
                break;
2388
            }
2389
            node_mem[nodenr] = value;
2390
        }
2391
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2392
            node_cpumask[nodenr] = 0;
2393
        } else {
2394
            value = strtoull(option, &endptr, 10);
2395
            if (value >= 64) {
2396
                value = 63;
2397
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2398
            } else {
2399
                if (*endptr == '-') {
2400
                    endvalue = strtoull(endptr+1, &endptr, 10);
2401
                    if (endvalue >= 63) {
2402
                        endvalue = 62;
2403
                        fprintf(stderr,
2404
                            "only 63 CPUs in NUMA mode supported.\n");
2405
                    }
2406
                    value = (2ULL << endvalue) - (1ULL << value);
2407
                } else {
2408
                    value = 1ULL << value;
2409
                }
2410
            }
2411
            node_cpumask[nodenr] = value;
2412
        }
2413
        nb_numa_nodes++;
2414
    }
2415
    return;
2416
}
2417

    
2418
static void smp_parse(const char *optarg)
2419
{
2420
    int smp, sockets = 0, threads = 0, cores = 0;
2421
    char *endptr;
2422
    char option[128];
2423

    
2424
    smp = strtoul(optarg, &endptr, 10);
2425
    if (endptr != optarg) {
2426
        if (*endptr == ',') {
2427
            endptr++;
2428
        }
2429
    }
2430
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2431
        sockets = strtoull(option, NULL, 10);
2432
    if (get_param_value(option, 128, "cores", endptr) != 0)
2433
        cores = strtoull(option, NULL, 10);
2434
    if (get_param_value(option, 128, "threads", endptr) != 0)
2435
        threads = strtoull(option, NULL, 10);
2436
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2437
        max_cpus = strtoull(option, NULL, 10);
2438

    
2439
    /* compute missing values, prefer sockets over cores over threads */
2440
    if (smp == 0 || sockets == 0) {
2441
        sockets = sockets > 0 ? sockets : 1;
2442
        cores = cores > 0 ? cores : 1;
2443
        threads = threads > 0 ? threads : 1;
2444
        if (smp == 0) {
2445
            smp = cores * threads * sockets;
2446
        }
2447
    } else {
2448
        if (cores == 0) {
2449
            threads = threads > 0 ? threads : 1;
2450
            cores = smp / (sockets * threads);
2451
        } else {
2452
            if (sockets) {
2453
                threads = smp / (cores * sockets);
2454
            }
2455
        }
2456
    }
2457
    smp_cpus = smp;
2458
    smp_cores = cores > 0 ? cores : 1;
2459
    smp_threads = threads > 0 ? threads : 1;
2460
    if (max_cpus == 0)
2461
        max_cpus = smp_cpus;
2462
}
2463

    
2464
/***********************************************************/
2465
/* USB devices */
2466

    
2467
static int usb_device_add(const char *devname, int is_hotplug)
2468
{
2469
    const char *p;
2470
    USBDevice *dev = NULL;
2471

    
2472
    if (!usb_enabled)
2473
        return -1;
2474

    
2475
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2476
    dev = usbdevice_create(devname);
2477
    if (dev)
2478
        goto done;
2479

    
2480
    /* the other ones */
2481
    if (strstart(devname, "host:", &p)) {
2482
        dev = usb_host_device_open(p);
2483
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2484
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2485
                        bt_new_hci(qemu_find_bt_vlan(0)));
2486
    } else {
2487
        return -1;
2488
    }
2489
    if (!dev)
2490
        return -1;
2491

    
2492
done:
2493
    return 0;
2494
}
2495

    
2496
static int usb_device_del(const char *devname)
2497
{
2498
    int bus_num, addr;
2499
    const char *p;
2500

    
2501
    if (strstart(devname, "host:", &p))
2502
        return usb_host_device_close(p);
2503

    
2504
    if (!usb_enabled)
2505
        return -1;
2506

    
2507
    p = strchr(devname, '.');
2508
    if (!p)
2509
        return -1;
2510
    bus_num = strtoul(devname, NULL, 0);
2511
    addr = strtoul(p + 1, NULL, 0);
2512

    
2513
    return usb_device_delete_addr(bus_num, addr);
2514
}
2515

    
2516
static int usb_parse(const char *cmdline)
2517
{
2518
    int r;
2519
    r = usb_device_add(cmdline, 0);
2520
    if (r < 0) {
2521
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2522
    }
2523
    return r;
2524
}
2525

    
2526
void do_usb_add(Monitor *mon, const QDict *qdict)
2527
{
2528
    const char *devname = qdict_get_str(qdict, "devname");
2529
    if (usb_device_add(devname, 1) < 0) {
2530
        qemu_error("could not add USB device '%s'\n", devname);
2531
    }
2532
}
2533

    
2534
void do_usb_del(Monitor *mon, const QDict *qdict)
2535
{
2536
    const char *devname = qdict_get_str(qdict, "devname");
2537
    if (usb_device_del(devname) < 0) {
2538
        qemu_error("could not delete USB device '%s'\n", devname);
2539
    }
2540
}
2541

    
2542
/***********************************************************/
2543
/* PCMCIA/Cardbus */
2544

    
2545
static struct pcmcia_socket_entry_s {
2546
    PCMCIASocket *socket;
2547
    struct pcmcia_socket_entry_s *next;
2548
} *pcmcia_sockets = 0;
2549

    
2550
void pcmcia_socket_register(PCMCIASocket *socket)
2551
{
2552
    struct pcmcia_socket_entry_s *entry;
2553

    
2554
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2555
    entry->socket = socket;
2556
    entry->next = pcmcia_sockets;
2557
    pcmcia_sockets = entry;
2558
}
2559

    
2560
void pcmcia_socket_unregister(PCMCIASocket *socket)
2561
{
2562
    struct pcmcia_socket_entry_s *entry, **ptr;
2563

    
2564
    ptr = &pcmcia_sockets;
2565
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2566
        if (entry->socket == socket) {
2567
            *ptr = entry->next;
2568
            qemu_free(entry);
2569
        }
2570
}
2571

    
2572
void pcmcia_info(Monitor *mon)
2573
{
2574
    struct pcmcia_socket_entry_s *iter;
2575

    
2576
    if (!pcmcia_sockets)
2577
        monitor_printf(mon, "No PCMCIA sockets\n");
2578

    
2579
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2580
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2581
                       iter->socket->attached ? iter->socket->card_string :
2582
                       "Empty");
2583
}
2584

    
2585
/***********************************************************/
2586
/* register display */
2587

    
2588
struct DisplayAllocator default_allocator = {
2589
    defaultallocator_create_displaysurface,
2590
    defaultallocator_resize_displaysurface,
2591
    defaultallocator_free_displaysurface
2592
};
2593

    
2594
void register_displaystate(DisplayState *ds)
2595
{
2596
    DisplayState **s;
2597
    s = &display_state;
2598
    while (*s != NULL)
2599
        s = &(*s)->next;
2600
    ds->next = NULL;
2601
    *s = ds;
2602
}
2603

    
2604
DisplayState *get_displaystate(void)
2605
{
2606
    return display_state;
2607
}
2608

    
2609
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2610
{
2611
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2612
    return ds->allocator;
2613
}
2614

    
2615
/* dumb display */
2616

    
2617
static void dumb_display_init(void)
2618
{
2619
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2620
    ds->allocator = &default_allocator;
2621
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2622
    register_displaystate(ds);
2623
}
2624

    
2625
/***********************************************************/
2626
/* I/O handling */
2627

    
2628
typedef struct IOHandlerRecord {
2629
    int fd;
2630
    IOCanRWHandler *fd_read_poll;
2631
    IOHandler *fd_read;
2632
    IOHandler *fd_write;
2633
    int deleted;
2634
    void *opaque;
2635
    /* temporary data */
2636
    struct pollfd *ufd;
2637
    struct IOHandlerRecord *next;
2638
} IOHandlerRecord;
2639

    
2640
static IOHandlerRecord *first_io_handler;
2641

    
2642
/* XXX: fd_read_poll should be suppressed, but an API change is
2643
   necessary in the character devices to suppress fd_can_read(). */
2644
int qemu_set_fd_handler2(int fd,
2645
                         IOCanRWHandler *fd_read_poll,
2646
                         IOHandler *fd_read,
2647
                         IOHandler *fd_write,
2648
                         void *opaque)
2649
{
2650
    IOHandlerRecord **pioh, *ioh;
2651

    
2652
    if (!fd_read && !fd_write) {
2653
        pioh = &first_io_handler;
2654
        for(;;) {
2655
            ioh = *pioh;
2656
            if (ioh == NULL)
2657
                break;
2658
            if (ioh->fd == fd) {
2659
                ioh->deleted = 1;
2660
                break;
2661
            }
2662
            pioh = &ioh->next;
2663
        }
2664
    } else {
2665
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2666
            if (ioh->fd == fd)
2667
                goto found;
2668
        }
2669
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2670
        ioh->next = first_io_handler;
2671
        first_io_handler = ioh;
2672
    found:
2673
        ioh->fd = fd;
2674
        ioh->fd_read_poll = fd_read_poll;
2675
        ioh->fd_read = fd_read;
2676
        ioh->fd_write = fd_write;
2677
        ioh->opaque = opaque;
2678
        ioh->deleted = 0;
2679
    }
2680
    return 0;
2681
}
2682

    
2683
int qemu_set_fd_handler(int fd,
2684
                        IOHandler *fd_read,
2685
                        IOHandler *fd_write,
2686
                        void *opaque)
2687
{
2688
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2689
}
2690

    
2691
#ifdef _WIN32
2692
/***********************************************************/
2693
/* Polling handling */
2694

    
2695
typedef struct PollingEntry {
2696
    PollingFunc *func;
2697
    void *opaque;
2698
    struct PollingEntry *next;
2699
} PollingEntry;
2700

    
2701
static PollingEntry *first_polling_entry;
2702

    
2703
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2704
{
2705
    PollingEntry **ppe, *pe;
2706
    pe = qemu_mallocz(sizeof(PollingEntry));
2707
    pe->func = func;
2708
    pe->opaque = opaque;
2709
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2710
    *ppe = pe;
2711
    return 0;
2712
}
2713

    
2714
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2715
{
2716
    PollingEntry **ppe, *pe;
2717
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2718
        pe = *ppe;
2719
        if (pe->func == func && pe->opaque == opaque) {
2720
            *ppe = pe->next;
2721
            qemu_free(pe);
2722
            break;
2723
        }
2724
    }
2725
}
2726

    
2727
/***********************************************************/
2728
/* Wait objects support */
2729
typedef struct WaitObjects {
2730
    int num;
2731
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2732
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2733
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2734
} WaitObjects;
2735

    
2736
static WaitObjects wait_objects = {0};
2737

    
2738
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2739
{
2740
    WaitObjects *w = &wait_objects;
2741

    
2742
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2743
        return -1;
2744
    w->events[w->num] = handle;
2745
    w->func[w->num] = func;
2746
    w->opaque[w->num] = opaque;
2747
    w->num++;
2748
    return 0;
2749
}
2750

    
2751
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2752
{
2753
    int i, found;
2754
    WaitObjects *w = &wait_objects;
2755

    
2756
    found = 0;
2757
    for (i = 0; i < w->num; i++) {
2758
        if (w->events[i] == handle)
2759
            found = 1;
2760
        if (found) {
2761
            w->events[i] = w->events[i + 1];
2762
            w->func[i] = w->func[i + 1];
2763
            w->opaque[i] = w->opaque[i + 1];
2764
        }
2765
    }
2766
    if (found)
2767
        w->num--;
2768
}
2769
#endif
2770

    
2771
/***********************************************************/
2772
/* ram save/restore */
2773

    
2774
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2775
#define RAM_SAVE_FLAG_COMPRESS        0x02
2776
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2777
#define RAM_SAVE_FLAG_PAGE        0x08
2778
#define RAM_SAVE_FLAG_EOS        0x10
2779

    
2780
static int is_dup_page(uint8_t *page, uint8_t ch)
2781
{
2782
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2783
    uint32_t *array = (uint32_t *)page;
2784
    int i;
2785

    
2786
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2787
        if (array[i] != val)
2788
            return 0;
2789
    }
2790

    
2791
    return 1;
2792
}
2793

    
2794
static int ram_save_block(QEMUFile *f)
2795
{
2796
    static ram_addr_t current_addr = 0;
2797
    ram_addr_t saved_addr = current_addr;
2798
    ram_addr_t addr = 0;
2799
    int found = 0;
2800

    
2801
    while (addr < last_ram_offset) {
2802
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2803
            uint8_t *p;
2804

    
2805
            cpu_physical_memory_reset_dirty(current_addr,
2806
                                            current_addr + TARGET_PAGE_SIZE,
2807
                                            MIGRATION_DIRTY_FLAG);
2808

    
2809
            p = qemu_get_ram_ptr(current_addr);
2810

    
2811
            if (is_dup_page(p, *p)) {
2812
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2813
                qemu_put_byte(f, *p);
2814
            } else {
2815
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2816
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2817
            }
2818

    
2819
            found = 1;
2820
            break;
2821
        }
2822
        addr += TARGET_PAGE_SIZE;
2823
        current_addr = (saved_addr + addr) % last_ram_offset;
2824
    }
2825

    
2826
    return found;
2827
}
2828

    
2829
static uint64_t bytes_transferred;
2830

    
2831
static ram_addr_t ram_save_remaining(void)
2832
{
2833
    ram_addr_t addr;
2834
    ram_addr_t count = 0;
2835

    
2836
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2837
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2838
            count++;
2839
    }
2840

    
2841
    return count;
2842
}
2843

    
2844
uint64_t ram_bytes_remaining(void)
2845
{
2846
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2847
}
2848

    
2849
uint64_t ram_bytes_transferred(void)
2850
{
2851
    return bytes_transferred;
2852
}
2853

    
2854
uint64_t ram_bytes_total(void)
2855
{
2856
    return last_ram_offset;
2857
}
2858

    
2859
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2860
{
2861
    ram_addr_t addr;
2862
    uint64_t bytes_transferred_last;
2863
    double bwidth = 0;
2864
    uint64_t expected_time = 0;
2865

    
2866
    if (stage < 0) {
2867
        cpu_physical_memory_set_dirty_tracking(0);
2868
        return 0;
2869
    }
2870

    
2871
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2872
        qemu_file_set_error(f);
2873
        return 0;
2874
    }
2875

    
2876
    if (stage == 1) {
2877
        bytes_transferred = 0;
2878

    
2879
        /* Make sure all dirty bits are set */
2880
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2881
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2882
                cpu_physical_memory_set_dirty(addr);
2883
        }
2884

    
2885
        /* Enable dirty memory tracking */
2886
        cpu_physical_memory_set_dirty_tracking(1);
2887

    
2888
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2889
    }
2890

    
2891
    bytes_transferred_last = bytes_transferred;
2892
    bwidth = qemu_get_clock_ns(rt_clock);
2893

    
2894
    while (!qemu_file_rate_limit(f)) {
2895
        int ret;
2896

    
2897
        ret = ram_save_block(f);
2898
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2899
        if (ret == 0) /* no more blocks */
2900
            break;
2901
    }
2902

    
2903
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2904
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2905

    
2906
    /* if we haven't transferred anything this round, force expected_time to a
2907
     * a very high value, but without crashing */
2908
    if (bwidth == 0)
2909
        bwidth = 0.000001;
2910

    
2911
    /* try transferring iterative blocks of memory */
2912
    if (stage == 3) {
2913
        /* flush all remaining blocks regardless of rate limiting */
2914
        while (ram_save_block(f) != 0) {
2915
            bytes_transferred += TARGET_PAGE_SIZE;
2916
        }
2917
        cpu_physical_memory_set_dirty_tracking(0);
2918
    }
2919

    
2920
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2921

    
2922
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2923

    
2924
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2925
}
2926

    
2927
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2928
{
2929
    ram_addr_t addr;
2930
    int flags;
2931

    
2932
    if (version_id != 3)
2933
        return -EINVAL;
2934

    
2935
    do {
2936
        addr = qemu_get_be64(f);
2937

    
2938
        flags = addr & ~TARGET_PAGE_MASK;
2939
        addr &= TARGET_PAGE_MASK;
2940

    
2941
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2942
            if (addr != last_ram_offset)
2943
                return -EINVAL;
2944
        }
2945

    
2946
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2947
            uint8_t ch = qemu_get_byte(f);
2948
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2949
#ifndef _WIN32
2950
            if (ch == 0 &&
2951
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2952
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2953
            }
2954
#endif
2955
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
2956
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2957
        }
2958
        if (qemu_file_has_error(f)) {
2959
            return -EIO;
2960
        }
2961
    } while (!(flags & RAM_SAVE_FLAG_EOS));
2962

    
2963
    return 0;
2964
}
2965

    
2966
void qemu_service_io(void)
2967
{
2968
    qemu_notify_event();
2969
}
2970

    
2971
/***********************************************************/
2972
/* machine registration */
2973

    
2974
static QEMUMachine *first_machine = NULL;
2975
QEMUMachine *current_machine = NULL;
2976

    
2977
int qemu_register_machine(QEMUMachine *m)
2978
{
2979
    QEMUMachine **pm;
2980
    pm = &first_machine;
2981
    while (*pm != NULL)
2982
        pm = &(*pm)->next;
2983
    m->next = NULL;
2984
    *pm = m;
2985
    return 0;
2986
}
2987

    
2988
static QEMUMachine *find_machine(const char *name)
2989
{
2990
    QEMUMachine *m;
2991

    
2992
    for(m = first_machine; m != NULL; m = m->next) {
2993
        if (!strcmp(m->name, name))
2994
            return m;
2995
        if (m->alias && !strcmp(m->alias, name))
2996
            return m;
2997
    }
2998
    return NULL;
2999
}
3000

    
3001
static QEMUMachine *find_default_machine(void)
3002
{
3003
    QEMUMachine *m;
3004

    
3005
    for(m = first_machine; m != NULL; m = m->next) {
3006
        if (m->is_default) {
3007
            return m;
3008
        }
3009
    }
3010
    return NULL;
3011
}
3012

    
3013
/***********************************************************/
3014
/* main execution loop */
3015

    
3016
static void gui_update(void *opaque)
3017
{
3018
    uint64_t interval = GUI_REFRESH_INTERVAL;
3019
    DisplayState *ds = opaque;
3020
    DisplayChangeListener *dcl = ds->listeners;
3021

    
3022
    qemu_flush_coalesced_mmio_buffer();
3023
    dpy_refresh(ds);
3024

    
3025
    while (dcl != NULL) {
3026
        if (dcl->gui_timer_interval &&
3027
            dcl->gui_timer_interval < interval)
3028
            interval = dcl->gui_timer_interval;
3029
        dcl = dcl->next;
3030
    }
3031
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3032
}
3033

    
3034
static void nographic_update(void *opaque)
3035
{
3036
    uint64_t interval = GUI_REFRESH_INTERVAL;
3037

    
3038
    qemu_flush_coalesced_mmio_buffer();
3039
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3040
}
3041

    
3042
struct vm_change_state_entry {
3043
    VMChangeStateHandler *cb;
3044
    void *opaque;
3045
    QLIST_ENTRY (vm_change_state_entry) entries;
3046
};
3047

    
3048
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3049

    
3050
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3051
                                                     void *opaque)
3052
{
3053
    VMChangeStateEntry *e;
3054

    
3055
    e = qemu_mallocz(sizeof (*e));
3056

    
3057
    e->cb = cb;
3058
    e->opaque = opaque;
3059
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3060
    return e;
3061
}
3062

    
3063
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3064
{
3065
    QLIST_REMOVE (e, entries);
3066
    qemu_free (e);
3067
}
3068

    
3069
static void vm_state_notify(int running, int reason)
3070
{
3071
    VMChangeStateEntry *e;
3072

    
3073
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3074
        e->cb(e->opaque, running, reason);
3075
    }
3076
}
3077

    
3078
static void resume_all_vcpus(void);
3079
static void pause_all_vcpus(void);
3080

    
3081
void vm_start(void)
3082
{
3083
    if (!vm_running) {
3084
        cpu_enable_ticks();
3085
        vm_running = 1;
3086
        vm_state_notify(1, 0);
3087
        qemu_rearm_alarm_timer(alarm_timer);
3088
        resume_all_vcpus();
3089
    }
3090
}
3091

    
3092
/* reset/shutdown handler */
3093

    
3094
typedef struct QEMUResetEntry {
3095
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3096
    QEMUResetHandler *func;
3097
    void *opaque;
3098
} QEMUResetEntry;
3099

    
3100
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3101
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3102
static int reset_requested;
3103
static int shutdown_requested;
3104
static int powerdown_requested;
3105
static int debug_requested;
3106
static int vmstop_requested;
3107

    
3108
int qemu_shutdown_requested(void)
3109
{
3110
    int r = shutdown_requested;
3111
    shutdown_requested = 0;
3112
    return r;
3113
}
3114

    
3115
int qemu_reset_requested(void)
3116
{
3117
    int r = reset_requested;
3118
    reset_requested = 0;
3119
    return r;
3120
}
3121

    
3122
int qemu_powerdown_requested(void)
3123
{
3124
    int r = powerdown_requested;
3125
    powerdown_requested = 0;
3126
    return r;
3127
}
3128

    
3129
static int qemu_debug_requested(void)
3130
{
3131
    int r = debug_requested;
3132
    debug_requested = 0;
3133
    return r;
3134
}
3135

    
3136
static int qemu_vmstop_requested(void)
3137
{
3138
    int r = vmstop_requested;
3139
    vmstop_requested = 0;
3140
    return r;
3141
}
3142

    
3143
static void do_vm_stop(int reason)
3144
{
3145
    if (vm_running) {
3146
        cpu_disable_ticks();
3147
        vm_running = 0;
3148
        pause_all_vcpus();
3149
        vm_state_notify(0, reason);
3150
    }
3151
}
3152

    
3153
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3154
{
3155
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3156

    
3157
    re->func = func;
3158
    re->opaque = opaque;
3159
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3160
}
3161

    
3162
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3163
{
3164
    QEMUResetEntry *re;
3165

    
3166
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3167
        if (re->func == func && re->opaque == opaque) {
3168
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3169
            qemu_free(re);
3170
            return;
3171
        }
3172
    }
3173
}
3174

    
3175
void qemu_system_reset(void)
3176
{
3177
    QEMUResetEntry *re, *nre;
3178

    
3179
    /* reset all devices */
3180
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3181
        re->func(re->opaque);
3182
    }
3183
}
3184

    
3185
void qemu_system_reset_request(void)
3186
{
3187
    if (no_reboot) {
3188
        shutdown_requested = 1;
3189
    } else {
3190
        reset_requested = 1;
3191
    }
3192
    qemu_notify_event();
3193
}
3194

    
3195
void qemu_system_shutdown_request(void)
3196
{
3197
    shutdown_requested = 1;
3198
    qemu_notify_event();
3199
}
3200

    
3201
void qemu_system_powerdown_request(void)
3202
{
3203
    powerdown_requested = 1;
3204
    qemu_notify_event();
3205
}
3206

    
3207
#ifdef CONFIG_IOTHREAD
3208
static void qemu_system_vmstop_request(int reason)
3209
{
3210
    vmstop_requested = reason;
3211
    qemu_notify_event();
3212
}
3213
#endif
3214

    
3215
#ifndef _WIN32
3216
static int io_thread_fd = -1;
3217

    
3218
static void qemu_event_increment(void)
3219
{
3220
    /* Write 8 bytes to be compatible with eventfd.  */
3221
    static uint64_t val = 1;
3222
    ssize_t ret;
3223

    
3224
    if (io_thread_fd == -1)
3225
        return;
3226

    
3227
    do {
3228
        ret = write(io_thread_fd, &val, sizeof(val));
3229
    } while (ret < 0 && errno == EINTR);
3230

    
3231
    /* EAGAIN is fine, a read must be pending.  */
3232
    if (ret < 0 && errno != EAGAIN) {
3233
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3234
                strerror(errno));
3235
        exit (1);
3236
    }
3237
}
3238

    
3239
static void qemu_event_read(void *opaque)
3240
{
3241
    int fd = (unsigned long)opaque;
3242
    ssize_t len;
3243
    char buffer[512];
3244

    
3245
    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
3246
    do {
3247
        len = read(fd, buffer, sizeof(buffer));
3248
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3249
}
3250

    
3251
static int qemu_event_init(void)
3252
{
3253
    int err;
3254
    int fds[2];
3255

    
3256
    err = qemu_eventfd(fds);
3257
    if (err == -1)
3258
        return -errno;
3259

    
3260
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3261
    if (err < 0)
3262
        goto fail;
3263

    
3264
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3265
    if (err < 0)
3266
        goto fail;
3267

    
3268
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3269
                         (void *)(unsigned long)fds[0]);
3270

    
3271
    io_thread_fd = fds[1];
3272
    return 0;
3273

    
3274
fail:
3275
    close(fds[0]);
3276
    close(fds[1]);
3277
    return err;
3278
}
3279
#else
3280
HANDLE qemu_event_handle;
3281

    
3282
static void dummy_event_handler(void *opaque)
3283
{
3284
}
3285

    
3286
static int qemu_event_init(void)
3287
{
3288
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3289
    if (!qemu_event_handle) {
3290
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3291
        return -1;
3292
    }
3293
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3294
    return 0;
3295
}
3296

    
3297
static void qemu_event_increment(void)
3298
{
3299
    if (!SetEvent(qemu_event_handle)) {
3300
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3301
                GetLastError());
3302
        exit (1);
3303
    }
3304
}
3305
#endif
3306

    
3307
static int cpu_can_run(CPUState *env)
3308
{
3309
    if (env->stop)
3310
        return 0;
3311
    if (env->stopped)
3312
        return 0;
3313
    if (!vm_running)
3314
        return 0;
3315
    return 1;
3316
}
3317

    
3318
#ifndef CONFIG_IOTHREAD
3319
static int qemu_init_main_loop(void)
3320
{
3321
    return qemu_event_init();
3322
}
3323

    
3324
void qemu_init_vcpu(void *_env)
3325
{
3326
    CPUState *env = _env;
3327

    
3328
    env->nr_cores = smp_cores;
3329
    env->nr_threads = smp_threads;
3330
    if (kvm_enabled())
3331
        kvm_init_vcpu(env);
3332
    return;
3333
}
3334

    
3335
int qemu_cpu_self(void *env)
3336
{
3337
    return 1;
3338
}
3339

    
3340
static void resume_all_vcpus(void)
3341
{
3342
}
3343

    
3344
static void pause_all_vcpus(void)
3345
{
3346
}
3347

    
3348
void qemu_cpu_kick(void *env)
3349
{
3350
    return;
3351
}
3352

    
3353
void qemu_notify_event(void)
3354
{
3355
    CPUState *env = cpu_single_env;
3356

    
3357
    if (env) {
3358
        cpu_exit(env);
3359
    }
3360
}
3361

    
3362
void qemu_mutex_lock_iothread(void) {}
3363
void qemu_mutex_unlock_iothread(void) {}
3364

    
3365
void vm_stop(int reason)
3366
{
3367
    do_vm_stop(reason);
3368
}
3369

    
3370
#else /* CONFIG_IOTHREAD */
3371

    
3372
#include "qemu-thread.h"
3373

    
3374
QemuMutex qemu_global_mutex;
3375
static QemuMutex qemu_fair_mutex;
3376

    
3377
static QemuThread io_thread;
3378

    
3379
static QemuThread *tcg_cpu_thread;
3380
static QemuCond *tcg_halt_cond;
3381

    
3382
static int qemu_system_ready;
3383
/* cpu creation */
3384
static QemuCond qemu_cpu_cond;
3385
/* system init */
3386
static QemuCond qemu_system_cond;
3387
static QemuCond qemu_pause_cond;
3388

    
3389
static void tcg_block_io_signals(void);
3390
static void kvm_block_io_signals(CPUState *env);
3391
static void unblock_io_signals(void);
3392
static int tcg_has_work(void);
3393
static int cpu_has_work(CPUState *env);
3394

    
3395
static int qemu_init_main_loop(void)
3396
{
3397
    int ret;
3398

    
3399
    ret = qemu_event_init();
3400
    if (ret)
3401
        return ret;
3402

    
3403
    qemu_cond_init(&qemu_pause_cond);
3404
    qemu_mutex_init(&qemu_fair_mutex);
3405
    qemu_mutex_init(&qemu_global_mutex);
3406
    qemu_mutex_lock(&qemu_global_mutex);
3407

    
3408
    unblock_io_signals();
3409
    qemu_thread_self(&io_thread);
3410

    
3411
    return 0;
3412
}
3413

    
3414
static void qemu_wait_io_event_common(CPUState *env)
3415
{
3416
    if (env->stop) {
3417
        env->stop = 0;
3418
        env->stopped = 1;
3419
        qemu_cond_signal(&qemu_pause_cond);
3420
    }
3421
}
3422

    
3423
static void qemu_wait_io_event(CPUState *env)
3424
{
3425
    while (!tcg_has_work())
3426
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3427

    
3428
    qemu_mutex_unlock(&qemu_global_mutex);
3429

    
3430
    /*
3431
     * Users of qemu_global_mutex can be starved, having no chance
3432
     * to acquire it since this path will get to it first.
3433
     * So use another lock to provide fairness.
3434
     */
3435
    qemu_mutex_lock(&qemu_fair_mutex);
3436
    qemu_mutex_unlock(&qemu_fair_mutex);
3437

    
3438
    qemu_mutex_lock(&qemu_global_mutex);
3439
    qemu_wait_io_event_common(env);
3440
}
3441

    
3442
static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3443
{
3444
    struct timespec ts;
3445
    int r, e;
3446
    siginfo_t siginfo;
3447
    sigset_t waitset;
3448

    
3449
    ts.tv_sec = timeout / 1000;
3450
    ts.tv_nsec = (timeout % 1000) * 1000000;
3451

    
3452
    sigemptyset(&waitset);
3453
    sigaddset(&waitset, SIG_IPI);
3454

    
3455
    qemu_mutex_unlock(&qemu_global_mutex);
3456
    r = sigtimedwait(&waitset, &siginfo, &ts);
3457
    e = errno;
3458
    qemu_mutex_lock(&qemu_global_mutex);
3459

    
3460
    if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3461
        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3462
        exit(1);
3463
    }
3464
}
3465

    
3466
static void qemu_kvm_wait_io_event(CPUState *env)
3467
{
3468
    while (!cpu_has_work(env))
3469
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3470

    
3471
    qemu_kvm_eat_signal(env, 0);
3472
    qemu_wait_io_event_common(env);
3473
}
3474

    
3475
static int qemu_cpu_exec(CPUState *env);
3476

    
3477
static void *kvm_cpu_thread_fn(void *arg)
3478
{
3479
    CPUState *env = arg;
3480

    
3481
    qemu_thread_self(env->thread);
3482
    if (kvm_enabled())
3483
        kvm_init_vcpu(env);
3484

    
3485
    kvm_block_io_signals(env);
3486

    
3487
    /* signal CPU creation */
3488
    qemu_mutex_lock(&qemu_global_mutex);
3489
    env->created = 1;
3490
    qemu_cond_signal(&qemu_cpu_cond);
3491

    
3492
    /* and wait for machine initialization */
3493
    while (!qemu_system_ready)
3494
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3495

    
3496
    while (1) {
3497
        if (cpu_can_run(env))
3498
            qemu_cpu_exec(env);
3499
        qemu_kvm_wait_io_event(env);
3500
    }
3501

    
3502
    return NULL;
3503
}
3504

    
3505
static void tcg_cpu_exec(void);
3506

    
3507
static void *tcg_cpu_thread_fn(void *arg)
3508
{
3509
    CPUState *env = arg;
3510

    
3511
    tcg_block_io_signals();
3512
    qemu_thread_self(env->thread);
3513

    
3514
    /* signal CPU creation */
3515
    qemu_mutex_lock(&qemu_global_mutex);
3516
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3517
        env->created = 1;
3518
    qemu_cond_signal(&qemu_cpu_cond);
3519

    
3520
    /* and wait for machine initialization */
3521
    while (!qemu_system_ready)
3522
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3523

    
3524
    while (1) {
3525
        tcg_cpu_exec();
3526
        qemu_wait_io_event(cur_cpu);
3527
    }
3528

    
3529
    return NULL;
3530
}
3531

    
3532
void qemu_cpu_kick(void *_env)
3533
{
3534
    CPUState *env = _env;
3535
    qemu_cond_broadcast(env->halt_cond);
3536
    if (kvm_enabled())
3537
        qemu_thread_signal(env->thread, SIG_IPI);
3538
}
3539

    
3540
int qemu_cpu_self(void *_env)
3541
{
3542
    CPUState *env = _env;
3543
    QemuThread this;
3544
 
3545
    qemu_thread_self(&this);
3546
 
3547
    return qemu_thread_equal(&this, env->thread);
3548
}
3549

    
3550
static void cpu_signal(int sig)
3551
{
3552
    if (cpu_single_env)
3553
        cpu_exit(cpu_single_env);
3554
}
3555

    
3556
static void tcg_block_io_signals(void)
3557
{
3558
    sigset_t set;
3559
    struct sigaction sigact;
3560

    
3561
    sigemptyset(&set);
3562
    sigaddset(&set, SIGUSR2);
3563
    sigaddset(&set, SIGIO);
3564
    sigaddset(&set, SIGALRM);
3565
    sigaddset(&set, SIGCHLD);
3566
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3567

    
3568
    sigemptyset(&set);
3569
    sigaddset(&set, SIG_IPI);
3570
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3571

    
3572
    memset(&sigact, 0, sizeof(sigact));
3573
    sigact.sa_handler = cpu_signal;
3574
    sigaction(SIG_IPI, &sigact, NULL);
3575
}
3576

    
3577
static void dummy_signal(int sig)
3578
{
3579
}
3580

    
3581
static void kvm_block_io_signals(CPUState *env)
3582
{
3583
    int r;
3584
    sigset_t set;
3585
    struct sigaction sigact;
3586

    
3587
    sigemptyset(&set);
3588
    sigaddset(&set, SIGUSR2);
3589
    sigaddset(&set, SIGIO);
3590
    sigaddset(&set, SIGALRM);
3591
    sigaddset(&set, SIGCHLD);
3592
    sigaddset(&set, SIG_IPI);
3593
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3594

    
3595
    pthread_sigmask(SIG_BLOCK, NULL, &set);
3596
    sigdelset(&set, SIG_IPI);
3597

    
3598
    memset(&sigact, 0, sizeof(sigact));
3599
    sigact.sa_handler = dummy_signal;
3600
    sigaction(SIG_IPI, &sigact, NULL);
3601

    
3602
    r = kvm_set_signal_mask(env, &set);
3603
    if (r) {
3604
        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3605
        exit(1);
3606
    }
3607
}
3608

    
3609
static void unblock_io_signals(void)
3610
{
3611
    sigset_t set;
3612

    
3613
    sigemptyset(&set);
3614
    sigaddset(&set, SIGUSR2);
3615
    sigaddset(&set, SIGIO);
3616
    sigaddset(&set, SIGALRM);
3617
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3618

    
3619
    sigemptyset(&set);
3620
    sigaddset(&set, SIG_IPI);
3621
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3622
}
3623

    
3624
static void qemu_signal_lock(unsigned int msecs)
3625
{
3626
    qemu_mutex_lock(&qemu_fair_mutex);
3627

    
3628
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3629
        qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3630
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3631
            break;
3632
    }
3633
    qemu_mutex_unlock(&qemu_fair_mutex);
3634
}
3635

    
3636
void qemu_mutex_lock_iothread(void)
3637
{
3638
    if (kvm_enabled()) {
3639
        qemu_mutex_lock(&qemu_fair_mutex);
3640
        qemu_mutex_lock(&qemu_global_mutex);
3641
        qemu_mutex_unlock(&qemu_fair_mutex);
3642
    } else
3643
        qemu_signal_lock(100);
3644
}
3645

    
3646
void qemu_mutex_unlock_iothread(void)
3647
{
3648
    qemu_mutex_unlock(&qemu_global_mutex);
3649
}
3650

    
3651
static int all_vcpus_paused(void)
3652
{
3653
    CPUState *penv = first_cpu;
3654

    
3655
    while (penv) {
3656
        if (!penv->stopped)
3657
            return 0;
3658
        penv = (CPUState *)penv->next_cpu;
3659
    }
3660

    
3661
    return 1;
3662
}
3663

    
3664
static void pause_all_vcpus(void)
3665
{
3666
    CPUState *penv = first_cpu;
3667

    
3668
    while (penv) {
3669
        penv->stop = 1;
3670
        qemu_thread_signal(penv->thread, SIG_IPI);
3671
        qemu_cpu_kick(penv);
3672
        penv = (CPUState *)penv->next_cpu;
3673
    }
3674

    
3675
    while (!all_vcpus_paused()) {
3676
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3677
        penv = first_cpu;
3678
        while (penv) {
3679
            qemu_thread_signal(penv->thread, SIG_IPI);
3680
            penv = (CPUState *)penv->next_cpu;
3681
        }
3682
    }
3683
}
3684

    
3685
static void resume_all_vcpus(void)
3686
{
3687
    CPUState *penv = first_cpu;
3688

    
3689
    while (penv) {
3690
        penv->stop = 0;
3691
        penv->stopped = 0;
3692
        qemu_thread_signal(penv->thread, SIG_IPI);
3693
        qemu_cpu_kick(penv);
3694
        penv = (CPUState *)penv->next_cpu;
3695
    }
3696
}
3697

    
3698
static void tcg_init_vcpu(void *_env)
3699
{
3700
    CPUState *env = _env;
3701
    /* share a single thread for all cpus with TCG */
3702
    if (!tcg_cpu_thread) {
3703
        env->thread = qemu_mallocz(sizeof(QemuThread));
3704
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3705
        qemu_cond_init(env->halt_cond);
3706
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3707
        while (env->created == 0)
3708
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3709
        tcg_cpu_thread = env->thread;
3710
        tcg_halt_cond = env->halt_cond;
3711
    } else {
3712
        env->thread = tcg_cpu_thread;
3713
        env->halt_cond = tcg_halt_cond;
3714
    }
3715
}
3716

    
3717
static void kvm_start_vcpu(CPUState *env)
3718
{
3719
    env->thread = qemu_mallocz(sizeof(QemuThread));
3720
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3721
    qemu_cond_init(env->halt_cond);
3722
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3723
    while (env->created == 0)
3724
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3725
}
3726

    
3727
void qemu_init_vcpu(void *_env)
3728
{
3729
    CPUState *env = _env;
3730

    
3731
    env->nr_cores = smp_cores;
3732
    env->nr_threads = smp_threads;
3733
    if (kvm_enabled())
3734
        kvm_start_vcpu(env);
3735
    else
3736
        tcg_init_vcpu(env);
3737
}
3738

    
3739
void qemu_notify_event(void)
3740
{
3741
    qemu_event_increment();
3742
}
3743

    
3744
void vm_stop(int reason)
3745
{
3746
    QemuThread me;
3747
    qemu_thread_self(&me);
3748

    
3749
    if (!qemu_thread_equal(&me, &io_thread)) {
3750
        qemu_system_vmstop_request(reason);
3751
        /*
3752
         * FIXME: should not return to device code in case
3753
         * vm_stop() has been requested.
3754
         */
3755
        if (cpu_single_env) {
3756
            cpu_exit(cpu_single_env);
3757
            cpu_single_env->stop = 1;
3758
        }
3759
        return;
3760
    }
3761
    do_vm_stop(reason);
3762
}
3763

    
3764
#endif
3765

    
3766

    
3767
#ifdef _WIN32
3768
static void host_main_loop_wait(int *timeout)
3769
{
3770
    int ret, ret2, i;
3771
    PollingEntry *pe;
3772

    
3773

    
3774
    /* XXX: need to suppress polling by better using win32 events */
3775
    ret = 0;
3776
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3777
        ret |= pe->func(pe->opaque);
3778
    }
3779
    if (ret == 0) {
3780
        int err;
3781
        WaitObjects *w = &wait_objects;
3782

    
3783
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3784
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3785
            if (w->func[ret - WAIT_OBJECT_0])
3786
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3787

    
3788
            /* Check for additional signaled events */
3789
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3790

    
3791
                /* Check if event is signaled */
3792
                ret2 = WaitForSingleObject(w->events[i], 0);
3793
                if(ret2 == WAIT_OBJECT_0) {
3794
                    if (w->func[i])
3795
                        w->func[i](w->opaque[i]);
3796
                } else if (ret2 == WAIT_TIMEOUT) {
3797
                } else {
3798
                    err = GetLastError();
3799
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3800
                }
3801
            }
3802
        } else if (ret == WAIT_TIMEOUT) {
3803
        } else {
3804
            err = GetLastError();
3805
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3806
        }
3807
    }
3808

    
3809
    *timeout = 0;
3810
}
3811
#else
3812
static void host_main_loop_wait(int *timeout)
3813
{
3814
}
3815
#endif
3816

    
3817
void main_loop_wait(int timeout)
3818
{
3819
    IOHandlerRecord *ioh;
3820
    fd_set rfds, wfds, xfds;
3821
    int ret, nfds;
3822
    struct timeval tv;
3823

    
3824
    qemu_bh_update_timeout(&timeout);
3825

    
3826
    host_main_loop_wait(&timeout);
3827

    
3828
    /* poll any events */
3829
    /* XXX: separate device handlers from system ones */
3830
    nfds = -1;
3831
    FD_ZERO(&rfds);
3832
    FD_ZERO(&wfds);
3833
    FD_ZERO(&xfds);
3834
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3835
        if (ioh->deleted)
3836
            continue;
3837
        if (ioh->fd_read &&
3838
            (!ioh->fd_read_poll ||
3839
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3840
            FD_SET(ioh->fd, &rfds);
3841
            if (ioh->fd > nfds)
3842
                nfds = ioh->fd;
3843
        }
3844
        if (ioh->fd_write) {
3845
            FD_SET(ioh->fd, &wfds);
3846
            if (ioh->fd > nfds)
3847
                nfds = ioh->fd;
3848
        }
3849
    }
3850

    
3851
    tv.tv_sec = timeout / 1000;
3852
    tv.tv_usec = (timeout % 1000) * 1000;
3853

    
3854
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3855

    
3856
    qemu_mutex_unlock_iothread();
3857
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3858
    qemu_mutex_lock_iothread();
3859
    if (ret > 0) {
3860
        IOHandlerRecord **pioh;
3861

    
3862
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3863
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3864
                ioh->fd_read(ioh->opaque);
3865
            }
3866
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3867
                ioh->fd_write(ioh->opaque);
3868
            }
3869
        }
3870

    
3871
        /* remove deleted IO handlers */
3872
        pioh = &first_io_handler;
3873
        while (*pioh) {
3874
            ioh = *pioh;
3875
            if (ioh->deleted) {
3876
                *pioh = ioh->next;
3877
                qemu_free(ioh);
3878
            } else
3879
                pioh = &ioh->next;
3880
        }
3881
    }
3882

    
3883
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3884

    
3885
    /* rearm timer, if not periodic */
3886
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3887
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3888
        qemu_rearm_alarm_timer(alarm_timer);
3889
    }
3890

    
3891
    /* vm time timers */
3892
    if (vm_running) {
3893
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3894
            qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3895
                            qemu_get_clock(vm_clock));
3896
    }
3897

    
3898
    /* real time timers */
3899
    qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3900
                    qemu_get_clock(rt_clock));
3901

    
3902
    qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3903
                    qemu_get_clock(host_clock));
3904

    
3905
    /* Check bottom-halves last in case any of the earlier events triggered
3906
       them.  */
3907
    qemu_bh_poll();
3908

    
3909
}
3910

    
3911
static int qemu_cpu_exec(CPUState *env)
3912
{
3913
    int ret;
3914
#ifdef CONFIG_PROFILER
3915
    int64_t ti;
3916
#endif
3917

    
3918
#ifdef CONFIG_PROFILER
3919
    ti = profile_getclock();
3920
#endif
3921
    if (use_icount) {
3922
        int64_t count;
3923
        int decr;
3924
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3925
        env->icount_decr.u16.low = 0;
3926
        env->icount_extra = 0;
3927
        count = qemu_next_deadline();
3928
        count = (count + (1 << icount_time_shift) - 1)
3929
                >> icount_time_shift;
3930
        qemu_icount += count;
3931
        decr = (count > 0xffff) ? 0xffff : count;
3932
        count -= decr;
3933
        env->icount_decr.u16.low = decr;
3934
        env->icount_extra = count;
3935
    }
3936
    ret = cpu_exec(env);
3937
#ifdef CONFIG_PROFILER
3938
    qemu_time += profile_getclock() - ti;
3939
#endif
3940
    if (use_icount) {
3941
        /* Fold pending instructions back into the
3942
           instruction counter, and clear the interrupt flag.  */
3943
        qemu_icount -= (env->icount_decr.u16.low
3944
                        + env->icount_extra);
3945
        env->icount_decr.u32 = 0;
3946
        env->icount_extra = 0;
3947
    }
3948
    return ret;
3949
}
3950

    
3951
static void tcg_cpu_exec(void)
3952
{
3953
    int ret = 0;
3954

    
3955
    if (next_cpu == NULL)
3956
        next_cpu = first_cpu;
3957
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3958
        CPUState *env = cur_cpu = next_cpu;
3959

    
3960
        if (timer_alarm_pending) {
3961
            timer_alarm_pending = 0;
3962
            break;
3963
        }
3964
        if (cpu_can_run(env))
3965
            ret = qemu_cpu_exec(env);
3966
        else if (env->stop)
3967
            break;
3968

    
3969
        if (ret == EXCP_DEBUG) {
3970
            gdb_set_stop_cpu(env);
3971
            debug_requested = 1;
3972
            break;
3973
        }
3974
    }
3975
}
3976

    
3977
static int cpu_has_work(CPUState *env)
3978
{
3979
    if (env->stop)
3980
        return 1;
3981
    if (env->stopped)
3982
        return 0;
3983
    if (!env->halted)
3984
        return 1;
3985
    if (qemu_cpu_has_work(env))
3986
        return 1;
3987
    return 0;
3988
}
3989

    
3990
static int tcg_has_work(void)
3991
{
3992
    CPUState *env;
3993

    
3994
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3995
        if (cpu_has_work(env))
3996
            return 1;
3997
    return 0;
3998
}
3999

    
4000
static int qemu_calculate_timeout(void)
4001
{
4002
#ifndef CONFIG_IOTHREAD
4003
    int timeout;
4004

    
4005
    if (!vm_running)
4006
        timeout = 5000;
4007
    else if (tcg_has_work())
4008
        timeout = 0;
4009
    else if (!use_icount)
4010
        timeout = 5000;
4011
    else {
4012
     /* XXX: use timeout computed from timers */
4013
        int64_t add;
4014
        int64_t delta;
4015
        /* Advance virtual time to the next event.  */
4016
        if (use_icount == 1) {
4017
            /* When not using an adaptive execution frequency
4018
               we tend to get badly out of sync with real time,
4019
               so just delay for a reasonable amount of time.  */
4020
            delta = 0;
4021
        } else {
4022
            delta = cpu_get_icount() - cpu_get_clock();
4023
        }
4024
        if (delta > 0) {
4025
            /* If virtual time is ahead of real time then just
4026
               wait for IO.  */
4027
            timeout = (delta / 1000000) + 1;
4028
        } else {
4029
            /* Wait for either IO to occur or the next
4030
               timer event.  */
4031
            add = qemu_next_deadline();
4032
            /* We advance the timer before checking for IO.
4033
               Limit the amount we advance so that early IO
4034
               activity won't get the guest too far ahead.  */
4035
            if (add > 10000000)
4036
                add = 10000000;
4037
            delta += add;
4038
            add = (add + (1 << icount_time_shift) - 1)
4039
                  >> icount_time_shift;
4040
            qemu_icount += add;
4041
            timeout = delta / 1000000;
4042
            if (timeout < 0)
4043
                timeout = 0;
4044
        }
4045
    }
4046

    
4047
    return timeout;
4048
#else /* CONFIG_IOTHREAD */
4049
    return 1000;
4050
#endif
4051
}
4052

    
4053
static int vm_can_run(void)
4054
{
4055
    if (powerdown_requested)
4056
        return 0;
4057
    if (reset_requested)
4058
        return 0;
4059
    if (shutdown_requested)
4060
        return 0;
4061
    if (debug_requested)
4062
        return 0;
4063
    return 1;
4064
}
4065

    
4066
qemu_irq qemu_system_powerdown;
4067

    
4068
static void main_loop(void)
4069
{
4070
    int r;
4071

    
4072
#ifdef CONFIG_IOTHREAD
4073
    qemu_system_ready = 1;
4074
    qemu_cond_broadcast(&qemu_system_cond);
4075
#endif
4076

    
4077
    for (;;) {
4078
        do {
4079
#ifdef CONFIG_PROFILER
4080
            int64_t ti;
4081
#endif
4082
#ifndef CONFIG_IOTHREAD
4083
            tcg_cpu_exec();
4084
#endif
4085
#ifdef CONFIG_PROFILER
4086
            ti = profile_getclock();
4087
#endif
4088
            main_loop_wait(qemu_calculate_timeout());
4089
#ifdef CONFIG_PROFILER
4090
            dev_time += profile_getclock() - ti;
4091
#endif
4092
        } while (vm_can_run());
4093

    
4094
        if (qemu_debug_requested()) {
4095
            monitor_protocol_event(QEVENT_DEBUG, NULL);
4096
            vm_stop(EXCP_DEBUG);
4097
        }
4098
        if (qemu_shutdown_requested()) {
4099
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4100
            if (no_shutdown) {
4101
                vm_stop(0);
4102
                no_shutdown = 0;
4103
            } else
4104
                break;
4105
        }
4106
        if (qemu_reset_requested()) {
4107
            monitor_protocol_event(QEVENT_RESET, NULL);
4108
            pause_all_vcpus();
4109
            qemu_system_reset();
4110
            resume_all_vcpus();
4111
        }
4112
        if (qemu_powerdown_requested()) {
4113
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4114
            qemu_irq_raise(qemu_system_powerdown);
4115
        }
4116
        if ((r = qemu_vmstop_requested())) {
4117
            monitor_protocol_event(QEVENT_STOP, NULL);
4118
            vm_stop(r);
4119
        }
4120
    }
4121
    pause_all_vcpus();
4122
}
4123

    
4124
static void version(void)
4125
{
4126
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4127
}
4128

    
4129
static void help(int exitcode)
4130
{
4131
    const char *options_help =
4132
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4133
           opt_help
4134
#define DEFHEADING(text) stringify(text) "\n"
4135
#include "qemu-options.h"
4136
#undef DEF
4137
#undef DEFHEADING
4138
#undef GEN_DOCS
4139
        ;
4140
    version();
4141
    printf("usage: %s [options] [disk_image]\n"
4142
           "\n"
4143
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4144
           "\n"
4145
           "%s\n"
4146
           "During emulation, the following keys are useful:\n"
4147
           "ctrl-alt-f      toggle full screen\n"
4148
           "ctrl-alt-n      switch to virtual console 'n'\n"
4149
           "ctrl-alt        toggle mouse and keyboard grab\n"
4150
           "\n"
4151
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
4152
           "qemu",
4153
           options_help);
4154
    exit(exitcode);
4155
}
4156

    
4157
#define HAS_ARG 0x0001
4158

    
4159
enum {
4160
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4161
    opt_enum,
4162
#define DEFHEADING(text)
4163
#include "qemu-options.h"
4164
#undef DEF
4165
#undef DEFHEADING
4166
#undef GEN_DOCS
4167
};
4168

    
4169
typedef struct QEMUOption {
4170
    const char *name;
4171
    int flags;
4172
    int index;
4173
} QEMUOption;
4174

    
4175
static const QEMUOption qemu_options[] = {
4176
    { "h", 0, QEMU_OPTION_h },
4177
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4178
    { option, opt_arg, opt_enum },
4179
#define DEFHEADING(text)
4180
#include "qemu-options.h"
4181
#undef DEF
4182
#undef DEFHEADING
4183
#undef GEN_DOCS
4184
    { NULL },
4185
};
4186

    
4187
#ifdef HAS_AUDIO
4188
struct soundhw soundhw[] = {
4189
#ifdef HAS_AUDIO_CHOICE
4190
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4191
    {
4192
        "pcspk",
4193
        "PC speaker",
4194
        0,
4195
        1,
4196
        { .init_isa = pcspk_audio_init }
4197
    },
4198
#endif
4199

    
4200
#ifdef CONFIG_SB16
4201
    {
4202
        "sb16",
4203
        "Creative Sound Blaster 16",
4204
        0,
4205
        1,
4206
        { .init_isa = SB16_init }
4207
    },
4208
#endif
4209

    
4210
#ifdef CONFIG_CS4231A
4211
    {
4212
        "cs4231a",
4213
        "CS4231A",
4214
        0,
4215
        1,
4216
        { .init_isa = cs4231a_init }
4217
    },
4218
#endif
4219

    
4220
#ifdef CONFIG_ADLIB
4221
    {
4222
        "adlib",
4223
#ifdef HAS_YMF262
4224
        "Yamaha YMF262 (OPL3)",
4225
#else
4226
        "Yamaha YM3812 (OPL2)",
4227
#endif
4228
        0,
4229
        1,
4230
        { .init_isa = Adlib_init }
4231
    },
4232
#endif
4233

    
4234
#ifdef CONFIG_GUS
4235
    {
4236
        "gus",
4237
        "Gravis Ultrasound GF1",
4238
        0,
4239
        1,
4240
        { .init_isa = GUS_init }
4241
    },
4242
#endif
4243

    
4244
#ifdef CONFIG_AC97
4245
    {
4246
        "ac97",
4247
        "Intel 82801AA AC97 Audio",
4248
        0,
4249
        0,
4250
        { .init_pci = ac97_init }
4251
    },
4252
#endif
4253

    
4254
#ifdef CONFIG_ES1370
4255
    {
4256
        "es1370",
4257
        "ENSONIQ AudioPCI ES1370",
4258
        0,
4259
        0,
4260
        { .init_pci = es1370_init }
4261
    },
4262
#endif
4263

    
4264
#endif /* HAS_AUDIO_CHOICE */
4265

    
4266
    { NULL, NULL, 0, 0, { NULL } }
4267
};
4268

    
4269
static void select_soundhw (const char *optarg)
4270
{
4271
    struct soundhw *c;
4272

    
4273
    if (*optarg == '?') {
4274
    show_valid_cards:
4275

    
4276
        printf ("Valid sound card names (comma separated):\n");
4277
        for (c = soundhw; c->name; ++c) {
4278
            printf ("%-11s %s\n", c->name, c->descr);
4279
        }
4280
        printf ("\n-soundhw all will enable all of the above\n");
4281
        exit (*optarg != '?');
4282
    }
4283
    else {
4284
        size_t l;
4285
        const char *p;
4286
        char *e;
4287
        int bad_card = 0;
4288

    
4289
        if (!strcmp (optarg, "all")) {
4290
            for (c = soundhw; c->name; ++c) {
4291
                c->enabled = 1;
4292
            }
4293
            return;
4294
        }
4295

    
4296
        p = optarg;
4297
        while (*p) {
4298
            e = strchr (p, ',');
4299
            l = !e ? strlen (p) : (size_t) (e - p);
4300

    
4301
            for (c = soundhw; c->name; ++c) {
4302
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4303
                    c->enabled = 1;
4304
                    break;
4305
                }
4306
            }
4307

    
4308
            if (!c->name) {
4309
                if (l > 80) {
4310
                    fprintf (stderr,
4311
                             "Unknown sound card name (too big to show)\n");
4312
                }
4313
                else {
4314
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4315
                             (int) l, p);
4316
                }
4317
                bad_card = 1;
4318
            }
4319
            p += l + (e != NULL);
4320
        }
4321

    
4322
        if (bad_card)
4323
            goto show_valid_cards;
4324
    }
4325
}
4326
#endif
4327

    
4328
static void select_vgahw (const char *p)
4329
{
4330
    const char *opts;
4331

    
4332
    default_vga = 0;
4333
    vga_interface_type = VGA_NONE;
4334
    if (strstart(p, "std", &opts)) {
4335
        vga_interface_type = VGA_STD;
4336
    } else if (strstart(p, "cirrus", &opts)) {
4337
        vga_interface_type = VGA_CIRRUS;
4338
    } else if (strstart(p, "vmware", &opts)) {
4339
        vga_interface_type = VGA_VMWARE;
4340
    } else if (strstart(p, "xenfb", &opts)) {
4341
        vga_interface_type = VGA_XENFB;
4342
    } else if (!strstart(p, "none", &opts)) {
4343
    invalid_vga:
4344
        fprintf(stderr, "Unknown vga type: %s\n", p);
4345
        exit(1);
4346
    }
4347
    while (*opts) {
4348
        const char *nextopt;
4349

    
4350
        if (strstart(opts, ",retrace=", &nextopt)) {
4351
            opts = nextopt;
4352
            if (strstart(opts, "dumb", &nextopt))
4353
                vga_retrace_method = VGA_RETRACE_DUMB;
4354
            else if (strstart(opts, "precise", &nextopt))
4355
                vga_retrace_method = VGA_RETRACE_PRECISE;
4356
            else goto invalid_vga;
4357
        } else goto invalid_vga;
4358
        opts = nextopt;
4359
    }
4360
}
4361

    
4362
#ifdef TARGET_I386
4363
static int balloon_parse(const char *arg)
4364
{
4365
    QemuOpts *opts;
4366

    
4367
    if (strcmp(arg, "none") == 0) {
4368
        return 0;
4369
    }
4370

    
4371
    if (!strncmp(arg, "virtio", 6)) {
4372
        if (arg[6] == ',') {
4373
            /* have params -> parse them */
4374
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4375
            if (!opts)
4376
                return  -1;
4377
        } else {
4378
            /* create empty opts */
4379
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4380
        }
4381
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4382
        return 0;
4383
    }
4384

    
4385
    return -1;
4386
}
4387
#endif
4388

    
4389
#ifdef _WIN32
4390
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4391
{
4392
    exit(STATUS_CONTROL_C_EXIT);
4393
    return TRUE;
4394
}
4395
#endif
4396

    
4397
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4398
{
4399
    int ret;
4400

    
4401
    if(strlen(str) != 36)
4402
        return -1;
4403

    
4404
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4405
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4406
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4407

    
4408
    if(ret != 16)
4409
        return -1;
4410

    
4411
#ifdef TARGET_I386
4412
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4413
#endif
4414

    
4415
    return 0;
4416
}
4417

    
4418
#ifndef _WIN32
4419

    
4420
static void termsig_handler(int signal)
4421
{
4422
    qemu_system_shutdown_request();
4423
}
4424

    
4425
static void sigchld_handler(int signal)
4426
{
4427
    waitpid(-1, NULL, WNOHANG);
4428
}
4429

    
4430
static void sighandler_setup(void)
4431
{
4432
    struct sigaction act;
4433

    
4434
    memset(&act, 0, sizeof(act));
4435
    act.sa_handler = termsig_handler;
4436
    sigaction(SIGINT,  &act, NULL);
4437
    sigaction(SIGHUP,  &act, NULL);
4438
    sigaction(SIGTERM, &act, NULL);
4439

    
4440
    act.sa_handler = sigchld_handler;
4441
    act.sa_flags = SA_NOCLDSTOP;
4442
    sigaction(SIGCHLD, &act, NULL);
4443
}
4444

    
4445
#endif
4446

    
4447
#ifdef _WIN32
4448
/* Look for support files in the same directory as the executable.  */
4449
static char *find_datadir(const char *argv0)
4450
{
4451
    char *p;
4452
    char buf[MAX_PATH];
4453
    DWORD len;
4454

    
4455
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4456
    if (len == 0) {
4457
        return NULL;
4458
    }
4459

    
4460
    buf[len] = 0;
4461
    p = buf + len - 1;
4462
    while (p != buf && *p != '\\')
4463
        p--;
4464
    *p = 0;
4465
    if (access(buf, R_OK) == 0) {
4466
        return qemu_strdup(buf);
4467
    }
4468
    return NULL;
4469
}
4470
#else /* !_WIN32 */
4471

    
4472
/* Find a likely location for support files using the location of the binary.
4473
   For installed binaries this will be "$bindir/../share/qemu".  When
4474
   running from the build tree this will be "$bindir/../pc-bios".  */
4475
#define SHARE_SUFFIX "/share/qemu"
4476
#define BUILD_SUFFIX "/pc-bios"
4477
static char *find_datadir(const char *argv0)
4478
{
4479
    char *dir;
4480
    char *p = NULL;
4481
    char *res;
4482
    char buf[PATH_MAX];
4483
    size_t max_len;
4484

    
4485
#if defined(__linux__)
4486
    {
4487
        int len;
4488
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4489
        if (len > 0) {
4490
            buf[len] = 0;
4491
            p = buf;
4492
        }
4493
    }
4494
#elif defined(__FreeBSD__)
4495
    {
4496
        int len;
4497
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4498
        if (len > 0) {
4499
            buf[len] = 0;
4500
            p = buf;
4501
        }
4502
    }
4503
#endif
4504
    /* If we don't have any way of figuring out the actual executable
4505
       location then try argv[0].  */
4506
    if (!p) {
4507
        p = realpath(argv0, buf);
4508
        if (!p) {
4509
            return NULL;
4510
        }
4511
    }
4512
    dir = dirname(p);
4513
    dir = dirname(dir);
4514

    
4515
    max_len = strlen(dir) +
4516
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4517
    res = qemu_mallocz(max_len);
4518
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4519
    if (access(res, R_OK)) {
4520
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4521
        if (access(res, R_OK)) {
4522
            qemu_free(res);
4523
            res = NULL;
4524
        }
4525
    }
4526

    
4527
    return res;
4528
}
4529
#undef SHARE_SUFFIX
4530
#undef BUILD_SUFFIX
4531
#endif
4532

    
4533
char *qemu_find_file(int type, const char *name)
4534
{
4535
    int len;
4536
    const char *subdir;
4537
    char *buf;
4538

    
4539
    /* If name contains path separators then try it as a straight path.  */
4540
    if ((strchr(name, '/') || strchr(name, '\\'))
4541
        && access(name, R_OK) == 0) {
4542
        return qemu_strdup(name);
4543
    }
4544
    switch (type) {
4545
    case QEMU_FILE_TYPE_BIOS:
4546
        subdir = "";
4547
        break;
4548
    case QEMU_FILE_TYPE_KEYMAP:
4549
        subdir = "keymaps/";
4550
        break;
4551
    default:
4552
        abort();
4553
    }
4554
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4555
    buf = qemu_mallocz(len);
4556
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4557
    if (access(buf, R_OK)) {
4558
        qemu_free(buf);
4559
        return NULL;
4560
    }
4561
    return buf;
4562
}
4563

    
4564
static int device_help_func(QemuOpts *opts, void *opaque)
4565
{
4566
    return qdev_device_help(opts);
4567
}
4568

    
4569
static int device_init_func(QemuOpts *opts, void *opaque)
4570
{
4571
    DeviceState *dev;
4572

    
4573
    dev = qdev_device_add(opts);
4574
    if (!dev)
4575
        return -1;
4576
    return 0;
4577
}
4578

    
4579
static int chardev_init_func(QemuOpts *opts, void *opaque)
4580
{
4581
    CharDriverState *chr;
4582

    
4583
    chr = qemu_chr_open_opts(opts, NULL);
4584
    if (!chr)
4585
        return -1;
4586
    return 0;
4587
}
4588

    
4589
static int mon_init_func(QemuOpts *opts, void *opaque)
4590
{
4591
    CharDriverState *chr;
4592
    const char *chardev;
4593
    const char *mode;
4594
    int flags;
4595

    
4596
    mode = qemu_opt_get(opts, "mode");
4597
    if (mode == NULL) {
4598
        mode = "readline";
4599
    }
4600
    if (strcmp(mode, "readline") == 0) {
4601
        flags = MONITOR_USE_READLINE;
4602
    } else if (strcmp(mode, "control") == 0) {
4603
        flags = MONITOR_USE_CONTROL;
4604
    } else {
4605
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4606
        exit(1);
4607
    }
4608

    
4609
    if (qemu_opt_get_bool(opts, "default", 0))
4610
        flags |= MONITOR_IS_DEFAULT;
4611

    
4612
    chardev = qemu_opt_get(opts, "chardev");
4613
    chr = qemu_chr_find(chardev);
4614
    if (chr == NULL) {
4615
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4616
        exit(1);
4617
    }
4618

    
4619
    monitor_init(chr, flags);
4620
    return 0;
4621
}
4622

    
4623
static void monitor_parse(const char *optarg, const char *mode)
4624
{
4625
    static int monitor_device_index = 0;
4626
    QemuOpts *opts;
4627
    const char *p;
4628
    char label[32];
4629
    int def = 0;
4630

    
4631
    if (strstart(optarg, "chardev:", &p)) {
4632
        snprintf(label, sizeof(label), "%s", p);
4633
    } else {
4634
        if (monitor_device_index) {
4635
            snprintf(label, sizeof(label), "monitor%d",
4636
                     monitor_device_index);
4637
        } else {
4638
            snprintf(label, sizeof(label), "monitor");
4639
            def = 1;
4640
        }
4641
        opts = qemu_chr_parse_compat(label, optarg);
4642
        if (!opts) {
4643
            fprintf(stderr, "parse error: %s\n", optarg);
4644
            exit(1);
4645
        }
4646
    }
4647

    
4648
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4649
    if (!opts) {
4650
        fprintf(stderr, "duplicate chardev: %s\n", label);
4651
        exit(1);
4652
    }
4653
    qemu_opt_set(opts, "mode", mode);
4654
    qemu_opt_set(opts, "chardev", label);
4655
    if (def)
4656
        qemu_opt_set(opts, "default", "on");
4657
    monitor_device_index++;
4658
}
4659

    
4660
struct device_config {
4661
    enum {
4662
        DEV_USB,       /* -usbdevice     */
4663
        DEV_BT,        /* -bt            */
4664
        DEV_SERIAL,    /* -serial        */
4665
        DEV_PARALLEL,  /* -parallel      */
4666
        DEV_VIRTCON,   /* -virtioconsole */
4667
        DEV_DEBUGCON,  /* -debugcon */
4668
    } type;
4669
    const char *cmdline;
4670
    QTAILQ_ENTRY(device_config) next;
4671
};
4672
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4673

    
4674
static void add_device_config(int type, const char *cmdline)
4675
{
4676
    struct device_config *conf;
4677

    
4678
    conf = qemu_mallocz(sizeof(*conf));
4679
    conf->type = type;
4680
    conf->cmdline = cmdline;
4681
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4682
}
4683

    
4684
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4685
{
4686
    struct device_config *conf;
4687
    int rc;
4688

    
4689
    QTAILQ_FOREACH(conf, &device_configs, next) {
4690
        if (conf->type != type)
4691
            continue;
4692
        rc = func(conf->cmdline);
4693
        if (0 != rc)
4694
            return rc;
4695
    }
4696
    return 0;
4697
}
4698

    
4699
static int serial_parse(const char *devname)
4700
{
4701
    static int index = 0;
4702
    char label[32];
4703

    
4704
    if (strcmp(devname, "none") == 0)
4705
        return 0;
4706
    if (index == MAX_SERIAL_PORTS) {
4707
        fprintf(stderr, "qemu: too many serial ports\n");
4708
        exit(1);
4709
    }
4710
    snprintf(label, sizeof(label), "serial%d", index);
4711
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
4712
    if (!serial_hds[index]) {
4713
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4714
                devname, strerror(errno));
4715
        return -1;
4716
    }
4717
    index++;
4718
    return 0;
4719
}
4720

    
4721
static int parallel_parse(const char *devname)
4722
{
4723
    static int index = 0;
4724
    char label[32];
4725

    
4726
    if (strcmp(devname, "none") == 0)
4727
        return 0;
4728
    if (index == MAX_PARALLEL_PORTS) {
4729
        fprintf(stderr, "qemu: too many parallel ports\n");
4730
        exit(1);
4731
    }
4732
    snprintf(label, sizeof(label), "parallel%d", index);
4733
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4734
    if (!parallel_hds[index]) {
4735
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4736
                devname, strerror(errno));
4737
        return -1;
4738
    }
4739
    index++;
4740
    return 0;
4741
}
4742

    
4743
static int virtcon_parse(const char *devname)
4744
{
4745
    static int index = 0;
4746
    char label[32];
4747
    QemuOpts *bus_opts, *dev_opts;
4748

    
4749
    if (strcmp(devname, "none") == 0)
4750
        return 0;
4751
    if (index == MAX_VIRTIO_CONSOLES) {
4752
        fprintf(stderr, "qemu: too many virtio consoles\n");
4753
        exit(1);
4754
    }
4755

    
4756
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4757
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4758

    
4759
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4760
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4761

    
4762
    snprintf(label, sizeof(label), "virtcon%d", index);
4763
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4764
    if (!virtcon_hds[index]) {
4765
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4766
                devname, strerror(errno));
4767
        return -1;
4768
    }
4769
    qemu_opt_set(dev_opts, "chardev", label);
4770

    
4771
    index++;
4772
    return 0;
4773
}
4774

    
4775
static int debugcon_parse(const char *devname)
4776
{   
4777
    QemuOpts *opts;
4778

    
4779
    if (!qemu_chr_open("debugcon", devname, NULL)) {
4780
        exit(1);
4781
    }
4782
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4783
    if (!opts) {
4784
        fprintf(stderr, "qemu: already have a debugcon device\n");
4785
        exit(1);
4786
    }
4787
    qemu_opt_set(opts, "driver", "isa-debugcon");
4788
    qemu_opt_set(opts, "chardev", "debugcon");
4789
    return 0;
4790
}
4791

    
4792
static const QEMUOption *lookup_opt(int argc, char **argv,
4793
                                    const char **poptarg, int *poptind)
4794
{
4795
    const QEMUOption *popt;
4796
    int optind = *poptind;
4797
    char *r = argv[optind];
4798
    const char *optarg;
4799

    
4800
    optind++;
4801
    /* Treat --foo the same as -foo.  */
4802
    if (r[1] == '-')
4803
        r++;
4804
    popt = qemu_options;
4805
    for(;;) {
4806
        if (!popt->name) {
4807
            fprintf(stderr, "%s: invalid option -- '%s'\n",
4808
                    argv[0], r);
4809
            exit(1);
4810
        }
4811
        if (!strcmp(popt->name, r + 1))
4812
            break;
4813
        popt++;
4814
    }
4815
    if (popt->flags & HAS_ARG) {
4816
        if (optind >= argc) {
4817
            fprintf(stderr, "%s: option '%s' requires an argument\n",
4818
                    argv[0], r);
4819
            exit(1);
4820
        }
4821
        optarg = argv[optind++];
4822
    } else {
4823
        optarg = NULL;
4824
    }
4825

    
4826
    *poptarg = optarg;
4827
    *poptind = optind;
4828

    
4829
    return popt;
4830
}
4831

    
4832
int main(int argc, char **argv, char **envp)
4833
{
4834
    const char *gdbstub_dev = NULL;
4835
    uint32_t boot_devices_bitmap = 0;
4836
    int i;
4837
    int snapshot, linux_boot, net_boot;
4838
    const char *initrd_filename;
4839
    const char *kernel_filename, *kernel_cmdline;
4840
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4841
    DisplayState *ds;
4842
    DisplayChangeListener *dcl;
4843
    int cyls, heads, secs, translation;
4844
    QemuOpts *hda_opts = NULL, *opts;
4845
    int optind;
4846
    const char *optarg;
4847
    const char *loadvm = NULL;
4848
    QEMUMachine *machine;
4849
    const char *cpu_model;
4850
#ifndef _WIN32
4851
    int fds[2];
4852
#endif
4853
    int tb_size;
4854
    const char *pid_file = NULL;
4855
    const char *incoming = NULL;
4856
#ifndef _WIN32
4857
    int fd = 0;
4858
    struct passwd *pwd = NULL;
4859
    const char *chroot_dir = NULL;
4860
    const char *run_as = NULL;
4861
#endif
4862
    CPUState *env;
4863
    int show_vnc_port = 0;
4864
    int defconfig = 1;
4865

    
4866
    init_clocks();
4867

    
4868
    qemu_errors_to_file(stderr);
4869
    qemu_cache_utils_init(envp);
4870

    
4871
    QLIST_INIT (&vm_change_state_head);
4872
#ifndef _WIN32
4873
    {
4874
        struct sigaction act;
4875
        sigfillset(&act.sa_mask);
4876
        act.sa_flags = 0;
4877
        act.sa_handler = SIG_IGN;
4878
        sigaction(SIGPIPE, &act, NULL);
4879
    }
4880
#else
4881
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4882
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4883
       QEMU to run on a single CPU */
4884
    {
4885
        HANDLE h;
4886
        DWORD mask, smask;
4887
        int i;
4888
        h = GetCurrentProcess();
4889
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4890
            for(i = 0; i < 32; i++) {
4891
                if (mask & (1 << i))
4892
                    break;
4893
            }
4894
            if (i != 32) {
4895
                mask = 1 << i;
4896
                SetProcessAffinityMask(h, mask);
4897
            }
4898
        }
4899
    }
4900
#endif
4901

    
4902
    module_call_init(MODULE_INIT_MACHINE);
4903
    machine = find_default_machine();
4904
    cpu_model = NULL;
4905
    initrd_filename = NULL;
4906
    ram_size = 0;
4907
    snapshot = 0;
4908
    kernel_filename = NULL;
4909
    kernel_cmdline = "";
4910
    cyls = heads = secs = 0;
4911
    translation = BIOS_ATA_TRANSLATION_AUTO;
4912

    
4913
    for (i = 0; i < MAX_NODES; i++) {
4914
        node_mem[i] = 0;
4915
        node_cpumask[i] = 0;
4916
    }
4917

    
4918
    nb_numa_nodes = 0;
4919
    nb_nics = 0;
4920

    
4921
    tb_size = 0;
4922
    autostart= 1;
4923

    
4924
    /* first pass of option parsing */
4925
    optind = 1;
4926
    while (optind < argc) {
4927
        if (argv[optind][0] != '-') {
4928
            /* disk image */
4929
            optind++;
4930
            continue;
4931
        } else {
4932
            const QEMUOption *popt;
4933

    
4934
            popt = lookup_opt(argc, argv, &optarg, &optind);
4935
            switch (popt->index) {
4936
            case QEMU_OPTION_nodefconfig:
4937
                defconfig=0;
4938
                break;
4939
            }
4940
        }
4941
    }
4942

    
4943
    if (defconfig) {
4944
        FILE *fp;
4945
        fp = fopen(CONFIG_QEMU_CONFDIR "/qemu.conf", "r");
4946
        if (fp) {
4947
            if (qemu_config_parse(fp) != 0) {
4948
                exit(1);
4949
            }
4950
            fclose(fp);
4951
        }
4952

    
4953
        fp = fopen(CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf", "r");
4954
        if (fp) {
4955
            if (qemu_config_parse(fp) != 0) {
4956
                exit(1);
4957
            }
4958
            fclose(fp);
4959
        }
4960
    }
4961

    
4962
    /* second pass of option parsing */
4963
    optind = 1;
4964
    for(;;) {
4965
        if (optind >= argc)
4966
            break;
4967
        if (argv[optind][0] != '-') {
4968
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4969
        } else {
4970
            const QEMUOption *popt;
4971

    
4972
            popt = lookup_opt(argc, argv, &optarg, &optind);
4973
            switch(popt->index) {
4974
            case QEMU_OPTION_M:
4975
                machine = find_machine(optarg);
4976
                if (!machine) {
4977
                    QEMUMachine *m;
4978
                    printf("Supported machines are:\n");
4979
                    for(m = first_machine; m != NULL; m = m->next) {
4980
                        if (m->alias)
4981
                            printf("%-10s %s (alias of %s)\n",
4982
                                   m->alias, m->desc, m->name);
4983
                        printf("%-10s %s%s\n",
4984
                               m->name, m->desc,
4985
                               m->is_default ? " (default)" : "");
4986
                    }
4987
                    exit(*optarg != '?');
4988
                }
4989
                break;
4990
            case QEMU_OPTION_cpu:
4991
                /* hw initialization will check this */
4992
                if (*optarg == '?') {
4993
/* XXX: implement xxx_cpu_list for targets that still miss it */
4994
#if defined(cpu_list)
4995
                    cpu_list(stdout, &fprintf);
4996
#endif
4997
                    exit(0);
4998
                } else {
4999
                    cpu_model = optarg;
5000
                }
5001
                break;
5002
            case QEMU_OPTION_initrd:
5003
                initrd_filename = optarg;
5004
                break;
5005
            case QEMU_OPTION_hda:
5006
                if (cyls == 0)
5007
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
5008
                else
5009
                    hda_opts = drive_add(optarg, HD_ALIAS
5010
                             ",cyls=%d,heads=%d,secs=%d%s",
5011
                             0, cyls, heads, secs,
5012
                             translation == BIOS_ATA_TRANSLATION_LBA ?
5013
                                 ",trans=lba" :
5014
                             translation == BIOS_ATA_TRANSLATION_NONE ?
5015
                                 ",trans=none" : "");
5016
                 break;
5017
            case QEMU_OPTION_hdb:
5018
            case QEMU_OPTION_hdc:
5019
            case QEMU_OPTION_hdd:
5020
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5021
                break;
5022
            case QEMU_OPTION_drive:
5023
                drive_add(NULL, "%s", optarg);
5024
                break;
5025
            case QEMU_OPTION_set:
5026
                if (qemu_set_option(optarg) != 0)
5027
                    exit(1);
5028
                break;
5029
            case QEMU_OPTION_global:
5030
                if (qemu_global_option(optarg) != 0)
5031
                    exit(1);
5032
                break;
5033
            case QEMU_OPTION_mtdblock:
5034
                drive_add(optarg, MTD_ALIAS);
5035
                break;
5036
            case QEMU_OPTION_sd:
5037
                drive_add(optarg, SD_ALIAS);
5038
                break;
5039
            case QEMU_OPTION_pflash:
5040
                drive_add(optarg, PFLASH_ALIAS);
5041
                break;
5042
            case QEMU_OPTION_snapshot:
5043
                snapshot = 1;
5044
                break;
5045
            case QEMU_OPTION_hdachs:
5046
                {
5047
                    const char *p;
5048
                    p = optarg;
5049
                    cyls = strtol(p, (char **)&p, 0);
5050
                    if (cyls < 1 || cyls > 16383)
5051
                        goto chs_fail;
5052
                    if (*p != ',')
5053
                        goto chs_fail;
5054
                    p++;
5055
                    heads = strtol(p, (char **)&p, 0);
5056
                    if (heads < 1 || heads > 16)
5057
                        goto chs_fail;
5058
                    if (*p != ',')
5059
                        goto chs_fail;
5060
                    p++;
5061
                    secs = strtol(p, (char **)&p, 0);
5062
                    if (secs < 1 || secs > 63)
5063
                        goto chs_fail;
5064
                    if (*p == ',') {
5065
                        p++;
5066
                        if (!strcmp(p, "none"))
5067
                            translation = BIOS_ATA_TRANSLATION_NONE;
5068
                        else if (!strcmp(p, "lba"))
5069
                            translation = BIOS_ATA_TRANSLATION_LBA;
5070
                        else if (!strcmp(p, "auto"))
5071
                            translation = BIOS_ATA_TRANSLATION_AUTO;
5072
                        else
5073
                            goto chs_fail;
5074
                    } else if (*p != '\0') {
5075
                    chs_fail:
5076
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
5077
                        exit(1);
5078
                    }
5079
                    if (hda_opts != NULL) {
5080
                        char num[16];
5081
                        snprintf(num, sizeof(num), "%d", cyls);
5082
                        qemu_opt_set(hda_opts, "cyls", num);
5083
                        snprintf(num, sizeof(num), "%d", heads);
5084
                        qemu_opt_set(hda_opts, "heads", num);
5085
                        snprintf(num, sizeof(num), "%d", secs);
5086
                        qemu_opt_set(hda_opts, "secs", num);
5087
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
5088
                            qemu_opt_set(hda_opts, "trans", "lba");
5089
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
5090
                            qemu_opt_set(hda_opts, "trans", "none");
5091
                    }
5092
                }
5093
                break;
5094
            case QEMU_OPTION_numa:
5095
                if (nb_numa_nodes >= MAX_NODES) {
5096
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
5097
                    exit(1);
5098
                }
5099
                numa_add(optarg);
5100
                break;
5101
            case QEMU_OPTION_nographic:
5102
                display_type = DT_NOGRAPHIC;
5103
                break;
5104
#ifdef CONFIG_CURSES
5105
            case QEMU_OPTION_curses:
5106
                display_type = DT_CURSES;
5107
                break;
5108
#endif
5109
            case QEMU_OPTION_portrait:
5110
                graphic_rotate = 1;
5111
                break;
5112
            case QEMU_OPTION_kernel:
5113
                kernel_filename = optarg;
5114
                break;
5115
            case QEMU_OPTION_append:
5116
                kernel_cmdline = optarg;
5117
                break;
5118
            case QEMU_OPTION_cdrom:
5119
                drive_add(optarg, CDROM_ALIAS);
5120
                break;
5121
            case QEMU_OPTION_boot:
5122
                {
5123
                    static const char * const params[] = {
5124
                        "order", "once", "menu", NULL
5125
                    };
5126
                    char buf[sizeof(boot_devices)];
5127
                    char *standard_boot_devices;
5128
                    int legacy = 0;
5129

    
5130
                    if (!strchr(optarg, '=')) {
5131
                        legacy = 1;
5132
                        pstrcpy(buf, sizeof(buf), optarg);
5133
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5134
                        fprintf(stderr,
5135
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5136
                                buf, optarg);
5137
                        exit(1);
5138
                    }
5139

    
5140
                    if (legacy ||
5141
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
5142
                        boot_devices_bitmap = parse_bootdevices(buf);
5143
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
5144
                    }
5145
                    if (!legacy) {
5146
                        if (get_param_value(buf, sizeof(buf),
5147
                                            "once", optarg)) {
5148
                            boot_devices_bitmap |= parse_bootdevices(buf);
5149
                            standard_boot_devices = qemu_strdup(boot_devices);
5150
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
5151
                            qemu_register_reset(restore_boot_devices,
5152
                                                standard_boot_devices);
5153
                        }
5154
                        if (get_param_value(buf, sizeof(buf),
5155
                                            "menu", optarg)) {
5156
                            if (!strcmp(buf, "on")) {
5157
                                boot_menu = 1;
5158
                            } else if (!strcmp(buf, "off")) {
5159
                                boot_menu = 0;
5160
                            } else {
5161
                                fprintf(stderr,
5162
                                        "qemu: invalid option value '%s'\n",
5163
                                        buf);
5164
                                exit(1);
5165
                            }
5166
                        }
5167
                    }
5168
                }
5169
                break;
5170
            case QEMU_OPTION_fda:
5171
            case QEMU_OPTION_fdb:
5172
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5173
                break;
5174
#ifdef TARGET_I386
5175
            case QEMU_OPTION_no_fd_bootchk:
5176
                fd_bootchk = 0;
5177
                break;
5178
#endif
5179
            case QEMU_OPTION_netdev:
5180
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5181
                    exit(1);
5182
                }
5183
                break;
5184
            case QEMU_OPTION_net:
5185
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5186
                    exit(1);
5187
                }
5188
                break;
5189
#ifdef CONFIG_SLIRP
5190
            case QEMU_OPTION_tftp:
5191
                legacy_tftp_prefix = optarg;
5192
                break;
5193
            case QEMU_OPTION_bootp:
5194
                legacy_bootp_filename = optarg;
5195
                break;
5196
#ifndef _WIN32
5197
            case QEMU_OPTION_smb:
5198
                if (net_slirp_smb(optarg) < 0)
5199
                    exit(1);
5200
                break;
5201
#endif
5202
            case QEMU_OPTION_redir:
5203
                if (net_slirp_redir(optarg) < 0)
5204
                    exit(1);
5205
                break;
5206
#endif
5207
            case QEMU_OPTION_bt:
5208
                add_device_config(DEV_BT, optarg);
5209
                break;
5210
#ifdef HAS_AUDIO
5211
            case QEMU_OPTION_audio_help:
5212
                AUD_help ();
5213
                exit (0);
5214
                break;
5215
            case QEMU_OPTION_soundhw:
5216
                select_soundhw (optarg);
5217
                break;
5218
#endif
5219
            case QEMU_OPTION_h:
5220
                help(0);
5221
                break;
5222
            case QEMU_OPTION_version:
5223
                version();
5224
                exit(0);
5225
                break;
5226
            case QEMU_OPTION_m: {
5227
                uint64_t value;
5228
                char *ptr;
5229

    
5230
                value = strtoul(optarg, &ptr, 10);
5231
                switch (*ptr) {
5232
                case 0: case 'M': case 'm':
5233
                    value <<= 20;
5234
                    break;
5235
                case 'G': case 'g':
5236
                    value <<= 30;
5237
                    break;
5238
                default:
5239
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5240
                    exit(1);
5241
                }
5242

    
5243
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5244
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5245
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5246
                    exit(1);
5247
                }
5248
                if (value != (uint64_t)(ram_addr_t)value) {
5249
                    fprintf(stderr, "qemu: ram size too large\n");
5250
                    exit(1);
5251
                }
5252
                ram_size = value;
5253
                break;
5254
            }
5255
            case QEMU_OPTION_d:
5256
                {
5257
                    int mask;
5258
                    const CPULogItem *item;
5259

    
5260
                    mask = cpu_str_to_log_mask(optarg);
5261
                    if (!mask) {
5262
                        printf("Log items (comma separated):\n");
5263
                    for(item = cpu_log_items; item->mask != 0; item++) {
5264
                        printf("%-10s %s\n", item->name, item->help);
5265
                    }
5266
                    exit(1);
5267
                    }
5268
                    cpu_set_log(mask);
5269
                }
5270
                break;
5271
            case QEMU_OPTION_s:
5272
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5273
                break;
5274
            case QEMU_OPTION_gdb:
5275
                gdbstub_dev = optarg;
5276
                break;
5277
            case QEMU_OPTION_L:
5278
                data_dir = optarg;
5279
                break;
5280
            case QEMU_OPTION_bios:
5281
                bios_name = optarg;
5282
                break;
5283
            case QEMU_OPTION_singlestep:
5284
                singlestep = 1;
5285
                break;
5286
            case QEMU_OPTION_S:
5287
                autostart = 0;
5288
                break;
5289
            case QEMU_OPTION_k:
5290
                keyboard_layout = optarg;
5291
                break;
5292
            case QEMU_OPTION_localtime:
5293
                rtc_utc = 0;
5294
                break;
5295
            case QEMU_OPTION_vga:
5296
                select_vgahw (optarg);
5297
                break;
5298
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5299
            case QEMU_OPTION_g:
5300
                {
5301
                    const char *p;
5302
                    int w, h, depth;
5303
                    p = optarg;
5304
                    w = strtol(p, (char **)&p, 10);
5305
                    if (w <= 0) {
5306
                    graphic_error:
5307
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5308
                        exit(1);
5309
                    }
5310
                    if (*p != 'x')
5311
                        goto graphic_error;
5312
                    p++;
5313
                    h = strtol(p, (char **)&p, 10);
5314
                    if (h <= 0)
5315
                        goto graphic_error;
5316
                    if (*p == 'x') {
5317
                        p++;
5318
                        depth = strtol(p, (char **)&p, 10);
5319
                        if (depth != 8 && depth != 15 && depth != 16 &&
5320
                            depth != 24 && depth != 32)
5321
                            goto graphic_error;
5322
                    } else if (*p == '\0') {
5323
                        depth = graphic_depth;
5324
                    } else {
5325
                        goto graphic_error;
5326
                    }
5327

    
5328
                    graphic_width = w;
5329
                    graphic_height = h;
5330
                    graphic_depth = depth;
5331
                }
5332
                break;
5333
#endif
5334
            case QEMU_OPTION_echr:
5335
                {
5336
                    char *r;
5337
                    term_escape_char = strtol(optarg, &r, 0);
5338
                    if (r == optarg)
5339
                        printf("Bad argument to echr\n");
5340
                    break;
5341
                }
5342
            case QEMU_OPTION_monitor:
5343
                monitor_parse(optarg, "readline");
5344
                default_monitor = 0;
5345
                break;
5346
            case QEMU_OPTION_qmp:
5347
                monitor_parse(optarg, "control");
5348
                default_monitor = 0;
5349
                break;
5350
            case QEMU_OPTION_mon:
5351
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5352
                if (!opts) {
5353
                    fprintf(stderr, "parse error: %s\n", optarg);
5354
                    exit(1);
5355
                }
5356
                default_monitor = 0;
5357
                break;
5358
            case QEMU_OPTION_chardev:
5359
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5360
                if (!opts) {
5361
                    fprintf(stderr, "parse error: %s\n", optarg);
5362
                    exit(1);
5363
                }
5364
                break;
5365
            case QEMU_OPTION_serial:
5366
                add_device_config(DEV_SERIAL, optarg);
5367
                default_serial = 0;
5368
                break;
5369
            case QEMU_OPTION_watchdog:
5370
                if (watchdog) {
5371
                    fprintf(stderr,
5372
                            "qemu: only one watchdog option may be given\n");
5373
                    return 1;
5374
                }
5375
                watchdog = optarg;
5376
                break;
5377
            case QEMU_OPTION_watchdog_action:
5378
                if (select_watchdog_action(optarg) == -1) {
5379
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
5380
                    exit(1);
5381
                }
5382
                break;
5383
            case QEMU_OPTION_virtiocon:
5384
                add_device_config(DEV_VIRTCON, optarg);
5385
                default_virtcon = 0;
5386
                break;
5387
            case QEMU_OPTION_parallel:
5388
                add_device_config(DEV_PARALLEL, optarg);
5389
                default_parallel = 0;
5390
                break;
5391
            case QEMU_OPTION_debugcon:
5392
                add_device_config(DEV_DEBUGCON, optarg);
5393
                break;
5394
            case QEMU_OPTION_loadvm:
5395
                loadvm = optarg;
5396
                break;
5397
            case QEMU_OPTION_full_screen:
5398
                full_screen = 1;
5399
                break;
5400
#ifdef CONFIG_SDL
5401
            case QEMU_OPTION_no_frame:
5402
                no_frame = 1;
5403
                break;
5404
            case QEMU_OPTION_alt_grab:
5405
                alt_grab = 1;
5406
                break;
5407
            case QEMU_OPTION_ctrl_grab:
5408
                ctrl_grab = 1;
5409
                break;
5410
            case QEMU_OPTION_no_quit:
5411
                no_quit = 1;
5412
                break;
5413
            case QEMU_OPTION_sdl:
5414
                display_type = DT_SDL;
5415
                break;
5416
#endif
5417
            case QEMU_OPTION_pidfile:
5418
                pid_file = optarg;
5419
                break;
5420
#ifdef TARGET_I386
5421
            case QEMU_OPTION_win2k_hack:
5422
                win2k_install_hack = 1;
5423
                break;
5424
            case QEMU_OPTION_rtc_td_hack:
5425
                rtc_td_hack = 1;
5426
                break;
5427
            case QEMU_OPTION_acpitable:
5428
                if(acpi_table_add(optarg) < 0) {
5429
                    fprintf(stderr, "Wrong acpi table provided\n");
5430
                    exit(1);
5431
                }
5432
                break;
5433
            case QEMU_OPTION_smbios:
5434
                if(smbios_entry_add(optarg) < 0) {
5435
                    fprintf(stderr, "Wrong smbios provided\n");
5436
                    exit(1);
5437
                }
5438
                break;
5439
#endif
5440
#ifdef CONFIG_KVM
5441
            case QEMU_OPTION_enable_kvm:
5442
                kvm_allowed = 1;
5443
                break;
5444
#endif
5445
            case QEMU_OPTION_usb:
5446
                usb_enabled = 1;
5447
                break;
5448
            case QEMU_OPTION_usbdevice:
5449
                usb_enabled = 1;
5450
                add_device_config(DEV_USB, optarg);
5451
                break;
5452
            case QEMU_OPTION_device:
5453
                if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5454
                    exit(1);
5455
                }
5456
                break;
5457
            case QEMU_OPTION_smp:
5458
                smp_parse(optarg);
5459
                if (smp_cpus < 1) {
5460
                    fprintf(stderr, "Invalid number of CPUs\n");
5461
                    exit(1);
5462
                }
5463
                if (max_cpus < smp_cpus) {
5464
                    fprintf(stderr, "maxcpus must be equal to or greater than "
5465
                            "smp\n");
5466
                    exit(1);
5467
                }
5468
                if (max_cpus > 255) {
5469
                    fprintf(stderr, "Unsupported number of maxcpus\n");
5470
                    exit(1);
5471
                }
5472
                break;
5473
            case QEMU_OPTION_vnc:
5474
                display_type = DT_VNC;
5475
                vnc_display = optarg;
5476
                break;
5477
#ifdef TARGET_I386
5478
            case QEMU_OPTION_no_acpi:
5479
                acpi_enabled = 0;
5480
                break;
5481
            case QEMU_OPTION_no_hpet:
5482
                no_hpet = 1;
5483
                break;
5484
            case QEMU_OPTION_balloon:
5485
                if (balloon_parse(optarg) < 0) {
5486
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5487
                    exit(1);
5488
                }
5489
                break;
5490
#endif
5491
            case QEMU_OPTION_no_reboot:
5492
                no_reboot = 1;
5493
                break;
5494
            case QEMU_OPTION_no_shutdown:
5495
                no_shutdown = 1;
5496
                break;
5497
            case QEMU_OPTION_show_cursor:
5498
                cursor_hide = 0;
5499
                break;
5500
            case QEMU_OPTION_uuid:
5501
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5502
                    fprintf(stderr, "Fail to parse UUID string."
5503
                            " Wrong format.\n");
5504
                    exit(1);
5505
                }
5506
                break;
5507
#ifndef _WIN32
5508
            case QEMU_OPTION_daemonize:
5509
                daemonize = 1;
5510
                break;
5511
#endif
5512
            case QEMU_OPTION_option_rom:
5513
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5514
                    fprintf(stderr, "Too many option ROMs\n");
5515
                    exit(1);
5516
                }
5517
                option_rom[nb_option_roms] = optarg;
5518
                nb_option_roms++;
5519
                break;
5520
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5521
            case QEMU_OPTION_semihosting:
5522
                semihosting_enabled = 1;
5523
                break;
5524
#endif
5525
            case QEMU_OPTION_name:
5526
                qemu_name = qemu_strdup(optarg);
5527
                 {
5528
                     char *p = strchr(qemu_name, ',');
5529
                     if (p != NULL) {
5530
                        *p++ = 0;
5531
                        if (strncmp(p, "process=", 8)) {
5532
                            fprintf(stderr, "Unknown subargument %s to -name", p);
5533
                            exit(1);
5534
                        }
5535
                        p += 8;
5536
                        set_proc_name(p);
5537
                     }        
5538
                 }        
5539
                break;
5540
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5541
            case QEMU_OPTION_prom_env:
5542
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5543
                    fprintf(stderr, "Too many prom variables\n");
5544
                    exit(1);
5545
                }
5546
                prom_envs[nb_prom_envs] = optarg;
5547
                nb_prom_envs++;
5548
                break;
5549
#endif
5550
#ifdef TARGET_ARM
5551
            case QEMU_OPTION_old_param:
5552
                old_param = 1;
5553
                break;
5554
#endif
5555
            case QEMU_OPTION_clock:
5556
                configure_alarms(optarg);
5557
                break;
5558
            case QEMU_OPTION_startdate:
5559
                configure_rtc_date_offset(optarg, 1);
5560
                break;
5561
            case QEMU_OPTION_rtc:
5562
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5563
                if (!opts) {
5564
                    fprintf(stderr, "parse error: %s\n", optarg);
5565
                    exit(1);
5566
                }
5567
                configure_rtc(opts);
5568
                break;
5569
            case QEMU_OPTION_tb_size:
5570
                tb_size = strtol(optarg, NULL, 0);
5571
                if (tb_size < 0)
5572
                    tb_size = 0;
5573
                break;
5574
            case QEMU_OPTION_icount:
5575
                use_icount = 1;
5576
                if (strcmp(optarg, "auto") == 0) {
5577
                    icount_time_shift = -1;
5578
                } else {
5579
                    icount_time_shift = strtol(optarg, NULL, 0);
5580
                }
5581
                break;
5582
            case QEMU_OPTION_incoming:
5583
                incoming = optarg;
5584
                break;
5585
            case QEMU_OPTION_nodefaults:
5586
                default_serial = 0;
5587
                default_parallel = 0;
5588
                default_virtcon = 0;
5589
                default_monitor = 0;
5590
                default_vga = 0;
5591
                default_net = 0;
5592
                default_floppy = 0;
5593
                default_cdrom = 0;
5594
                default_sdcard = 0;
5595
                break;
5596
#ifndef _WIN32
5597
            case QEMU_OPTION_chroot:
5598
                chroot_dir = optarg;
5599
                break;
5600
            case QEMU_OPTION_runas:
5601
                run_as = optarg;
5602
                break;
5603
#endif
5604
#ifdef CONFIG_XEN
5605
            case QEMU_OPTION_xen_domid:
5606
                xen_domid = atoi(optarg);
5607
                break;
5608
            case QEMU_OPTION_xen_create:
5609
                xen_mode = XEN_CREATE;
5610
                break;
5611
            case QEMU_OPTION_xen_attach:
5612
                xen_mode = XEN_ATTACH;
5613
                break;
5614
#endif
5615
            case QEMU_OPTION_readconfig:
5616
                {
5617
                    FILE *fp;
5618
                    fp = fopen(optarg, "r");
5619
                    if (fp == NULL) {
5620
                        fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5621
                        exit(1);
5622
                    }
5623
                    if (qemu_config_parse(fp) != 0) {
5624
                        exit(1);
5625
                    }
5626
                    fclose(fp);
5627
                    break;
5628
                }
5629
            case QEMU_OPTION_writeconfig:
5630
                {
5631
                    FILE *fp;
5632
                    if (strcmp(optarg, "-") == 0) {
5633
                        fp = stdout;
5634
                    } else {
5635
                        fp = fopen(optarg, "w");
5636
                        if (fp == NULL) {
5637
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5638
                            exit(1);
5639
                        }
5640
                    }
5641
                    qemu_config_write(fp);
5642
                    fclose(fp);
5643
                    break;
5644
                }
5645
            }
5646
        }
5647
    }
5648

    
5649
    /* If no data_dir is specified then try to find it relative to the
5650
       executable path.  */
5651
    if (!data_dir) {
5652
        data_dir = find_datadir(argv[0]);
5653
    }
5654
    /* If all else fails use the install patch specified when building.  */
5655
    if (!data_dir) {
5656
        data_dir = CONFIG_QEMU_SHAREDIR;
5657
    }
5658

    
5659
    /*
5660
     * Default to max_cpus = smp_cpus, in case the user doesn't
5661
     * specify a max_cpus value.
5662
     */
5663
    if (!max_cpus)
5664
        max_cpus = smp_cpus;
5665

    
5666
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5667
    if (smp_cpus > machine->max_cpus) {
5668
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5669
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5670
                machine->max_cpus);
5671
        exit(1);
5672
    }
5673

    
5674
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5675
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5676

    
5677
    if (machine->no_serial) {
5678
        default_serial = 0;
5679
    }
5680
    if (machine->no_parallel) {
5681
        default_parallel = 0;
5682
    }
5683
    if (!machine->use_virtcon) {
5684
        default_virtcon = 0;
5685
    }
5686
    if (machine->no_vga) {
5687
        default_vga = 0;
5688
    }
5689
    if (machine->no_floppy) {
5690
        default_floppy = 0;
5691
    }
5692
    if (machine->no_cdrom) {
5693
        default_cdrom = 0;
5694
    }
5695
    if (machine->no_sdcard) {
5696
        default_sdcard = 0;
5697
    }
5698

    
5699
    if (display_type == DT_NOGRAPHIC) {
5700
        if (default_parallel)
5701
            add_device_config(DEV_PARALLEL, "null");
5702
        if (default_serial && default_monitor) {
5703
            add_device_config(DEV_SERIAL, "mon:stdio");
5704
        } else if (default_virtcon && default_monitor) {
5705
            add_device_config(DEV_VIRTCON, "mon:stdio");
5706
        } else {
5707
            if (default_serial)
5708
                add_device_config(DEV_SERIAL, "stdio");
5709
            if (default_virtcon)
5710
                add_device_config(DEV_VIRTCON, "stdio");
5711
            if (default_monitor)
5712
                monitor_parse("stdio", "readline");
5713
        }
5714
    } else {
5715
        if (default_serial)
5716
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5717
        if (default_parallel)
5718
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5719
        if (default_monitor)
5720
            monitor_parse("vc:80Cx24C", "readline");
5721
        if (default_virtcon)
5722
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5723
    }
5724
    if (default_vga)
5725
        vga_interface_type = VGA_CIRRUS;
5726

    
5727
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5728
        exit(1);
5729

    
5730
#ifndef _WIN32
5731
    if (daemonize) {
5732
        pid_t pid;
5733

    
5734
        if (pipe(fds) == -1)
5735
            exit(1);
5736

    
5737
        pid = fork();
5738
        if (pid > 0) {
5739
            uint8_t status;
5740
            ssize_t len;
5741

    
5742
            close(fds[1]);
5743

    
5744
        again:
5745
            len = read(fds[0], &status, 1);
5746
            if (len == -1 && (errno == EINTR))
5747
                goto again;
5748

    
5749
            if (len != 1)
5750
                exit(1);
5751
            else if (status == 1) {
5752
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5753
                exit(1);
5754
            } else
5755
                exit(0);
5756
        } else if (pid < 0)
5757
            exit(1);
5758

    
5759
        close(fds[0]);
5760
        qemu_set_cloexec(fds[1]);
5761

    
5762
        setsid();
5763

    
5764
        pid = fork();
5765
        if (pid > 0)
5766
            exit(0);
5767
        else if (pid < 0)
5768
            exit(1);
5769

    
5770
        umask(027);
5771

    
5772
        signal(SIGTSTP, SIG_IGN);
5773
        signal(SIGTTOU, SIG_IGN);
5774
        signal(SIGTTIN, SIG_IGN);
5775
    }
5776
#endif
5777

    
5778
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5779
#ifndef _WIN32
5780
        if (daemonize) {
5781
            uint8_t status = 1;
5782
            if (write(fds[1], &status, 1) != 1) {
5783
                perror("daemonize. Writing to pipe\n");
5784
            }
5785
        } else
5786
#endif
5787
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5788
        exit(1);
5789
    }
5790

    
5791
    if (kvm_enabled()) {
5792
        int ret;
5793

    
5794
        ret = kvm_init(smp_cpus);
5795
        if (ret < 0) {
5796
            fprintf(stderr, "failed to initialize KVM\n");
5797
            exit(1);
5798
        }
5799
    }
5800

    
5801
    if (qemu_init_main_loop()) {
5802
        fprintf(stderr, "qemu_init_main_loop failed\n");
5803
        exit(1);
5804
    }
5805
    linux_boot = (kernel_filename != NULL);
5806

    
5807
    if (!linux_boot && *kernel_cmdline != '\0') {
5808
        fprintf(stderr, "-append only allowed with -kernel option\n");
5809
        exit(1);
5810
    }
5811

    
5812
    if (!linux_boot && initrd_filename != NULL) {
5813
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5814
        exit(1);
5815
    }
5816

    
5817
#ifndef _WIN32
5818
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5819
    setvbuf(stdout, NULL, _IOLBF, 0);
5820
#endif
5821

    
5822
    if (init_timer_alarm() < 0) {
5823
        fprintf(stderr, "could not initialize alarm timer\n");
5824
        exit(1);
5825
    }
5826
    if (use_icount && icount_time_shift < 0) {
5827
        use_icount = 2;
5828
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5829
           It will be corrected fairly quickly anyway.  */
5830
        icount_time_shift = 3;
5831
        init_icount_adjust();
5832
    }
5833

    
5834
#ifdef _WIN32
5835
    socket_init();
5836
#endif
5837

    
5838
    if (net_init_clients() < 0) {
5839
        exit(1);
5840
    }
5841

    
5842
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5843
    net_set_boot_mask(net_boot);
5844

    
5845
    /* init the bluetooth world */
5846
    if (foreach_device_config(DEV_BT, bt_parse))
5847
        exit(1);
5848

    
5849
    /* init the memory */
5850
    if (ram_size == 0)
5851
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5852

    
5853
    /* init the dynamic translator */
5854
    cpu_exec_init_all(tb_size * 1024 * 1024);
5855

    
5856
    bdrv_init_with_whitelist();
5857

    
5858
    blk_mig_init();
5859

    
5860
    if (default_cdrom) {
5861
        /* we always create the cdrom drive, even if no disk is there */
5862
        drive_add(NULL, CDROM_ALIAS);
5863
    }
5864

    
5865
    if (default_floppy) {
5866
        /* we always create at least one floppy */
5867
        drive_add(NULL, FD_ALIAS, 0);
5868
    }
5869

    
5870
    if (default_sdcard) {
5871
        /* we always create one sd slot, even if no card is in it */
5872
        drive_add(NULL, SD_ALIAS);
5873
    }
5874

    
5875
    /* open the virtual block devices */
5876
    if (snapshot)
5877
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5878
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5879
        exit(1);
5880

    
5881
    vmstate_register(0, &vmstate_timers ,&timers_state);
5882
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5883
                         ram_load, NULL);
5884

    
5885
    if (nb_numa_nodes > 0) {
5886
        int i;
5887

    
5888
        if (nb_numa_nodes > smp_cpus) {
5889
            nb_numa_nodes = smp_cpus;
5890
        }
5891

    
5892
        /* If no memory size if given for any node, assume the default case
5893
         * and distribute the available memory equally across all nodes
5894
         */
5895
        for (i = 0; i < nb_numa_nodes; i++) {
5896
            if (node_mem[i] != 0)
5897
                break;
5898
        }
5899
        if (i == nb_numa_nodes) {
5900
            uint64_t usedmem = 0;
5901

    
5902
            /* On Linux, the each node's border has to be 8MB aligned,
5903
             * the final node gets the rest.
5904
             */
5905
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5906
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5907
                usedmem += node_mem[i];
5908
            }
5909
            node_mem[i] = ram_size - usedmem;
5910
        }
5911

    
5912
        for (i = 0; i < nb_numa_nodes; i++) {
5913
            if (node_cpumask[i] != 0)
5914
                break;
5915
        }
5916
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5917
         * must cope with this anyway, because there are BIOSes out there in
5918
         * real machines which also use this scheme.
5919
         */
5920
        if (i == nb_numa_nodes) {
5921
            for (i = 0; i < smp_cpus; i++) {
5922
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5923
            }
5924
        }
5925
    }
5926

    
5927
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5928
        exit(1);
5929
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5930
        exit(1);
5931
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5932
        exit(1);
5933
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5934
        exit(1);
5935

    
5936
    module_call_init(MODULE_INIT_DEVICE);
5937

    
5938
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5939
        exit(0);
5940

    
5941
    if (watchdog) {
5942
        i = select_watchdog(watchdog);
5943
        if (i > 0)
5944
            exit (i == 1 ? 1 : 0);
5945
    }
5946

    
5947
    if (machine->compat_props) {
5948
        qdev_prop_register_global_list(machine->compat_props);
5949
    }
5950
    qemu_add_globals();
5951

    
5952
    machine->init(ram_size, boot_devices,
5953
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5954

    
5955

    
5956
#ifndef _WIN32
5957
    /* must be after terminal init, SDL library changes signal handlers */
5958
    sighandler_setup();
5959
#endif
5960

    
5961
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5962
        for (i = 0; i < nb_numa_nodes; i++) {
5963
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5964
                env->numa_node = i;
5965
            }
5966
        }
5967
    }
5968

    
5969
    current_machine = machine;
5970

    
5971
    /* init USB devices */
5972
    if (usb_enabled) {
5973
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
5974
            exit(1);
5975
    }
5976

    
5977
    /* init generic devices */
5978
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5979
        exit(1);
5980

    
5981
    if (!display_state)
5982
        dumb_display_init();
5983
    /* just use the first displaystate for the moment */
5984
    ds = display_state;
5985

    
5986
    if (display_type == DT_DEFAULT) {
5987
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5988
        display_type = DT_SDL;
5989
#else
5990
        display_type = DT_VNC;
5991
        vnc_display = "localhost:0,to=99";
5992
        show_vnc_port = 1;
5993
#endif
5994
    }
5995
        
5996

    
5997
    switch (display_type) {
5998
    case DT_NOGRAPHIC:
5999
        break;
6000
#if defined(CONFIG_CURSES)
6001
    case DT_CURSES:
6002
        curses_display_init(ds, full_screen);
6003
        break;
6004
#endif
6005
#if defined(CONFIG_SDL)
6006
    case DT_SDL:
6007
        sdl_display_init(ds, full_screen, no_frame);
6008
        break;
6009
#elif defined(CONFIG_COCOA)
6010
    case DT_SDL:
6011
        cocoa_display_init(ds, full_screen);
6012
        break;
6013
#endif
6014
    case DT_VNC:
6015
        vnc_display_init(ds);
6016
        if (vnc_display_open(ds, vnc_display) < 0)
6017
            exit(1);
6018

    
6019
        if (show_vnc_port) {
6020
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6021
        }
6022
        break;
6023
    default:
6024
        break;
6025
    }
6026
    dpy_resize(ds);
6027

    
6028
    dcl = ds->listeners;
6029
    while (dcl != NULL) {
6030
        if (dcl->dpy_refresh != NULL) {
6031
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6032
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6033
        }
6034
        dcl = dcl->next;
6035
    }
6036

    
6037
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6038
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6039
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6040
    }
6041

    
6042
    text_consoles_set_display(display_state);
6043

    
6044
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6045
        exit(1);
6046

    
6047
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6048
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6049
                gdbstub_dev);
6050
        exit(1);
6051
    }
6052

    
6053
    qdev_machine_creation_done();
6054

    
6055
    if (rom_load_all() != 0) {
6056
        fprintf(stderr, "rom loading failed\n");
6057
        exit(1);
6058
    }
6059

    
6060
    qemu_system_reset();
6061
    if (loadvm) {
6062
        if (load_vmstate(cur_mon, loadvm) < 0) {
6063
            autostart = 0;
6064
        }
6065
    }
6066

    
6067
    if (incoming) {
6068
        qemu_start_incoming_migration(incoming);
6069
    } else if (autostart) {
6070
        vm_start();
6071
    }
6072

    
6073
#ifndef _WIN32
6074
    if (daemonize) {
6075
        uint8_t status = 0;
6076
        ssize_t len;
6077

    
6078
    again1:
6079
        len = write(fds[1], &status, 1);
6080
        if (len == -1 && (errno == EINTR))
6081
            goto again1;
6082

    
6083
        if (len != 1)
6084
            exit(1);
6085

    
6086
        if (chdir("/")) {
6087
            perror("not able to chdir to /");
6088
            exit(1);
6089
        }
6090
        TFR(fd = qemu_open("/dev/null", O_RDWR));
6091
        if (fd == -1)
6092
            exit(1);
6093
    }
6094

    
6095
    if (run_as) {
6096
        pwd = getpwnam(run_as);
6097
        if (!pwd) {
6098
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6099
            exit(1);
6100
        }
6101
    }
6102

    
6103
    if (chroot_dir) {
6104
        if (chroot(chroot_dir) < 0) {
6105
            fprintf(stderr, "chroot failed\n");
6106
            exit(1);
6107
        }
6108
        if (chdir("/")) {
6109
            perror("not able to chdir to /");
6110
            exit(1);
6111
        }
6112
    }
6113

    
6114
    if (run_as) {
6115
        if (setgid(pwd->pw_gid) < 0) {
6116
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6117
            exit(1);
6118
        }
6119
        if (setuid(pwd->pw_uid) < 0) {
6120
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6121
            exit(1);
6122
        }
6123
        if (setuid(0) != -1) {
6124
            fprintf(stderr, "Dropping privileges failed\n");
6125
            exit(1);
6126
        }
6127
    }
6128

    
6129
    if (daemonize) {
6130
        dup2(fd, 0);
6131
        dup2(fd, 1);
6132
        dup2(fd, 2);
6133

    
6134
        close(fd);
6135
    }
6136
#endif
6137

    
6138
    main_loop();
6139
    quit_timers();
6140
    net_cleanup();
6141

    
6142
    return 0;
6143
}