Statistics
| Branch: | Revision:

root / vl.c @ 291defbc

History | View | Annotate | Download (157.4 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
DisplayType display_type = DT_DEFAULT;
186
const char* keyboard_layout = NULL;
187
ram_addr_t ram_size;
188
const char *mem_path = NULL;
189
#ifdef MAP_POPULATE
190
int mem_prealloc = 0; /* force preallocation of physical target memory */
191
#endif
192
int nb_nics;
193
NICInfo nd_table[MAX_NICS];
194
int vm_running;
195
int autostart;
196
static int rtc_utc = 1;
197
static int rtc_date_offset = -1; /* -1 means no change */
198
QEMUClock *rtc_clock;
199
int vga_interface_type = VGA_NONE;
200
#ifdef TARGET_SPARC
201
int graphic_width = 1024;
202
int graphic_height = 768;
203
int graphic_depth = 8;
204
#else
205
int graphic_width = 800;
206
int graphic_height = 600;
207
int graphic_depth = 15;
208
#endif
209
static int full_screen = 0;
210
#ifdef CONFIG_SDL
211
static int no_frame = 0;
212
#endif
213
int no_quit = 0;
214
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
215
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
216
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
217
#ifdef TARGET_I386
218
int win2k_install_hack = 0;
219
int rtc_td_hack = 0;
220
#endif
221
int usb_enabled = 0;
222
int singlestep = 0;
223
int smp_cpus = 1;
224
int max_cpus = 0;
225
int smp_cores = 1;
226
int smp_threads = 1;
227
const char *vnc_display;
228
int acpi_enabled = 1;
229
int no_hpet = 0;
230
int fd_bootchk = 1;
231
int no_reboot = 0;
232
int no_shutdown = 0;
233
int cursor_hide = 1;
234
int graphic_rotate = 0;
235
uint8_t irq0override = 1;
236
#ifndef _WIN32
237
int daemonize = 0;
238
#endif
239
const char *watchdog;
240
const char *option_rom[MAX_OPTION_ROMS];
241
int nb_option_roms;
242
int semihosting_enabled = 0;
243
#ifdef TARGET_ARM
244
int old_param = 0;
245
#endif
246
const char *qemu_name;
247
int alt_grab = 0;
248
int ctrl_grab = 0;
249
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
250
unsigned int nb_prom_envs = 0;
251
const char *prom_envs[MAX_PROM_ENVS];
252
#endif
253
int boot_menu;
254

    
255
int nb_numa_nodes;
256
uint64_t node_mem[MAX_NODES];
257
uint64_t node_cpumask[MAX_NODES];
258

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

    
272
uint8_t qemu_uuid[16];
273

    
274
static QEMUBootSetHandler *boot_set_handler;
275
static void *boot_set_opaque;
276

    
277
#ifdef SIGRTMIN
278
#define SIG_IPI (SIGRTMIN+4)
279
#else
280
#define SIG_IPI SIGUSR1
281
#endif
282

    
283
static int default_serial = 1;
284
static int default_parallel = 1;
285
static int default_virtcon = 1;
286
static int default_monitor = 1;
287
static int default_vga = 1;
288
static int default_floppy = 1;
289
static int default_cdrom = 1;
290
static int default_sdcard = 1;
291

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

    
308
static int default_driver_check(QemuOpts *opts, void *opaque)
309
{
310
    const char *driver = qemu_opt_get(opts, "driver");
311
    int i;
312

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

    
323
/***********************************************************/
324
/* x86 ISA bus support */
325

    
326
target_phys_addr_t isa_mem_base = 0;
327
PicState2 *isa_pic;
328

    
329
/***********************************************************/
330
void hw_error(const char *fmt, ...)
331
{
332
    va_list ap;
333
    CPUState *env;
334

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

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

    
368
static QEMUBalloonEvent *qemu_balloon_event;
369
void *qemu_balloon_event_opaque;
370

    
371
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
372
{
373
    qemu_balloon_event = func;
374
    qemu_balloon_event_opaque = opaque;
375
}
376

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

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

    
397

    
398
/***********************************************************/
399
/* real time host monotonic timer */
400

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

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

    
425
static int64_t get_clock_realtime(void)
426
{
427
    struct timeval tv;
428

    
429
    gettimeofday(&tv, NULL);
430
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
431
}
432

    
433
#ifdef WIN32
434

    
435
static int64_t clock_freq;
436

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

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

    
456
#else
457

    
458
static int use_rt_clock;
459

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

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

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

    
506
/***********************************************************/
507
/* guest cycle counter */
508

    
509
typedef struct TimersState {
510
    int64_t cpu_ticks_prev;
511
    int64_t cpu_ticks_offset;
512
    int64_t cpu_clock_offset;
513
    int32_t cpu_ticks_enabled;
514
    int64_t dummy;
515
} TimersState;
516

    
517
TimersState timers_state;
518

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

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

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

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

    
573
/***********************************************************/
574
/* timers */
575

    
576
#define QEMU_CLOCK_REALTIME 0
577
#define QEMU_CLOCK_VIRTUAL  1
578
#define QEMU_CLOCK_HOST     2
579

    
580
struct QEMUClock {
581
    int type;
582
    /* XXX: add frequency */
583
};
584

    
585
struct QEMUTimer {
586
    QEMUClock *clock;
587
    int64_t expire_time;
588
    QEMUTimerCB *cb;
589
    void *opaque;
590
    struct QEMUTimer *next;
591
};
592

    
593
struct qemu_alarm_timer {
594
    char const *name;
595
    unsigned int flags;
596

    
597
    int (*start)(struct qemu_alarm_timer *t);
598
    void (*stop)(struct qemu_alarm_timer *t);
599
    void (*rearm)(struct qemu_alarm_timer *t);
600
    void *priv;
601
};
602

    
603
#define ALARM_FLAG_DYNTICKS  0x1
604
#define ALARM_FLAG_EXPIRED   0x2
605

    
606
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
607
{
608
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
609
}
610

    
611
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
612
{
613
    if (!alarm_has_dynticks(t))
614
        return;
615

    
616
    t->rearm(t);
617
}
618

    
619
/* TODO: MIN_TIMER_REARM_US should be optimized */
620
#define MIN_TIMER_REARM_US 250
621

    
622
static struct qemu_alarm_timer *alarm_timer;
623

    
624
#ifdef _WIN32
625

    
626
struct qemu_alarm_win32 {
627
    MMRESULT timerId;
628
    unsigned int period;
629
} alarm_win32_data = {0, 0};
630

    
631
static int win32_start_timer(struct qemu_alarm_timer *t);
632
static void win32_stop_timer(struct qemu_alarm_timer *t);
633
static void win32_rearm_timer(struct qemu_alarm_timer *t);
634

    
635
#else
636

    
637
static int unix_start_timer(struct qemu_alarm_timer *t);
638
static void unix_stop_timer(struct qemu_alarm_timer *t);
639

    
640
#ifdef __linux__
641

    
642
static int dynticks_start_timer(struct qemu_alarm_timer *t);
643
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
644
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
645

    
646
static int hpet_start_timer(struct qemu_alarm_timer *t);
647
static void hpet_stop_timer(struct qemu_alarm_timer *t);
648

    
649
static int rtc_start_timer(struct qemu_alarm_timer *t);
650
static void rtc_stop_timer(struct qemu_alarm_timer *t);
651

    
652
#endif /* __linux__ */
653

    
654
#endif /* _WIN32 */
655

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

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

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

    
692
static void icount_adjust_rt(void * opaque)
693
{
694
    qemu_mod_timer(icount_rt_timer,
695
                   qemu_get_clock(rt_clock) + 1000);
696
    icount_adjust();
697
}
698

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

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

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

    
741
static void show_available_alarms(void)
742
{
743
    int i;
744

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

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

    
759
    if (!strcmp(opt, "?")) {
760
        show_available_alarms();
761
        exit(0);
762
    }
763

    
764
    arg = qemu_strdup(opt);
765

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

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

    
779
        if (i < cur)
780
            /* Ignore */
781
            goto next;
782

    
783
        /* Swap */
784
        tmp = alarm_timers[i];
785
        alarm_timers[i] = alarm_timers[cur];
786
        alarm_timers[cur] = tmp;
787

    
788
        cur++;
789
next:
790
        name = strtok(NULL, ",");
791
    }
792

    
793
    qemu_free(arg);
794

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

    
805
#define QEMU_NUM_CLOCKS 3
806

    
807
QEMUClock *rt_clock;
808
QEMUClock *vm_clock;
809
QEMUClock *host_clock;
810

    
811
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
812

    
813
static QEMUClock *qemu_new_clock(int type)
814
{
815
    QEMUClock *clock;
816
    clock = qemu_mallocz(sizeof(QEMUClock));
817
    clock->type = type;
818
    return clock;
819
}
820

    
821
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
822
{
823
    QEMUTimer *ts;
824

    
825
    ts = qemu_mallocz(sizeof(QEMUTimer));
826
    ts->clock = clock;
827
    ts->cb = cb;
828
    ts->opaque = opaque;
829
    return ts;
830
}
831

    
832
void qemu_free_timer(QEMUTimer *ts)
833
{
834
    qemu_free(ts);
835
}
836

    
837
/* stop a timer, but do not dealloc it */
838
void qemu_del_timer(QEMUTimer *ts)
839
{
840
    QEMUTimer **pt, *t;
841

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

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

    
863
    qemu_del_timer(ts);
864

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

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

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

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

    
909
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
910
{
911
    QEMUTimer *ts;
912

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

    
921
        /* run the callback (the timer list can be modified) */
922
        ts->cb(ts->opaque);
923
    }
924
}
925

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

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

    
960
static void init_clocks(void)
961
{
962
    init_get_clock();
963
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
964
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
965
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
966

    
967
    rtc_clock = host_clock;
968
}
969

    
970
/* save a timer */
971
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
972
{
973
    uint64_t expire_time;
974

    
975
    if (qemu_timer_pending(ts)) {
976
        expire_time = ts->expire_time;
977
    } else {
978
        expire_time = -1;
979
    }
980
    qemu_put_be64(f, expire_time);
981
}
982

    
983
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
984
{
985
    uint64_t expire_time;
986

    
987
    expire_time = qemu_get_be64(f);
988
    if (expire_time != -1) {
989
        qemu_mod_timer(ts, expire_time);
990
    } else {
991
        qemu_del_timer(ts);
992
    }
993
}
994

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

    
1008
static void qemu_event_increment(void);
1009

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

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

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

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

    
1085
    if (delta < 0)
1086
        delta = 0;
1087

    
1088
    return delta;
1089
}
1090

    
1091
#if defined(__linux__)
1092
static uint64_t qemu_next_deadline_dyntick(void)
1093
{
1094
    int64_t delta;
1095
    int64_t rtdelta;
1096

    
1097
    if (use_icount)
1098
        delta = INT32_MAX;
1099
    else
1100
        delta = (qemu_next_deadline() + 999) / 1000;
1101

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

    
1109
    if (delta < MIN_TIMER_REARM_US)
1110
        delta = MIN_TIMER_REARM_US;
1111

    
1112
    return delta;
1113
}
1114
#endif
1115

    
1116
#ifndef _WIN32
1117

    
1118
/* Sets a specific flag */
1119
static int fcntl_setfl(int fd, int flag)
1120
{
1121
    int flags;
1122

    
1123
    flags = fcntl(fd, F_GETFL);
1124
    if (flags == -1)
1125
        return -errno;
1126

    
1127
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1128
        return -errno;
1129

    
1130
    return 0;
1131
}
1132

    
1133
#if defined(__linux__)
1134

    
1135
#define RTC_FREQ 1024
1136

    
1137
static void enable_sigio_timer(int fd)
1138
{
1139
    struct sigaction act;
1140

    
1141
    /* timer signal */
1142
    sigfillset(&act.sa_mask);
1143
    act.sa_flags = 0;
1144
    act.sa_handler = host_alarm_handler;
1145

    
1146
    sigaction(SIGIO, &act, NULL);
1147
    fcntl_setfl(fd, O_ASYNC);
1148
    fcntl(fd, F_SETOWN, getpid());
1149
}
1150

    
1151
static int hpet_start_timer(struct qemu_alarm_timer *t)
1152
{
1153
    struct hpet_info info;
1154
    int r, fd;
1155

    
1156
    fd = qemu_open("/dev/hpet", O_RDONLY);
1157
    if (fd < 0)
1158
        return -1;
1159

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

    
1169
    /* Check capabilities */
1170
    r = ioctl(fd, HPET_INFO, &info);
1171
    if (r < 0)
1172
        goto fail;
1173

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

    
1179
    /* Enable interrupt */
1180
    r = ioctl(fd, HPET_IE_ON, 0);
1181
    if (r < 0)
1182
        goto fail;
1183

    
1184
    enable_sigio_timer(fd);
1185
    t->priv = (void *)(long)fd;
1186

    
1187
    return 0;
1188
fail:
1189
    close(fd);
1190
    return -1;
1191
}
1192

    
1193
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1194
{
1195
    int fd = (long)t->priv;
1196

    
1197
    close(fd);
1198
}
1199

    
1200
static int rtc_start_timer(struct qemu_alarm_timer *t)
1201
{
1202
    int rtc_fd;
1203
    unsigned long current_rtc_freq = 0;
1204

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

    
1222
    enable_sigio_timer(rtc_fd);
1223

    
1224
    t->priv = (void *)(long)rtc_fd;
1225

    
1226
    return 0;
1227
}
1228

    
1229
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1230
{
1231
    int rtc_fd = (long)t->priv;
1232

    
1233
    close(rtc_fd);
1234
}
1235

    
1236
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1237
{
1238
    struct sigevent ev;
1239
    timer_t host_timer;
1240
    struct sigaction act;
1241

    
1242
    sigfillset(&act.sa_mask);
1243
    act.sa_flags = 0;
1244
    act.sa_handler = host_alarm_handler;
1245

    
1246
    sigaction(SIGALRM, &act, NULL);
1247

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

    
1257
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1258
        perror("timer_create");
1259

    
1260
        /* disable dynticks */
1261
        fprintf(stderr, "Dynamic Ticks disabled\n");
1262

    
1263
        return -1;
1264
    }
1265

    
1266
    t->priv = (void *)(long)host_timer;
1267

    
1268
    return 0;
1269
}
1270

    
1271
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1272
{
1273
    timer_t host_timer = (timer_t)(long)t->priv;
1274

    
1275
    timer_delete(host_timer);
1276
}
1277

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

    
1285
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1286
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1287
        !active_timers[QEMU_CLOCK_HOST])
1288
        return;
1289

    
1290
    nearest_delta_us = qemu_next_deadline_dyntick();
1291

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

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

    
1313
#endif /* defined(__linux__) */
1314

    
1315
static int unix_start_timer(struct qemu_alarm_timer *t)
1316
{
1317
    struct sigaction act;
1318
    struct itimerval itv;
1319
    int err;
1320

    
1321
    /* timer signal */
1322
    sigfillset(&act.sa_mask);
1323
    act.sa_flags = 0;
1324
    act.sa_handler = host_alarm_handler;
1325

    
1326
    sigaction(SIGALRM, &act, NULL);
1327

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

    
1334
    err = setitimer(ITIMER_REAL, &itv, NULL);
1335
    if (err)
1336
        return -1;
1337

    
1338
    return 0;
1339
}
1340

    
1341
static void unix_stop_timer(struct qemu_alarm_timer *t)
1342
{
1343
    struct itimerval itv;
1344

    
1345
    memset(&itv, 0, sizeof(itv));
1346
    setitimer(ITIMER_REAL, &itv, NULL);
1347
}
1348

    
1349
#endif /* !defined(_WIN32) */
1350

    
1351

    
1352
#ifdef _WIN32
1353

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

    
1360
    memset(&tc, 0, sizeof(tc));
1361
    timeGetDevCaps(&tc, sizeof(tc));
1362

    
1363
    data->period = tc.wPeriodMin;
1364
    timeBeginPeriod(data->period);
1365

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

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

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

    
1385
    return 0;
1386
}
1387

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

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

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

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

    
1405
    timeKillEvent(data->timerId);
1406

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

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

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

    
1422
#endif /* _WIN32 */
1423

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

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

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

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

    
1442
    alarm_timer = t;
1443

    
1444
    return 0;
1445

    
1446
fail:
1447
    return err;
1448
}
1449

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

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

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

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

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

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

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

    
1493
void rtc_change_mon_event(struct tm *tm)
1494
{
1495
    QObject *data;
1496

    
1497
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1498
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1499
    qobject_decref(data);
1500
}
1501

    
1502
static void configure_rtc_date_offset(const char *startdate, int legacy)
1503
{
1504
    time_t rtc_start_date;
1505
    struct tm tm;
1506

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

    
1541
static void configure_rtc(QemuOpts *opts)
1542
{
1543
    const char *value;
1544

    
1545
    value = qemu_opt_get(opts, "base");
1546
    if (value) {
1547
        if (!strcmp(value, "utc")) {
1548
            rtc_utc = 1;
1549
        } else if (!strcmp(value, "localtime")) {
1550
            rtc_utc = 0;
1551
        } else {
1552
            configure_rtc_date_offset(value, 0);
1553
        }
1554
    }
1555
    value = qemu_opt_get(opts, "clock");
1556
    if (value) {
1557
        if (!strcmp(value, "host")) {
1558
            rtc_clock = host_clock;
1559
        } else if (!strcmp(value, "vm")) {
1560
            rtc_clock = vm_clock;
1561
        } else {
1562
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1563
            exit(1);
1564
        }
1565
    }
1566
#ifdef CONFIG_TARGET_I386
1567
    value = qemu_opt_get(opts, "driftfix");
1568
    if (value) {
1569
        if (!strcmp(buf, "slew")) {
1570
            rtc_td_hack = 1;
1571
        } else if (!strcmp(buf, "none")) {
1572
            rtc_td_hack = 0;
1573
        } else {
1574
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1575
            exit(1);
1576
        }
1577
    }
1578
#endif
1579
}
1580

    
1581
#ifdef _WIN32
1582
static void socket_cleanup(void)
1583
{
1584
    WSACleanup();
1585
}
1586

    
1587
static int socket_init(void)
1588
{
1589
    WSADATA Data;
1590
    int ret, err;
1591

    
1592
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1593
    if (ret != 0) {
1594
        err = WSAGetLastError();
1595
        fprintf(stderr, "WSAStartup: %d\n", err);
1596
        return -1;
1597
    }
1598
    atexit(socket_cleanup);
1599
    return 0;
1600
}
1601
#endif
1602

    
1603
/***********************************************************/
1604
/* Bluetooth support */
1605
static int nb_hcis;
1606
static int cur_hci;
1607
static struct HCIInfo *hci_table[MAX_NICS];
1608

    
1609
static struct bt_vlan_s {
1610
    struct bt_scatternet_s net;
1611
    int id;
1612
    struct bt_vlan_s *next;
1613
} *first_bt_vlan;
1614

    
1615
/* find or alloc a new bluetooth "VLAN" */
1616
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1617
{
1618
    struct bt_vlan_s **pvlan, *vlan;
1619
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1620
        if (vlan->id == id)
1621
            return &vlan->net;
1622
    }
1623
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1624
    vlan->id = id;
1625
    pvlan = &first_bt_vlan;
1626
    while (*pvlan != NULL)
1627
        pvlan = &(*pvlan)->next;
1628
    *pvlan = vlan;
1629
    return &vlan->net;
1630
}
1631

    
1632
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1633
{
1634
}
1635

    
1636
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1637
{
1638
    return -ENOTSUP;
1639
}
1640

    
1641
static struct HCIInfo null_hci = {
1642
    .cmd_send = null_hci_send,
1643
    .sco_send = null_hci_send,
1644
    .acl_send = null_hci_send,
1645
    .bdaddr_set = null_hci_addr_set,
1646
};
1647

    
1648
struct HCIInfo *qemu_next_hci(void)
1649
{
1650
    if (cur_hci == nb_hcis)
1651
        return &null_hci;
1652

    
1653
    return hci_table[cur_hci++];
1654
}
1655

    
1656
static struct HCIInfo *hci_init(const char *str)
1657
{
1658
    char *endp;
1659
    struct bt_scatternet_s *vlan = 0;
1660

    
1661
    if (!strcmp(str, "null"))
1662
        /* null */
1663
        return &null_hci;
1664
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1665
        /* host[:hciN] */
1666
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1667
    else if (!strncmp(str, "hci", 3)) {
1668
        /* hci[,vlan=n] */
1669
        if (str[3]) {
1670
            if (!strncmp(str + 3, ",vlan=", 6)) {
1671
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1672
                if (*endp)
1673
                    vlan = 0;
1674
            }
1675
        } else
1676
            vlan = qemu_find_bt_vlan(0);
1677
        if (vlan)
1678
           return bt_new_hci(vlan);
1679
    }
1680

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

    
1683
    return 0;
1684
}
1685

    
1686
static int bt_hci_parse(const char *str)
1687
{
1688
    struct HCIInfo *hci;
1689
    bdaddr_t bdaddr;
1690

    
1691
    if (nb_hcis >= MAX_NICS) {
1692
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1693
        return -1;
1694
    }
1695

    
1696
    hci = hci_init(str);
1697
    if (!hci)
1698
        return -1;
1699

    
1700
    bdaddr.b[0] = 0x52;
1701
    bdaddr.b[1] = 0x54;
1702
    bdaddr.b[2] = 0x00;
1703
    bdaddr.b[3] = 0x12;
1704
    bdaddr.b[4] = 0x34;
1705
    bdaddr.b[5] = 0x56 + nb_hcis;
1706
    hci->bdaddr_set(hci, bdaddr.b);
1707

    
1708
    hci_table[nb_hcis++] = hci;
1709

    
1710
    return 0;
1711
}
1712

    
1713
static void bt_vhci_add(int vlan_id)
1714
{
1715
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1716

    
1717
    if (!vlan->slave)
1718
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1719
                        "an empty scatternet %i\n", vlan_id);
1720

    
1721
    bt_vhci_init(bt_new_hci(vlan));
1722
}
1723

    
1724
static struct bt_device_s *bt_device_add(const char *opt)
1725
{
1726
    struct bt_scatternet_s *vlan;
1727
    int vlan_id = 0;
1728
    char *endp = strstr(opt, ",vlan=");
1729
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1730
    char devname[10];
1731

    
1732
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1733

    
1734
    if (endp) {
1735
        vlan_id = strtol(endp + 6, &endp, 0);
1736
        if (*endp) {
1737
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1738
            return 0;
1739
        }
1740
    }
1741

    
1742
    vlan = qemu_find_bt_vlan(vlan_id);
1743

    
1744
    if (!vlan->slave)
1745
        fprintf(stderr, "qemu: warning: adding a slave device to "
1746
                        "an empty scatternet %i\n", vlan_id);
1747

    
1748
    if (!strcmp(devname, "keyboard"))
1749
        return bt_keyboard_init(vlan);
1750

    
1751
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1752
    return 0;
1753
}
1754

    
1755
static int bt_parse(const char *opt)
1756
{
1757
    const char *endp, *p;
1758
    int vlan;
1759

    
1760
    if (strstart(opt, "hci", &endp)) {
1761
        if (!*endp || *endp == ',') {
1762
            if (*endp)
1763
                if (!strstart(endp, ",vlan=", 0))
1764
                    opt = endp + 1;
1765

    
1766
            return bt_hci_parse(opt);
1767
       }
1768
    } else if (strstart(opt, "vhci", &endp)) {
1769
        if (!*endp || *endp == ',') {
1770
            if (*endp) {
1771
                if (strstart(endp, ",vlan=", &p)) {
1772
                    vlan = strtol(p, (char **) &endp, 0);
1773
                    if (*endp) {
1774
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1775
                        return 1;
1776
                    }
1777
                } else {
1778
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1779
                    return 1;
1780
                }
1781
            } else
1782
                vlan = 0;
1783

    
1784
            bt_vhci_add(vlan);
1785
            return 0;
1786
        }
1787
    } else if (strstart(opt, "device:", &endp))
1788
        return !bt_device_add(endp);
1789

    
1790
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1791
    return 1;
1792
}
1793

    
1794
/***********************************************************/
1795
/* QEMU Block devices */
1796

    
1797
#define HD_ALIAS "index=%d,media=disk"
1798
#define CDROM_ALIAS "index=2,media=cdrom"
1799
#define FD_ALIAS "index=%d,if=floppy"
1800
#define PFLASH_ALIAS "if=pflash"
1801
#define MTD_ALIAS "if=mtd"
1802
#define SD_ALIAS "index=0,if=sd"
1803

    
1804
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1805
{
1806
    va_list ap;
1807
    char optstr[1024];
1808
    QemuOpts *opts;
1809

    
1810
    va_start(ap, fmt);
1811
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1812
    va_end(ap);
1813

    
1814
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
1815
    if (!opts) {
1816
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1817
                __FUNCTION__, optstr);
1818
        return NULL;
1819
    }
1820
    if (file)
1821
        qemu_opt_set(opts, "file", file);
1822
    return opts;
1823
}
1824

    
1825
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1826
{
1827
    DriveInfo *dinfo;
1828

    
1829
    /* seek interface, bus and unit */
1830

    
1831
    QTAILQ_FOREACH(dinfo, &drives, next) {
1832
        if (dinfo->type == type &&
1833
            dinfo->bus == bus &&
1834
            dinfo->unit == unit)
1835
            return dinfo;
1836
    }
1837

    
1838
    return NULL;
1839
}
1840

    
1841
DriveInfo *drive_get_by_id(const char *id)
1842
{
1843
    DriveInfo *dinfo;
1844

    
1845
    QTAILQ_FOREACH(dinfo, &drives, next) {
1846
        if (strcmp(id, dinfo->id))
1847
            continue;
1848
        return dinfo;
1849
    }
1850
    return NULL;
1851
}
1852

    
1853
int drive_get_max_bus(BlockInterfaceType type)
1854
{
1855
    int max_bus;
1856
    DriveInfo *dinfo;
1857

    
1858
    max_bus = -1;
1859
    QTAILQ_FOREACH(dinfo, &drives, next) {
1860
        if(dinfo->type == type &&
1861
           dinfo->bus > max_bus)
1862
            max_bus = dinfo->bus;
1863
    }
1864
    return max_bus;
1865
}
1866

    
1867
const char *drive_get_serial(BlockDriverState *bdrv)
1868
{
1869
    DriveInfo *dinfo;
1870

    
1871
    QTAILQ_FOREACH(dinfo, &drives, next) {
1872
        if (dinfo->bdrv == bdrv)
1873
            return dinfo->serial;
1874
    }
1875

    
1876
    return "\0";
1877
}
1878

    
1879
BlockInterfaceErrorAction drive_get_on_error(
1880
    BlockDriverState *bdrv, int is_read)
1881
{
1882
    DriveInfo *dinfo;
1883

    
1884
    QTAILQ_FOREACH(dinfo, &drives, next) {
1885
        if (dinfo->bdrv == bdrv)
1886
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1887
    }
1888

    
1889
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1890
}
1891

    
1892
static void bdrv_format_print(void *opaque, const char *name)
1893
{
1894
    fprintf(stderr, " %s", name);
1895
}
1896

    
1897
void drive_uninit(DriveInfo *dinfo)
1898
{
1899
    qemu_opts_del(dinfo->opts);
1900
    bdrv_delete(dinfo->bdrv);
1901
    QTAILQ_REMOVE(&drives, dinfo, next);
1902
    qemu_free(dinfo);
1903
}
1904

    
1905
static int parse_block_error_action(const char *buf, int is_read)
1906
{
1907
    if (!strcmp(buf, "ignore")) {
1908
        return BLOCK_ERR_IGNORE;
1909
    } else if (!is_read && !strcmp(buf, "enospc")) {
1910
        return BLOCK_ERR_STOP_ENOSPC;
1911
    } else if (!strcmp(buf, "stop")) {
1912
        return BLOCK_ERR_STOP_ANY;
1913
    } else if (!strcmp(buf, "report")) {
1914
        return BLOCK_ERR_REPORT;
1915
    } else {
1916
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1917
            buf, is_read ? "read" : "write");
1918
        return -1;
1919
    }
1920
}
1921

    
1922
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1923
                      int *fatal_error)
1924
{
1925
    const char *buf;
1926
    const char *file = NULL;
1927
    char devname[128];
1928
    const char *serial;
1929
    const char *mediastr = "";
1930
    BlockInterfaceType type;
1931
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1932
    int bus_id, unit_id;
1933
    int cyls, heads, secs, translation;
1934
    BlockDriver *drv = NULL;
1935
    QEMUMachine *machine = opaque;
1936
    int max_devs;
1937
    int index;
1938
    int cache;
1939
    int aio = 0;
1940
    int ro = 0;
1941
    int bdrv_flags;
1942
    int on_read_error, on_write_error;
1943
    const char *devaddr;
1944
    DriveInfo *dinfo;
1945
    int snapshot = 0;
1946

    
1947
    *fatal_error = 1;
1948

    
1949
    translation = BIOS_ATA_TRANSLATION_AUTO;
1950
    cache = 1;
1951

    
1952
    if (machine && machine->use_scsi) {
1953
        type = IF_SCSI;
1954
        max_devs = MAX_SCSI_DEVS;
1955
        pstrcpy(devname, sizeof(devname), "scsi");
1956
    } else {
1957
        type = IF_IDE;
1958
        max_devs = MAX_IDE_DEVS;
1959
        pstrcpy(devname, sizeof(devname), "ide");
1960
    }
1961
    media = MEDIA_DISK;
1962

    
1963
    /* extract parameters */
1964
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1965
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1966
    index   = qemu_opt_get_number(opts, "index", -1);
1967

    
1968
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1969
    heads = qemu_opt_get_number(opts, "heads", 0);
1970
    secs  = qemu_opt_get_number(opts, "secs", 0);
1971

    
1972
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1973
    ro = qemu_opt_get_bool(opts, "readonly", 0);
1974

    
1975
    file = qemu_opt_get(opts, "file");
1976
    serial = qemu_opt_get(opts, "serial");
1977

    
1978
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1979
        pstrcpy(devname, sizeof(devname), buf);
1980
        if (!strcmp(buf, "ide")) {
1981
            type = IF_IDE;
1982
            max_devs = MAX_IDE_DEVS;
1983
        } else if (!strcmp(buf, "scsi")) {
1984
            type = IF_SCSI;
1985
            max_devs = MAX_SCSI_DEVS;
1986
        } else if (!strcmp(buf, "floppy")) {
1987
            type = IF_FLOPPY;
1988
            max_devs = 0;
1989
        } else if (!strcmp(buf, "pflash")) {
1990
            type = IF_PFLASH;
1991
            max_devs = 0;
1992
        } else if (!strcmp(buf, "mtd")) {
1993
            type = IF_MTD;
1994
            max_devs = 0;
1995
        } else if (!strcmp(buf, "sd")) {
1996
            type = IF_SD;
1997
            max_devs = 0;
1998
        } else if (!strcmp(buf, "virtio")) {
1999
            type = IF_VIRTIO;
2000
            max_devs = 0;
2001
        } else if (!strcmp(buf, "xen")) {
2002
            type = IF_XEN;
2003
            max_devs = 0;
2004
        } else if (!strcmp(buf, "none")) {
2005
            type = IF_NONE;
2006
            max_devs = 0;
2007
        } else {
2008
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2009
            return NULL;
2010
        }
2011
    }
2012

    
2013
    if (cyls || heads || secs) {
2014
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2015
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2016
            return NULL;
2017
        }
2018
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
2019
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2020
            return NULL;
2021
        }
2022
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
2023
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2024
            return NULL;
2025
        }
2026
    }
2027

    
2028
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2029
        if (!cyls) {
2030
            fprintf(stderr,
2031
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2032
                    buf);
2033
            return NULL;
2034
        }
2035
        if (!strcmp(buf, "none"))
2036
            translation = BIOS_ATA_TRANSLATION_NONE;
2037
        else if (!strcmp(buf, "lba"))
2038
            translation = BIOS_ATA_TRANSLATION_LBA;
2039
        else if (!strcmp(buf, "auto"))
2040
            translation = BIOS_ATA_TRANSLATION_AUTO;
2041
        else {
2042
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2043
            return NULL;
2044
        }
2045
    }
2046

    
2047
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2048
        if (!strcmp(buf, "disk")) {
2049
            media = MEDIA_DISK;
2050
        } else if (!strcmp(buf, "cdrom")) {
2051
            if (cyls || secs || heads) {
2052
                fprintf(stderr,
2053
                        "qemu: '%s' invalid physical CHS format\n", buf);
2054
                return NULL;
2055
            }
2056
            media = MEDIA_CDROM;
2057
        } else {
2058
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2059
            return NULL;
2060
        }
2061
    }
2062

    
2063
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2064
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2065
            cache = 0;
2066
        else if (!strcmp(buf, "writethrough"))
2067
            cache = 1;
2068
        else if (!strcmp(buf, "writeback"))
2069
            cache = 2;
2070
        else {
2071
           fprintf(stderr, "qemu: invalid cache option\n");
2072
           return NULL;
2073
        }
2074
    }
2075

    
2076
#ifdef CONFIG_LINUX_AIO
2077
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2078
        if (!strcmp(buf, "threads"))
2079
            aio = 0;
2080
        else if (!strcmp(buf, "native"))
2081
            aio = 1;
2082
        else {
2083
           fprintf(stderr, "qemu: invalid aio option\n");
2084
           return NULL;
2085
        }
2086
    }
2087
#endif
2088

    
2089
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2090
       if (strcmp(buf, "?") == 0) {
2091
            fprintf(stderr, "qemu: Supported formats:");
2092
            bdrv_iterate_format(bdrv_format_print, NULL);
2093
            fprintf(stderr, "\n");
2094
            return NULL;
2095
        }
2096
        drv = bdrv_find_whitelisted_format(buf);
2097
        if (!drv) {
2098
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2099
            return NULL;
2100
        }
2101
    }
2102

    
2103
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2104
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2105
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2106
            fprintf(stderr, "werror is no supported by this format\n");
2107
            return NULL;
2108
        }
2109

    
2110
        on_write_error = parse_block_error_action(buf, 0);
2111
        if (on_write_error < 0) {
2112
            return NULL;
2113
        }
2114
    }
2115

    
2116
    on_read_error = BLOCK_ERR_REPORT;
2117
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2118
        if (type != IF_IDE && type != IF_VIRTIO) {
2119
            fprintf(stderr, "rerror is no supported by this format\n");
2120
            return NULL;
2121
        }
2122

    
2123
        on_read_error = parse_block_error_action(buf, 1);
2124
        if (on_read_error < 0) {
2125
            return NULL;
2126
        }
2127
    }
2128

    
2129
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2130
        if (type != IF_VIRTIO) {
2131
            fprintf(stderr, "addr is not supported\n");
2132
            return NULL;
2133
        }
2134
    }
2135

    
2136
    /* compute bus and unit according index */
2137

    
2138
    if (index != -1) {
2139
        if (bus_id != 0 || unit_id != -1) {
2140
            fprintf(stderr,
2141
                    "qemu: index cannot be used with bus and unit\n");
2142
            return NULL;
2143
        }
2144
        if (max_devs == 0)
2145
        {
2146
            unit_id = index;
2147
            bus_id = 0;
2148
        } else {
2149
            unit_id = index % max_devs;
2150
            bus_id = index / max_devs;
2151
        }
2152
    }
2153

    
2154
    /* if user doesn't specify a unit_id,
2155
     * try to find the first free
2156
     */
2157

    
2158
    if (unit_id == -1) {
2159
       unit_id = 0;
2160
       while (drive_get(type, bus_id, unit_id) != NULL) {
2161
           unit_id++;
2162
           if (max_devs && unit_id >= max_devs) {
2163
               unit_id -= max_devs;
2164
               bus_id++;
2165
           }
2166
       }
2167
    }
2168

    
2169
    /* check unit id */
2170

    
2171
    if (max_devs && unit_id >= max_devs) {
2172
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2173
                unit_id, max_devs - 1);
2174
        return NULL;
2175
    }
2176

    
2177
    /*
2178
     * ignore multiple definitions
2179
     */
2180

    
2181
    if (drive_get(type, bus_id, unit_id) != NULL) {
2182
        *fatal_error = 0;
2183
        return NULL;
2184
    }
2185

    
2186
    /* init */
2187

    
2188
    dinfo = qemu_mallocz(sizeof(*dinfo));
2189
    if ((buf = qemu_opts_id(opts)) != NULL) {
2190
        dinfo->id = qemu_strdup(buf);
2191
    } else {
2192
        /* no id supplied -> create one */
2193
        dinfo->id = qemu_mallocz(32);
2194
        if (type == IF_IDE || type == IF_SCSI)
2195
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2196
        if (max_devs)
2197
            snprintf(dinfo->id, 32, "%s%i%s%i",
2198
                     devname, bus_id, mediastr, unit_id);
2199
        else
2200
            snprintf(dinfo->id, 32, "%s%s%i",
2201
                     devname, mediastr, unit_id);
2202
    }
2203
    dinfo->bdrv = bdrv_new(dinfo->id);
2204
    dinfo->devaddr = devaddr;
2205
    dinfo->type = type;
2206
    dinfo->bus = bus_id;
2207
    dinfo->unit = unit_id;
2208
    dinfo->on_read_error = on_read_error;
2209
    dinfo->on_write_error = on_write_error;
2210
    dinfo->opts = opts;
2211
    if (serial)
2212
        strncpy(dinfo->serial, serial, sizeof(serial));
2213
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2214

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

    
2266
    if (aio == 1) {
2267
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2268
    } else {
2269
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2270
    }
2271

    
2272
    if (ro == 1) {
2273
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2274
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2275
            return NULL;
2276
        }
2277
    }
2278
    /* 
2279
     * cdrom is read-only. Set it now, after above interface checking
2280
     * since readonly attribute not explicitly required, so no error.
2281
     */
2282
    if (media == MEDIA_CDROM) {
2283
        ro = 1;
2284
    }
2285
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2286

    
2287
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2288
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2289
                        file, strerror(errno));
2290
        return NULL;
2291
    }
2292

    
2293
    if (bdrv_key_required(dinfo->bdrv))
2294
        autostart = 0;
2295
    *fatal_error = 0;
2296
    return dinfo;
2297
}
2298

    
2299
static int drive_init_func(QemuOpts *opts, void *opaque)
2300
{
2301
    QEMUMachine *machine = opaque;
2302
    int fatal_error = 0;
2303

    
2304
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2305
        if (fatal_error)
2306
            return 1;
2307
    }
2308
    return 0;
2309
}
2310

    
2311
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2312
{
2313
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2314
        qemu_opt_set(opts, "snapshot", "on");
2315
    }
2316
    return 0;
2317
}
2318

    
2319
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2320
{
2321
    boot_set_handler = func;
2322
    boot_set_opaque = opaque;
2323
}
2324

    
2325
int qemu_boot_set(const char *boot_devices)
2326
{
2327
    if (!boot_set_handler) {
2328
        return -EINVAL;
2329
    }
2330
    return boot_set_handler(boot_set_opaque, boot_devices);
2331
}
2332

    
2333
static int parse_bootdevices(char *devices)
2334
{
2335
    /* We just do some generic consistency checks */
2336
    const char *p;
2337
    int bitmap = 0;
2338

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

    
2362
static void restore_boot_devices(void *opaque)
2363
{
2364
    char *standard_boot_devices = opaque;
2365

    
2366
    qemu_boot_set(standard_boot_devices);
2367

    
2368
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2369
    qemu_free(standard_boot_devices);
2370
}
2371

    
2372
static void numa_add(const char *optarg)
2373
{
2374
    char option[128];
2375
    char *endptr;
2376
    unsigned long long value, endvalue;
2377
    int nodenr;
2378

    
2379
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2380
    if (!strcmp(option, "node")) {
2381
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2382
            nodenr = nb_numa_nodes;
2383
        } else {
2384
            nodenr = strtoull(option, NULL, 10);
2385
        }
2386

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

    
2428
static void smp_parse(const char *optarg)
2429
{
2430
    int smp, sockets = 0, threads = 0, cores = 0;
2431
    char *endptr;
2432
    char option[128];
2433

    
2434
    smp = strtoul(optarg, &endptr, 10);
2435
    if (endptr != optarg) {
2436
        if (*endptr == ',') {
2437
            endptr++;
2438
        }
2439
    }
2440
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2441
        sockets = strtoull(option, NULL, 10);
2442
    if (get_param_value(option, 128, "cores", endptr) != 0)
2443
        cores = strtoull(option, NULL, 10);
2444
    if (get_param_value(option, 128, "threads", endptr) != 0)
2445
        threads = strtoull(option, NULL, 10);
2446
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2447
        max_cpus = strtoull(option, NULL, 10);
2448

    
2449
    /* compute missing values, prefer sockets over cores over threads */
2450
    if (smp == 0 || sockets == 0) {
2451
        sockets = sockets > 0 ? sockets : 1;
2452
        cores = cores > 0 ? cores : 1;
2453
        threads = threads > 0 ? threads : 1;
2454
        if (smp == 0) {
2455
            smp = cores * threads * sockets;
2456
        }
2457
    } else {
2458
        if (cores == 0) {
2459
            threads = threads > 0 ? threads : 1;
2460
            cores = smp / (sockets * threads);
2461
        } else {
2462
            if (sockets) {
2463
                threads = smp / (cores * sockets);
2464
            }
2465
        }
2466
    }
2467
    smp_cpus = smp;
2468
    smp_cores = cores > 0 ? cores : 1;
2469
    smp_threads = threads > 0 ? threads : 1;
2470
    if (max_cpus == 0)
2471
        max_cpus = smp_cpus;
2472
}
2473

    
2474
/***********************************************************/
2475
/* USB devices */
2476

    
2477
static int usb_device_add(const char *devname, int is_hotplug)
2478
{
2479
    const char *p;
2480
    USBDevice *dev = NULL;
2481

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

    
2485
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2486
    dev = usbdevice_create(devname);
2487
    if (dev)
2488
        goto done;
2489

    
2490
    /* the other ones */
2491
    if (strstart(devname, "host:", &p)) {
2492
        dev = usb_host_device_open(p);
2493
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2494
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2495
                        bt_new_hci(qemu_find_bt_vlan(0)));
2496
    } else {
2497
        return -1;
2498
    }
2499
    if (!dev)
2500
        return -1;
2501

    
2502
done:
2503
    return 0;
2504
}
2505

    
2506
static int usb_device_del(const char *devname)
2507
{
2508
    int bus_num, addr;
2509
    const char *p;
2510

    
2511
    if (strstart(devname, "host:", &p))
2512
        return usb_host_device_close(p);
2513

    
2514
    if (!usb_enabled)
2515
        return -1;
2516

    
2517
    p = strchr(devname, '.');
2518
    if (!p)
2519
        return -1;
2520
    bus_num = strtoul(devname, NULL, 0);
2521
    addr = strtoul(p + 1, NULL, 0);
2522

    
2523
    return usb_device_delete_addr(bus_num, addr);
2524
}
2525

    
2526
static int usb_parse(const char *cmdline)
2527
{
2528
    int r;
2529
    r = usb_device_add(cmdline, 0);
2530
    if (r < 0) {
2531
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2532
    }
2533
    return r;
2534
}
2535

    
2536
void do_usb_add(Monitor *mon, const QDict *qdict)
2537
{
2538
    const char *devname = qdict_get_str(qdict, "devname");
2539
    if (usb_device_add(devname, 1) < 0) {
2540
        error_report("could not add USB device '%s'", devname);
2541
    }
2542
}
2543

    
2544
void do_usb_del(Monitor *mon, const QDict *qdict)
2545
{
2546
    const char *devname = qdict_get_str(qdict, "devname");
2547
    if (usb_device_del(devname) < 0) {
2548
        error_report("could not delete USB device '%s'", devname);
2549
    }
2550
}
2551

    
2552
/***********************************************************/
2553
/* PCMCIA/Cardbus */
2554

    
2555
static struct pcmcia_socket_entry_s {
2556
    PCMCIASocket *socket;
2557
    struct pcmcia_socket_entry_s *next;
2558
} *pcmcia_sockets = 0;
2559

    
2560
void pcmcia_socket_register(PCMCIASocket *socket)
2561
{
2562
    struct pcmcia_socket_entry_s *entry;
2563

    
2564
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2565
    entry->socket = socket;
2566
    entry->next = pcmcia_sockets;
2567
    pcmcia_sockets = entry;
2568
}
2569

    
2570
void pcmcia_socket_unregister(PCMCIASocket *socket)
2571
{
2572
    struct pcmcia_socket_entry_s *entry, **ptr;
2573

    
2574
    ptr = &pcmcia_sockets;
2575
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2576
        if (entry->socket == socket) {
2577
            *ptr = entry->next;
2578
            qemu_free(entry);
2579
        }
2580
}
2581

    
2582
void pcmcia_info(Monitor *mon)
2583
{
2584
    struct pcmcia_socket_entry_s *iter;
2585

    
2586
    if (!pcmcia_sockets)
2587
        monitor_printf(mon, "No PCMCIA sockets\n");
2588

    
2589
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2590
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2591
                       iter->socket->attached ? iter->socket->card_string :
2592
                       "Empty");
2593
}
2594

    
2595
/***********************************************************/
2596
/* I/O handling */
2597

    
2598
typedef struct IOHandlerRecord {
2599
    int fd;
2600
    IOCanRWHandler *fd_read_poll;
2601
    IOHandler *fd_read;
2602
    IOHandler *fd_write;
2603
    int deleted;
2604
    void *opaque;
2605
    /* temporary data */
2606
    struct pollfd *ufd;
2607
    struct IOHandlerRecord *next;
2608
} IOHandlerRecord;
2609

    
2610
static IOHandlerRecord *first_io_handler;
2611

    
2612
/* XXX: fd_read_poll should be suppressed, but an API change is
2613
   necessary in the character devices to suppress fd_can_read(). */
2614
int qemu_set_fd_handler2(int fd,
2615
                         IOCanRWHandler *fd_read_poll,
2616
                         IOHandler *fd_read,
2617
                         IOHandler *fd_write,
2618
                         void *opaque)
2619
{
2620
    IOHandlerRecord **pioh, *ioh;
2621

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

    
2653
int qemu_set_fd_handler(int fd,
2654
                        IOHandler *fd_read,
2655
                        IOHandler *fd_write,
2656
                        void *opaque)
2657
{
2658
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2659
}
2660

    
2661
#ifdef _WIN32
2662
/***********************************************************/
2663
/* Polling handling */
2664

    
2665
typedef struct PollingEntry {
2666
    PollingFunc *func;
2667
    void *opaque;
2668
    struct PollingEntry *next;
2669
} PollingEntry;
2670

    
2671
static PollingEntry *first_polling_entry;
2672

    
2673
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2674
{
2675
    PollingEntry **ppe, *pe;
2676
    pe = qemu_mallocz(sizeof(PollingEntry));
2677
    pe->func = func;
2678
    pe->opaque = opaque;
2679
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2680
    *ppe = pe;
2681
    return 0;
2682
}
2683

    
2684
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2685
{
2686
    PollingEntry **ppe, *pe;
2687
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2688
        pe = *ppe;
2689
        if (pe->func == func && pe->opaque == opaque) {
2690
            *ppe = pe->next;
2691
            qemu_free(pe);
2692
            break;
2693
        }
2694
    }
2695
}
2696

    
2697
/***********************************************************/
2698
/* Wait objects support */
2699
typedef struct WaitObjects {
2700
    int num;
2701
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2702
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2703
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2704
} WaitObjects;
2705

    
2706
static WaitObjects wait_objects = {0};
2707

    
2708
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2709
{
2710
    WaitObjects *w = &wait_objects;
2711

    
2712
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2713
        return -1;
2714
    w->events[w->num] = handle;
2715
    w->func[w->num] = func;
2716
    w->opaque[w->num] = opaque;
2717
    w->num++;
2718
    return 0;
2719
}
2720

    
2721
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2722
{
2723
    int i, found;
2724
    WaitObjects *w = &wait_objects;
2725

    
2726
    found = 0;
2727
    for (i = 0; i < w->num; i++) {
2728
        if (w->events[i] == handle)
2729
            found = 1;
2730
        if (found) {
2731
            w->events[i] = w->events[i + 1];
2732
            w->func[i] = w->func[i + 1];
2733
            w->opaque[i] = w->opaque[i + 1];
2734
        }
2735
    }
2736
    if (found)
2737
        w->num--;
2738
}
2739
#endif
2740

    
2741
/***********************************************************/
2742
/* ram save/restore */
2743

    
2744
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2745
#define RAM_SAVE_FLAG_COMPRESS        0x02
2746
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2747
#define RAM_SAVE_FLAG_PAGE        0x08
2748
#define RAM_SAVE_FLAG_EOS        0x10
2749

    
2750
static int is_dup_page(uint8_t *page, uint8_t ch)
2751
{
2752
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2753
    uint32_t *array = (uint32_t *)page;
2754
    int i;
2755

    
2756
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2757
        if (array[i] != val)
2758
            return 0;
2759
    }
2760

    
2761
    return 1;
2762
}
2763

    
2764
static int ram_save_block(QEMUFile *f)
2765
{
2766
    static ram_addr_t current_addr = 0;
2767
    ram_addr_t saved_addr = current_addr;
2768
    ram_addr_t addr = 0;
2769
    int found = 0;
2770

    
2771
    while (addr < last_ram_offset) {
2772
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2773
            uint8_t *p;
2774

    
2775
            cpu_physical_memory_reset_dirty(current_addr,
2776
                                            current_addr + TARGET_PAGE_SIZE,
2777
                                            MIGRATION_DIRTY_FLAG);
2778

    
2779
            p = qemu_get_ram_ptr(current_addr);
2780

    
2781
            if (is_dup_page(p, *p)) {
2782
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2783
                qemu_put_byte(f, *p);
2784
            } else {
2785
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2786
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2787
            }
2788

    
2789
            found = 1;
2790
            break;
2791
        }
2792
        addr += TARGET_PAGE_SIZE;
2793
        current_addr = (saved_addr + addr) % last_ram_offset;
2794
    }
2795

    
2796
    return found;
2797
}
2798

    
2799
static uint64_t bytes_transferred;
2800

    
2801
static ram_addr_t ram_save_remaining(void)
2802
{
2803
    ram_addr_t addr;
2804
    ram_addr_t count = 0;
2805

    
2806
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2807
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2808
            count++;
2809
    }
2810

    
2811
    return count;
2812
}
2813

    
2814
uint64_t ram_bytes_remaining(void)
2815
{
2816
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2817
}
2818

    
2819
uint64_t ram_bytes_transferred(void)
2820
{
2821
    return bytes_transferred;
2822
}
2823

    
2824
uint64_t ram_bytes_total(void)
2825
{
2826
    return last_ram_offset;
2827
}
2828

    
2829
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2830
{
2831
    ram_addr_t addr;
2832
    uint64_t bytes_transferred_last;
2833
    double bwidth = 0;
2834
    uint64_t expected_time = 0;
2835

    
2836
    if (stage < 0) {
2837
        cpu_physical_memory_set_dirty_tracking(0);
2838
        return 0;
2839
    }
2840

    
2841
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2842
        qemu_file_set_error(f);
2843
        return 0;
2844
    }
2845

    
2846
    if (stage == 1) {
2847
        bytes_transferred = 0;
2848

    
2849
        /* Make sure all dirty bits are set */
2850
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2851
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2852
                cpu_physical_memory_set_dirty(addr);
2853
        }
2854

    
2855
        /* Enable dirty memory tracking */
2856
        cpu_physical_memory_set_dirty_tracking(1);
2857

    
2858
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2859
    }
2860

    
2861
    bytes_transferred_last = bytes_transferred;
2862
    bwidth = qemu_get_clock_ns(rt_clock);
2863

    
2864
    while (!qemu_file_rate_limit(f)) {
2865
        int ret;
2866

    
2867
        ret = ram_save_block(f);
2868
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2869
        if (ret == 0) /* no more blocks */
2870
            break;
2871
    }
2872

    
2873
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2874
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2875

    
2876
    /* if we haven't transferred anything this round, force expected_time to a
2877
     * a very high value, but without crashing */
2878
    if (bwidth == 0)
2879
        bwidth = 0.000001;
2880

    
2881
    /* try transferring iterative blocks of memory */
2882
    if (stage == 3) {
2883
        /* flush all remaining blocks regardless of rate limiting */
2884
        while (ram_save_block(f) != 0) {
2885
            bytes_transferred += TARGET_PAGE_SIZE;
2886
        }
2887
        cpu_physical_memory_set_dirty_tracking(0);
2888
    }
2889

    
2890
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2891

    
2892
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2893

    
2894
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2895
}
2896

    
2897
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2898
{
2899
    ram_addr_t addr;
2900
    int flags;
2901

    
2902
    if (version_id != 3)
2903
        return -EINVAL;
2904

    
2905
    do {
2906
        addr = qemu_get_be64(f);
2907

    
2908
        flags = addr & ~TARGET_PAGE_MASK;
2909
        addr &= TARGET_PAGE_MASK;
2910

    
2911
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2912
            if (addr != last_ram_offset)
2913
                return -EINVAL;
2914
        }
2915

    
2916
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2917
            uint8_t ch = qemu_get_byte(f);
2918
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2919
#ifndef _WIN32
2920
            if (ch == 0 &&
2921
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2922
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2923
            }
2924
#endif
2925
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
2926
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2927
        }
2928
        if (qemu_file_has_error(f)) {
2929
            return -EIO;
2930
        }
2931
    } while (!(flags & RAM_SAVE_FLAG_EOS));
2932

    
2933
    return 0;
2934
}
2935

    
2936
void qemu_service_io(void)
2937
{
2938
    qemu_notify_event();
2939
}
2940

    
2941
/***********************************************************/
2942
/* machine registration */
2943

    
2944
static QEMUMachine *first_machine = NULL;
2945
QEMUMachine *current_machine = NULL;
2946

    
2947
int qemu_register_machine(QEMUMachine *m)
2948
{
2949
    QEMUMachine **pm;
2950
    pm = &first_machine;
2951
    while (*pm != NULL)
2952
        pm = &(*pm)->next;
2953
    m->next = NULL;
2954
    *pm = m;
2955
    return 0;
2956
}
2957

    
2958
static QEMUMachine *find_machine(const char *name)
2959
{
2960
    QEMUMachine *m;
2961

    
2962
    for(m = first_machine; m != NULL; m = m->next) {
2963
        if (!strcmp(m->name, name))
2964
            return m;
2965
        if (m->alias && !strcmp(m->alias, name))
2966
            return m;
2967
    }
2968
    return NULL;
2969
}
2970

    
2971
static QEMUMachine *find_default_machine(void)
2972
{
2973
    QEMUMachine *m;
2974

    
2975
    for(m = first_machine; m != NULL; m = m->next) {
2976
        if (m->is_default) {
2977
            return m;
2978
        }
2979
    }
2980
    return NULL;
2981
}
2982

    
2983
/***********************************************************/
2984
/* main execution loop */
2985

    
2986
static void gui_update(void *opaque)
2987
{
2988
    uint64_t interval = GUI_REFRESH_INTERVAL;
2989
    DisplayState *ds = opaque;
2990
    DisplayChangeListener *dcl = ds->listeners;
2991

    
2992
    qemu_flush_coalesced_mmio_buffer();
2993
    dpy_refresh(ds);
2994

    
2995
    while (dcl != NULL) {
2996
        if (dcl->gui_timer_interval &&
2997
            dcl->gui_timer_interval < interval)
2998
            interval = dcl->gui_timer_interval;
2999
        dcl = dcl->next;
3000
    }
3001
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3002
}
3003

    
3004
static void nographic_update(void *opaque)
3005
{
3006
    uint64_t interval = GUI_REFRESH_INTERVAL;
3007

    
3008
    qemu_flush_coalesced_mmio_buffer();
3009
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3010
}
3011

    
3012
void cpu_synchronize_all_states(void)
3013
{
3014
    CPUState *cpu;
3015

    
3016
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3017
        cpu_synchronize_state(cpu);
3018
    }
3019
}
3020

    
3021
void cpu_synchronize_all_post_reset(void)
3022
{
3023
    CPUState *cpu;
3024

    
3025
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3026
        cpu_synchronize_post_reset(cpu);
3027
    }
3028
}
3029

    
3030
void cpu_synchronize_all_post_init(void)
3031
{
3032
    CPUState *cpu;
3033

    
3034
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3035
        cpu_synchronize_post_init(cpu);
3036
    }
3037
}
3038

    
3039
struct vm_change_state_entry {
3040
    VMChangeStateHandler *cb;
3041
    void *opaque;
3042
    QLIST_ENTRY (vm_change_state_entry) entries;
3043
};
3044

    
3045
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3046

    
3047
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3048
                                                     void *opaque)
3049
{
3050
    VMChangeStateEntry *e;
3051

    
3052
    e = qemu_mallocz(sizeof (*e));
3053

    
3054
    e->cb = cb;
3055
    e->opaque = opaque;
3056
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3057
    return e;
3058
}
3059

    
3060
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3061
{
3062
    QLIST_REMOVE (e, entries);
3063
    qemu_free (e);
3064
}
3065

    
3066
static void vm_state_notify(int running, int reason)
3067
{
3068
    VMChangeStateEntry *e;
3069

    
3070
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3071
        e->cb(e->opaque, running, reason);
3072
    }
3073
}
3074

    
3075
static void resume_all_vcpus(void);
3076
static void pause_all_vcpus(void);
3077

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

    
3089
/* reset/shutdown handler */
3090

    
3091
typedef struct QEMUResetEntry {
3092
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3093
    QEMUResetHandler *func;
3094
    void *opaque;
3095
} QEMUResetEntry;
3096

    
3097
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3098
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3099
static int reset_requested;
3100
static int shutdown_requested;
3101
static int powerdown_requested;
3102
static int debug_requested;
3103
static int vmstop_requested;
3104

    
3105
int qemu_shutdown_requested(void)
3106
{
3107
    int r = shutdown_requested;
3108
    shutdown_requested = 0;
3109
    return r;
3110
}
3111

    
3112
int qemu_reset_requested(void)
3113
{
3114
    int r = reset_requested;
3115
    reset_requested = 0;
3116
    return r;
3117
}
3118

    
3119
int qemu_powerdown_requested(void)
3120
{
3121
    int r = powerdown_requested;
3122
    powerdown_requested = 0;
3123
    return r;
3124
}
3125

    
3126
static int qemu_debug_requested(void)
3127
{
3128
    int r = debug_requested;
3129
    debug_requested = 0;
3130
    return r;
3131
}
3132

    
3133
static int qemu_vmstop_requested(void)
3134
{
3135
    int r = vmstop_requested;
3136
    vmstop_requested = 0;
3137
    return r;
3138
}
3139

    
3140
static void do_vm_stop(int reason)
3141
{
3142
    if (vm_running) {
3143
        cpu_disable_ticks();
3144
        vm_running = 0;
3145
        pause_all_vcpus();
3146
        vm_state_notify(0, reason);
3147
        monitor_protocol_event(QEVENT_STOP, NULL);
3148
    }
3149
}
3150

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

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

    
3160
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3161
{
3162
    QEMUResetEntry *re;
3163

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

    
3173
void qemu_system_reset(void)
3174
{
3175
    QEMUResetEntry *re, *nre;
3176

    
3177
    /* reset all devices */
3178
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3179
        re->func(re->opaque);
3180
    }
3181
    monitor_protocol_event(QEVENT_RESET, NULL);
3182
    cpu_synchronize_all_post_reset();
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
            vm_stop(EXCP_DEBUG);
4096
        }
4097
        if (qemu_shutdown_requested()) {
4098
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4099
            if (no_shutdown) {
4100
                vm_stop(0);
4101
                no_shutdown = 0;
4102
            } else
4103
                break;
4104
        }
4105
        if (qemu_reset_requested()) {
4106
            pause_all_vcpus();
4107
            qemu_system_reset();
4108
            resume_all_vcpus();
4109
        }
4110
        if (qemu_powerdown_requested()) {
4111
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4112
            qemu_irq_raise(qemu_system_powerdown);
4113
        }
4114
        if ((r = qemu_vmstop_requested())) {
4115
            vm_stop(r);
4116
        }
4117
    }
4118
    pause_all_vcpus();
4119
}
4120

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

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

    
4154
#define HAS_ARG 0x0001
4155

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

    
4166
typedef struct QEMUOption {
4167
    const char *name;
4168
    int flags;
4169
    int index;
4170
} QEMUOption;
4171

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

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

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

    
4207
#ifdef CONFIG_CS4231A
4208
    {
4209
        "cs4231a",
4210
        "CS4231A",
4211
        0,
4212
        1,
4213
        { .init_isa = cs4231a_init }
4214
    },
4215
#endif
4216

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

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

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

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

    
4261
#endif /* HAS_AUDIO_CHOICE */
4262

    
4263
    { NULL, NULL, 0, 0, { NULL } }
4264
};
4265

    
4266
static void select_soundhw (const char *optarg)
4267
{
4268
    struct soundhw *c;
4269

    
4270
    if (*optarg == '?') {
4271
    show_valid_cards:
4272

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

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

    
4293
        p = optarg;
4294
        while (*p) {
4295
            e = strchr (p, ',');
4296
            l = !e ? strlen (p) : (size_t) (e - p);
4297

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

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

    
4319
        if (bad_card)
4320
            goto show_valid_cards;
4321
    }
4322
}
4323
#endif
4324

    
4325
static void select_vgahw (const char *p)
4326
{
4327
    const char *opts;
4328

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

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

    
4359
#ifdef TARGET_I386
4360
static int balloon_parse(const char *arg)
4361
{
4362
    QemuOpts *opts;
4363

    
4364
    if (strcmp(arg, "none") == 0) {
4365
        return 0;
4366
    }
4367

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

    
4382
    return -1;
4383
}
4384
#endif
4385

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

    
4394
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4395
{
4396
    int ret;
4397

    
4398
    if(strlen(str) != 36)
4399
        return -1;
4400

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

    
4405
    if(ret != 16)
4406
        return -1;
4407

    
4408
#ifdef TARGET_I386
4409
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4410
#endif
4411

    
4412
    return 0;
4413
}
4414

    
4415
#ifndef _WIN32
4416

    
4417
static void termsig_handler(int signal)
4418
{
4419
    qemu_system_shutdown_request();
4420
}
4421

    
4422
static void sigchld_handler(int signal)
4423
{
4424
    waitpid(-1, NULL, WNOHANG);
4425
}
4426

    
4427
static void sighandler_setup(void)
4428
{
4429
    struct sigaction act;
4430

    
4431
    memset(&act, 0, sizeof(act));
4432
    act.sa_handler = termsig_handler;
4433
    sigaction(SIGINT,  &act, NULL);
4434
    sigaction(SIGHUP,  &act, NULL);
4435
    sigaction(SIGTERM, &act, NULL);
4436

    
4437
    act.sa_handler = sigchld_handler;
4438
    act.sa_flags = SA_NOCLDSTOP;
4439
    sigaction(SIGCHLD, &act, NULL);
4440
}
4441

    
4442
#endif
4443

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

    
4452
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4453
    if (len == 0) {
4454
        return NULL;
4455
    }
4456

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

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

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

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

    
4524
    return res;
4525
}
4526
#undef SHARE_SUFFIX
4527
#undef BUILD_SUFFIX
4528
#endif
4529

    
4530
char *qemu_find_file(int type, const char *name)
4531
{
4532
    int len;
4533
    const char *subdir;
4534
    char *buf;
4535

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

    
4561
static int device_help_func(QemuOpts *opts, void *opaque)
4562
{
4563
    return qdev_device_help(opts);
4564
}
4565

    
4566
static int device_init_func(QemuOpts *opts, void *opaque)
4567
{
4568
    DeviceState *dev;
4569

    
4570
    dev = qdev_device_add(opts);
4571
    if (!dev)
4572
        return -1;
4573
    return 0;
4574
}
4575

    
4576
static int chardev_init_func(QemuOpts *opts, void *opaque)
4577
{
4578
    CharDriverState *chr;
4579

    
4580
    chr = qemu_chr_open_opts(opts, NULL);
4581
    if (!chr)
4582
        return -1;
4583
    return 0;
4584
}
4585

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

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

    
4606
    if (qemu_opt_get_bool(opts, "default", 0))
4607
        flags |= MONITOR_IS_DEFAULT;
4608

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

    
4616
    monitor_init(chr, flags);
4617
    return 0;
4618
}
4619

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

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

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

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

    
4671
static void add_device_config(int type, const char *cmdline)
4672
{
4673
    struct device_config *conf;
4674

    
4675
    conf = qemu_mallocz(sizeof(*conf));
4676
    conf->type = type;
4677
    conf->cmdline = cmdline;
4678
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4679
}
4680

    
4681
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4682
{
4683
    struct device_config *conf;
4684
    int rc;
4685

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

    
4696
static int serial_parse(const char *devname)
4697
{
4698
    static int index = 0;
4699
    char label[32];
4700

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

    
4718
static int parallel_parse(const char *devname)
4719
{
4720
    static int index = 0;
4721
    char label[32];
4722

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

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

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

    
4753
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4754
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4755

    
4756
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4757
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4758

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

    
4768
    index++;
4769
    return 0;
4770
}
4771

    
4772
static int debugcon_parse(const char *devname)
4773
{   
4774
    QemuOpts *opts;
4775

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

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

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

    
4823
    *poptarg = optarg;
4824
    *poptind = optind;
4825

    
4826
    return popt;
4827
}
4828

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

    
4863
    error_set_progname(argv[0]);
4864

    
4865
    init_clocks();
4866

    
4867
    qemu_cache_utils_init(envp);
4868

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

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

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

    
4916
    nb_numa_nodes = 0;
4917
    nb_nics = 0;
4918

    
4919
    tb_size = 0;
4920
    autostart= 1;
4921

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

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

    
4941
    if (defconfig) {
4942
        const char *fname;
4943
        FILE *fp;
4944

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

    
4954
        fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
4955
        fp = fopen(fname, "r");
4956
        if (fp) {
4957
            if (qemu_config_parse(fp, fname) != 0) {
4958
                exit(1);
4959
            }
4960
            fclose(fp);
4961
        }
4962
    }
4963
#if defined(cpudef_setup)
4964
    cpudef_setup(); /* parse cpu definitions in target config file */
4965
#endif
4966

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

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

    
5137
                    if (!strchr(optarg, '=')) {
5138
                        legacy = 1;
5139
                        pstrcpy(buf, sizeof(buf), optarg);
5140
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5141
                        fprintf(stderr,
5142
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5143
                                buf, optarg);
5144
                        exit(1);
5145
                    }
5146

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

    
5237
                value = strtoul(optarg, &ptr, 10);
5238
                switch (*ptr) {
5239
                case 0: case 'M': case 'm':
5240
                    value <<= 20;
5241
                    break;
5242
                case 'G': case 'g':
5243
                    value <<= 30;
5244
                    break;
5245
                default:
5246
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5247
                    exit(1);
5248
                }
5249

    
5250
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5251
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5252
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5253
                    exit(1);
5254
                }
5255
                if (value != (uint64_t)(ram_addr_t)value) {
5256
                    fprintf(stderr, "qemu: ram size too large\n");
5257
                    exit(1);
5258
                }
5259
                ram_size = value;
5260
                break;
5261
            }
5262
            case QEMU_OPTION_mempath:
5263
                mem_path = optarg;
5264
                break;
5265
#ifdef MAP_POPULATE
5266
            case QEMU_OPTION_mem_prealloc:
5267
                mem_prealloc = 1;
5268
                break;
5269
#endif
5270
            case QEMU_OPTION_d:
5271
                {
5272
                    int mask;
5273
                    const CPULogItem *item;
5274

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

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

    
5674
    /* If no data_dir is specified then try to find it relative to the
5675
       executable path.  */
5676
    if (!data_dir) {
5677
        data_dir = find_datadir(argv[0]);
5678
    }
5679
    /* If all else fails use the install patch specified when building.  */
5680
    if (!data_dir) {
5681
        data_dir = CONFIG_QEMU_SHAREDIR;
5682
    }
5683

    
5684
    /*
5685
     * Default to max_cpus = smp_cpus, in case the user doesn't
5686
     * specify a max_cpus value.
5687
     */
5688
    if (!max_cpus)
5689
        max_cpus = smp_cpus;
5690

    
5691
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5692
    if (smp_cpus > machine->max_cpus) {
5693
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5694
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5695
                machine->max_cpus);
5696
        exit(1);
5697
    }
5698

    
5699
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5700
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5701

    
5702
    if (machine->no_serial) {
5703
        default_serial = 0;
5704
    }
5705
    if (machine->no_parallel) {
5706
        default_parallel = 0;
5707
    }
5708
    if (!machine->use_virtcon) {
5709
        default_virtcon = 0;
5710
    }
5711
    if (machine->no_vga) {
5712
        default_vga = 0;
5713
    }
5714
    if (machine->no_floppy) {
5715
        default_floppy = 0;
5716
    }
5717
    if (machine->no_cdrom) {
5718
        default_cdrom = 0;
5719
    }
5720
    if (machine->no_sdcard) {
5721
        default_sdcard = 0;
5722
    }
5723

    
5724
    if (display_type == DT_NOGRAPHIC) {
5725
        if (default_parallel)
5726
            add_device_config(DEV_PARALLEL, "null");
5727
        if (default_serial && default_monitor) {
5728
            add_device_config(DEV_SERIAL, "mon:stdio");
5729
        } else if (default_virtcon && default_monitor) {
5730
            add_device_config(DEV_VIRTCON, "mon:stdio");
5731
        } else {
5732
            if (default_serial)
5733
                add_device_config(DEV_SERIAL, "stdio");
5734
            if (default_virtcon)
5735
                add_device_config(DEV_VIRTCON, "stdio");
5736
            if (default_monitor)
5737
                monitor_parse("stdio", "readline");
5738
        }
5739
    } else {
5740
        if (default_serial)
5741
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5742
        if (default_parallel)
5743
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5744
        if (default_monitor)
5745
            monitor_parse("vc:80Cx24C", "readline");
5746
        if (default_virtcon)
5747
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5748
    }
5749
    if (default_vga)
5750
        vga_interface_type = VGA_CIRRUS;
5751

    
5752
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5753
        exit(1);
5754

    
5755
#ifndef _WIN32
5756
    if (daemonize) {
5757
        pid_t pid;
5758

    
5759
        if (pipe(fds) == -1)
5760
            exit(1);
5761

    
5762
        pid = fork();
5763
        if (pid > 0) {
5764
            uint8_t status;
5765
            ssize_t len;
5766

    
5767
            close(fds[1]);
5768

    
5769
        again:
5770
            len = read(fds[0], &status, 1);
5771
            if (len == -1 && (errno == EINTR))
5772
                goto again;
5773

    
5774
            if (len != 1)
5775
                exit(1);
5776
            else if (status == 1) {
5777
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5778
                exit(1);
5779
            } else
5780
                exit(0);
5781
        } else if (pid < 0)
5782
            exit(1);
5783

    
5784
        close(fds[0]);
5785
        qemu_set_cloexec(fds[1]);
5786

    
5787
        setsid();
5788

    
5789
        pid = fork();
5790
        if (pid > 0)
5791
            exit(0);
5792
        else if (pid < 0)
5793
            exit(1);
5794

    
5795
        umask(027);
5796

    
5797
        signal(SIGTSTP, SIG_IGN);
5798
        signal(SIGTTOU, SIG_IGN);
5799
        signal(SIGTTIN, SIG_IGN);
5800
    }
5801
#endif
5802

    
5803
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5804
#ifndef _WIN32
5805
        if (daemonize) {
5806
            uint8_t status = 1;
5807
            if (write(fds[1], &status, 1) != 1) {
5808
                perror("daemonize. Writing to pipe\n");
5809
            }
5810
        } else
5811
#endif
5812
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5813
        exit(1);
5814
    }
5815

    
5816
    if (kvm_enabled()) {
5817
        int ret;
5818

    
5819
        ret = kvm_init(smp_cpus);
5820
        if (ret < 0) {
5821
            fprintf(stderr, "failed to initialize KVM\n");
5822
            exit(1);
5823
        }
5824
    }
5825

    
5826
    if (qemu_init_main_loop()) {
5827
        fprintf(stderr, "qemu_init_main_loop failed\n");
5828
        exit(1);
5829
    }
5830
    linux_boot = (kernel_filename != NULL);
5831

    
5832
    if (!linux_boot && *kernel_cmdline != '\0') {
5833
        fprintf(stderr, "-append only allowed with -kernel option\n");
5834
        exit(1);
5835
    }
5836

    
5837
    if (!linux_boot && initrd_filename != NULL) {
5838
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5839
        exit(1);
5840
    }
5841

    
5842
#ifndef _WIN32
5843
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5844
    setvbuf(stdout, NULL, _IOLBF, 0);
5845
#endif
5846

    
5847
    if (init_timer_alarm() < 0) {
5848
        fprintf(stderr, "could not initialize alarm timer\n");
5849
        exit(1);
5850
    }
5851
    if (use_icount && icount_time_shift < 0) {
5852
        use_icount = 2;
5853
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5854
           It will be corrected fairly quickly anyway.  */
5855
        icount_time_shift = 3;
5856
        init_icount_adjust();
5857
    }
5858

    
5859
#ifdef _WIN32
5860
    socket_init();
5861
#endif
5862

    
5863
    if (net_init_clients() < 0) {
5864
        exit(1);
5865
    }
5866

    
5867
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5868
    net_set_boot_mask(net_boot);
5869

    
5870
    /* init the bluetooth world */
5871
    if (foreach_device_config(DEV_BT, bt_parse))
5872
        exit(1);
5873

    
5874
    /* init the memory */
5875
    if (ram_size == 0)
5876
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5877

    
5878
    /* init the dynamic translator */
5879
    cpu_exec_init_all(tb_size * 1024 * 1024);
5880

    
5881
    bdrv_init_with_whitelist();
5882

    
5883
    blk_mig_init();
5884

    
5885
    if (default_cdrom) {
5886
        /* we always create the cdrom drive, even if no disk is there */
5887
        drive_add(NULL, CDROM_ALIAS);
5888
    }
5889

    
5890
    if (default_floppy) {
5891
        /* we always create at least one floppy */
5892
        drive_add(NULL, FD_ALIAS, 0);
5893
    }
5894

    
5895
    if (default_sdcard) {
5896
        /* we always create one sd slot, even if no card is in it */
5897
        drive_add(NULL, SD_ALIAS);
5898
    }
5899

    
5900
    /* open the virtual block devices */
5901
    if (snapshot)
5902
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5903
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5904
        exit(1);
5905

    
5906
    vmstate_register(0, &vmstate_timers ,&timers_state);
5907
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5908
                         ram_load, NULL);
5909

    
5910
    if (nb_numa_nodes > 0) {
5911
        int i;
5912

    
5913
        if (nb_numa_nodes > smp_cpus) {
5914
            nb_numa_nodes = smp_cpus;
5915
        }
5916

    
5917
        /* If no memory size if given for any node, assume the default case
5918
         * and distribute the available memory equally across all nodes
5919
         */
5920
        for (i = 0; i < nb_numa_nodes; i++) {
5921
            if (node_mem[i] != 0)
5922
                break;
5923
        }
5924
        if (i == nb_numa_nodes) {
5925
            uint64_t usedmem = 0;
5926

    
5927
            /* On Linux, the each node's border has to be 8MB aligned,
5928
             * the final node gets the rest.
5929
             */
5930
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5931
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5932
                usedmem += node_mem[i];
5933
            }
5934
            node_mem[i] = ram_size - usedmem;
5935
        }
5936

    
5937
        for (i = 0; i < nb_numa_nodes; i++) {
5938
            if (node_cpumask[i] != 0)
5939
                break;
5940
        }
5941
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5942
         * must cope with this anyway, because there are BIOSes out there in
5943
         * real machines which also use this scheme.
5944
         */
5945
        if (i == nb_numa_nodes) {
5946
            for (i = 0; i < smp_cpus; i++) {
5947
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5948
            }
5949
        }
5950
    }
5951

    
5952
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5953
        exit(1);
5954
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5955
        exit(1);
5956
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5957
        exit(1);
5958
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5959
        exit(1);
5960

    
5961
    module_call_init(MODULE_INIT_DEVICE);
5962

    
5963
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5964
        exit(0);
5965

    
5966
    if (watchdog) {
5967
        i = select_watchdog(watchdog);
5968
        if (i > 0)
5969
            exit (i == 1 ? 1 : 0);
5970
    }
5971

    
5972
    if (machine->compat_props) {
5973
        qdev_prop_register_global_list(machine->compat_props);
5974
    }
5975
    qemu_add_globals();
5976

    
5977
    machine->init(ram_size, boot_devices,
5978
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5979

    
5980
    cpu_synchronize_all_post_init();
5981

    
5982
#ifndef _WIN32
5983
    /* must be after terminal init, SDL library changes signal handlers */
5984
    sighandler_setup();
5985
#endif
5986

    
5987
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5988
        for (i = 0; i < nb_numa_nodes; i++) {
5989
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5990
                env->numa_node = i;
5991
            }
5992
        }
5993
    }
5994

    
5995
    current_machine = machine;
5996

    
5997
    /* init USB devices */
5998
    if (usb_enabled) {
5999
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
6000
            exit(1);
6001
    }
6002

    
6003
    /* init generic devices */
6004
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6005
        exit(1);
6006

    
6007
    net_check_clients();
6008

    
6009
    /* just use the first displaystate for the moment */
6010
    ds = get_displaystate();
6011

    
6012
    if (display_type == DT_DEFAULT) {
6013
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6014
        display_type = DT_SDL;
6015
#else
6016
        display_type = DT_VNC;
6017
        vnc_display = "localhost:0,to=99";
6018
        show_vnc_port = 1;
6019
#endif
6020
    }
6021
        
6022

    
6023
    switch (display_type) {
6024
    case DT_NOGRAPHIC:
6025
        break;
6026
#if defined(CONFIG_CURSES)
6027
    case DT_CURSES:
6028
        curses_display_init(ds, full_screen);
6029
        break;
6030
#endif
6031
#if defined(CONFIG_SDL)
6032
    case DT_SDL:
6033
        sdl_display_init(ds, full_screen, no_frame);
6034
        break;
6035
#elif defined(CONFIG_COCOA)
6036
    case DT_SDL:
6037
        cocoa_display_init(ds, full_screen);
6038
        break;
6039
#endif
6040
    case DT_VNC:
6041
        vnc_display_init(ds);
6042
        if (vnc_display_open(ds, vnc_display) < 0)
6043
            exit(1);
6044

    
6045
        if (show_vnc_port) {
6046
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6047
        }
6048
        break;
6049
    default:
6050
        break;
6051
    }
6052
    dpy_resize(ds);
6053

    
6054
    dcl = ds->listeners;
6055
    while (dcl != NULL) {
6056
        if (dcl->dpy_refresh != NULL) {
6057
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6058
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6059
        }
6060
        dcl = dcl->next;
6061
    }
6062

    
6063
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6064
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6065
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6066
    }
6067

    
6068
    text_consoles_set_display(ds);
6069

    
6070
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6071
        exit(1);
6072

    
6073
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6074
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6075
                gdbstub_dev);
6076
        exit(1);
6077
    }
6078

    
6079
    qdev_machine_creation_done();
6080

    
6081
    if (rom_load_all() != 0) {
6082
        fprintf(stderr, "rom loading failed\n");
6083
        exit(1);
6084
    }
6085

    
6086
    qemu_system_reset();
6087
    if (loadvm) {
6088
        if (load_vmstate(loadvm) < 0) {
6089
            autostart = 0;
6090
        }
6091
    }
6092

    
6093
    if (incoming) {
6094
        qemu_start_incoming_migration(incoming);
6095
    } else if (autostart) {
6096
        vm_start();
6097
    }
6098

    
6099
#ifndef _WIN32
6100
    if (daemonize) {
6101
        uint8_t status = 0;
6102
        ssize_t len;
6103

    
6104
    again1:
6105
        len = write(fds[1], &status, 1);
6106
        if (len == -1 && (errno == EINTR))
6107
            goto again1;
6108

    
6109
        if (len != 1)
6110
            exit(1);
6111

    
6112
        if (chdir("/")) {
6113
            perror("not able to chdir to /");
6114
            exit(1);
6115
        }
6116
        TFR(fd = qemu_open("/dev/null", O_RDWR));
6117
        if (fd == -1)
6118
            exit(1);
6119
    }
6120

    
6121
    if (run_as) {
6122
        pwd = getpwnam(run_as);
6123
        if (!pwd) {
6124
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6125
            exit(1);
6126
        }
6127
    }
6128

    
6129
    if (chroot_dir) {
6130
        if (chroot(chroot_dir) < 0) {
6131
            fprintf(stderr, "chroot failed\n");
6132
            exit(1);
6133
        }
6134
        if (chdir("/")) {
6135
            perror("not able to chdir to /");
6136
            exit(1);
6137
        }
6138
    }
6139

    
6140
    if (run_as) {
6141
        if (setgid(pwd->pw_gid) < 0) {
6142
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6143
            exit(1);
6144
        }
6145
        if (setuid(pwd->pw_uid) < 0) {
6146
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6147
            exit(1);
6148
        }
6149
        if (setuid(0) != -1) {
6150
            fprintf(stderr, "Dropping privileges failed\n");
6151
            exit(1);
6152
        }
6153
    }
6154

    
6155
    if (daemonize) {
6156
        dup2(fd, 0);
6157
        dup2(fd, 1);
6158
        dup2(fd, 2);
6159

    
6160
        close(fd);
6161
    }
6162
#endif
6163

    
6164
    main_loop();
6165
    quit_timers();
6166
    net_cleanup();
6167

    
6168
    return 0;
6169
}