Statistics
| Branch: | Revision:

root / vl.c @ a2aaa079

History | View | Annotate | Download (157.6 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
/* Conversion factor from emulated instructions to virtual clock ticks.  */
262
static int icount_time_shift;
263
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
264
#define MAX_ICOUNT_SHIFT 10
265
/* Compensate for varying guest execution speed.  */
266
static int64_t qemu_icount_bias;
267
static QEMUTimer *icount_rt_timer;
268
static QEMUTimer *icount_vm_timer;
269
static QEMUTimer *nographic_timer;
270

    
271
uint8_t qemu_uuid[16];
272

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
396

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

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

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

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

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

    
432
#ifdef WIN32
433

    
434
static int64_t clock_freq;
435

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

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

    
455
#else
456

    
457
static int use_rt_clock;
458

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

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

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

    
505
/***********************************************************/
506
/* guest cycle counter */
507

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

    
516
TimersState timers_state;
517

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

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

    
551
#ifndef CONFIG_IOTHREAD
552
static int64_t qemu_icount_delta(void)
553
{
554
    if (!use_icount) {
555
        return 5000 * (int64_t) 1000000;
556
    } else if (use_icount == 1) {
557
        /* When not using an adaptive execution frequency
558
           we tend to get badly out of sync with real time,
559
           so just delay for a reasonable amount of time.  */
560
        return 0;
561
    } else {
562
        return cpu_get_icount() - cpu_get_clock();
563
    }
564
}
565
#endif
566

    
567
/* enable cpu_get_ticks() */
568
void cpu_enable_ticks(void)
569
{
570
    if (!timers_state.cpu_ticks_enabled) {
571
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
572
        timers_state.cpu_clock_offset -= get_clock();
573
        timers_state.cpu_ticks_enabled = 1;
574
    }
575
}
576

    
577
/* disable cpu_get_ticks() : the clock is stopped. You must not call
578
   cpu_get_ticks() after that.  */
579
void cpu_disable_ticks(void)
580
{
581
    if (timers_state.cpu_ticks_enabled) {
582
        timers_state.cpu_ticks_offset = cpu_get_ticks();
583
        timers_state.cpu_clock_offset = cpu_get_clock();
584
        timers_state.cpu_ticks_enabled = 0;
585
    }
586
}
587

    
588
/***********************************************************/
589
/* timers */
590

    
591
#define QEMU_CLOCK_REALTIME 0
592
#define QEMU_CLOCK_VIRTUAL  1
593
#define QEMU_CLOCK_HOST     2
594

    
595
struct QEMUClock {
596
    int type;
597
    int enabled;
598
    /* XXX: add frequency */
599
};
600

    
601
struct QEMUTimer {
602
    QEMUClock *clock;
603
    int64_t expire_time;
604
    QEMUTimerCB *cb;
605
    void *opaque;
606
    struct QEMUTimer *next;
607
};
608

    
609
struct qemu_alarm_timer {
610
    char const *name;
611
    int (*start)(struct qemu_alarm_timer *t);
612
    void (*stop)(struct qemu_alarm_timer *t);
613
    void (*rearm)(struct qemu_alarm_timer *t);
614
    void *priv;
615

    
616
    char expired;
617
    char pending;
618
};
619

    
620
static struct qemu_alarm_timer *alarm_timer;
621

    
622
static inline int qemu_alarm_pending(void)
623
{
624
    return alarm_timer->pending;
625
}
626

    
627
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
628
{
629
    return !!t->rearm;
630
}
631

    
632
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
633
{
634
    if (!alarm_has_dynticks(t))
635
        return;
636

    
637
    t->rearm(t);
638
}
639

    
640
/* TODO: MIN_TIMER_REARM_US should be optimized */
641
#define MIN_TIMER_REARM_US 250
642

    
643
#ifdef _WIN32
644

    
645
struct qemu_alarm_win32 {
646
    MMRESULT timerId;
647
    unsigned int period;
648
} alarm_win32_data = {0, 0};
649

    
650
static int win32_start_timer(struct qemu_alarm_timer *t);
651
static void win32_stop_timer(struct qemu_alarm_timer *t);
652
static void win32_rearm_timer(struct qemu_alarm_timer *t);
653

    
654
#else
655

    
656
static int unix_start_timer(struct qemu_alarm_timer *t);
657
static void unix_stop_timer(struct qemu_alarm_timer *t);
658

    
659
#ifdef __linux__
660

    
661
static int dynticks_start_timer(struct qemu_alarm_timer *t);
662
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
663
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
664

    
665
static int hpet_start_timer(struct qemu_alarm_timer *t);
666
static void hpet_stop_timer(struct qemu_alarm_timer *t);
667

    
668
static int rtc_start_timer(struct qemu_alarm_timer *t);
669
static void rtc_stop_timer(struct qemu_alarm_timer *t);
670

    
671
#endif /* __linux__ */
672

    
673
#endif /* _WIN32 */
674

    
675
/* Correlation between real and virtual time is always going to be
676
   fairly approximate, so ignore small variation.
677
   When the guest is idle real and virtual time will be aligned in
678
   the IO wait loop.  */
679
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
680

    
681
static void icount_adjust(void)
682
{
683
    int64_t cur_time;
684
    int64_t cur_icount;
685
    int64_t delta;
686
    static int64_t last_delta;
687
    /* If the VM is not running, then do nothing.  */
688
    if (!vm_running)
689
        return;
690

    
691
    cur_time = cpu_get_clock();
692
    cur_icount = qemu_get_clock(vm_clock);
693
    delta = cur_icount - cur_time;
694
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
695
    if (delta > 0
696
        && last_delta + ICOUNT_WOBBLE < delta * 2
697
        && icount_time_shift > 0) {
698
        /* The guest is getting too far ahead.  Slow time down.  */
699
        icount_time_shift--;
700
    }
701
    if (delta < 0
702
        && last_delta - ICOUNT_WOBBLE > delta * 2
703
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
704
        /* The guest is getting too far behind.  Speed time up.  */
705
        icount_time_shift++;
706
    }
707
    last_delta = delta;
708
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
709
}
710

    
711
static void icount_adjust_rt(void * opaque)
712
{
713
    qemu_mod_timer(icount_rt_timer,
714
                   qemu_get_clock(rt_clock) + 1000);
715
    icount_adjust();
716
}
717

    
718
static void icount_adjust_vm(void * opaque)
719
{
720
    qemu_mod_timer(icount_vm_timer,
721
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
722
    icount_adjust();
723
}
724

    
725
static void configure_icount(const char *option)
726
{
727
    if (!option)
728
        return;
729

    
730
    if (strcmp(option, "auto") != 0) {
731
        icount_time_shift = strtol(option, NULL, 0);
732
        use_icount = 1;
733
        return;
734
    }
735

    
736
    use_icount = 2;
737

    
738
    /* 125MIPS seems a reasonable initial guess at the guest speed.
739
       It will be corrected fairly quickly anyway.  */
740
    icount_time_shift = 3;
741

    
742
    /* Have both realtime and virtual time triggers for speed adjustment.
743
       The realtime trigger catches emulated time passing too slowly,
744
       the virtual time trigger catches emulated time passing too fast.
745
       Realtime triggers occur even when idle, so use them less frequently
746
       than VM triggers.  */
747
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
748
    qemu_mod_timer(icount_rt_timer,
749
                   qemu_get_clock(rt_clock) + 1000);
750
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
751
    qemu_mod_timer(icount_vm_timer,
752
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
753
}
754

    
755
static int64_t qemu_icount_round(int64_t count)
756
{
757
    return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
758
}
759

    
760
static struct qemu_alarm_timer alarm_timers[] = {
761
#ifndef _WIN32
762
#ifdef __linux__
763
    {"dynticks", dynticks_start_timer,
764
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
765
    /* HPET - if available - is preferred */
766
    {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
767
    /* ...otherwise try RTC */
768
    {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
769
#endif
770
    {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
771
#else
772
    {"dynticks", win32_start_timer,
773
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
774
    {"win32", win32_start_timer,
775
     win32_stop_timer, NULL, &alarm_win32_data},
776
#endif
777
    {NULL, }
778
};
779

    
780
static void show_available_alarms(void)
781
{
782
    int i;
783

    
784
    printf("Available alarm timers, in order of precedence:\n");
785
    for (i = 0; alarm_timers[i].name; i++)
786
        printf("%s\n", alarm_timers[i].name);
787
}
788

    
789
static void configure_alarms(char const *opt)
790
{
791
    int i;
792
    int cur = 0;
793
    int count = ARRAY_SIZE(alarm_timers) - 1;
794
    char *arg;
795
    char *name;
796
    struct qemu_alarm_timer tmp;
797

    
798
    if (!strcmp(opt, "?")) {
799
        show_available_alarms();
800
        exit(0);
801
    }
802

    
803
    arg = qemu_strdup(opt);
804

    
805
    /* Reorder the array */
806
    name = strtok(arg, ",");
807
    while (name) {
808
        for (i = 0; i < count && alarm_timers[i].name; i++) {
809
            if (!strcmp(alarm_timers[i].name, name))
810
                break;
811
        }
812

    
813
        if (i == count) {
814
            fprintf(stderr, "Unknown clock %s\n", name);
815
            goto next;
816
        }
817

    
818
        if (i < cur)
819
            /* Ignore */
820
            goto next;
821

    
822
        /* Swap */
823
        tmp = alarm_timers[i];
824
        alarm_timers[i] = alarm_timers[cur];
825
        alarm_timers[cur] = tmp;
826

    
827
        cur++;
828
next:
829
        name = strtok(NULL, ",");
830
    }
831

    
832
    qemu_free(arg);
833

    
834
    if (cur) {
835
        /* Disable remaining timers */
836
        for (i = cur; i < count; i++)
837
            alarm_timers[i].name = NULL;
838
    } else {
839
        show_available_alarms();
840
        exit(1);
841
    }
842
}
843

    
844
#define QEMU_NUM_CLOCKS 3
845

    
846
QEMUClock *rt_clock;
847
QEMUClock *vm_clock;
848
QEMUClock *host_clock;
849

    
850
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
851

    
852
static QEMUClock *qemu_new_clock(int type)
853
{
854
    QEMUClock *clock;
855
    clock = qemu_mallocz(sizeof(QEMUClock));
856
    clock->type = type;
857
    clock->enabled = 1;
858
    return clock;
859
}
860

    
861
static void qemu_clock_enable(QEMUClock *clock, int enabled)
862
{
863
    clock->enabled = enabled;
864
}
865

    
866
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
867
{
868
    QEMUTimer *ts;
869

    
870
    ts = qemu_mallocz(sizeof(QEMUTimer));
871
    ts->clock = clock;
872
    ts->cb = cb;
873
    ts->opaque = opaque;
874
    return ts;
875
}
876

    
877
void qemu_free_timer(QEMUTimer *ts)
878
{
879
    qemu_free(ts);
880
}
881

    
882
/* stop a timer, but do not dealloc it */
883
void qemu_del_timer(QEMUTimer *ts)
884
{
885
    QEMUTimer **pt, *t;
886

    
887
    /* NOTE: this code must be signal safe because
888
       qemu_timer_expired() can be called from a signal. */
889
    pt = &active_timers[ts->clock->type];
890
    for(;;) {
891
        t = *pt;
892
        if (!t)
893
            break;
894
        if (t == ts) {
895
            *pt = t->next;
896
            break;
897
        }
898
        pt = &t->next;
899
    }
900
}
901

    
902
/* modify the current timer so that it will be fired when current_time
903
   >= expire_time. The corresponding callback will be called. */
904
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
905
{
906
    QEMUTimer **pt, *t;
907

    
908
    qemu_del_timer(ts);
909

    
910
    /* add the timer in the sorted list */
911
    /* NOTE: this code must be signal safe because
912
       qemu_timer_expired() can be called from a signal. */
913
    pt = &active_timers[ts->clock->type];
914
    for(;;) {
915
        t = *pt;
916
        if (!t)
917
            break;
918
        if (t->expire_time > expire_time)
919
            break;
920
        pt = &t->next;
921
    }
922
    ts->expire_time = expire_time;
923
    ts->next = *pt;
924
    *pt = ts;
925

    
926
    /* Rearm if necessary  */
927
    if (pt == &active_timers[ts->clock->type]) {
928
        if (!alarm_timer->pending) {
929
            qemu_rearm_alarm_timer(alarm_timer);
930
        }
931
        /* Interrupt execution to force deadline recalculation.  */
932
        if (use_icount)
933
            qemu_notify_event();
934
    }
935
}
936

    
937
int qemu_timer_pending(QEMUTimer *ts)
938
{
939
    QEMUTimer *t;
940
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
941
        if (t == ts)
942
            return 1;
943
    }
944
    return 0;
945
}
946

    
947
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
948
{
949
    if (!timer_head)
950
        return 0;
951
    return (timer_head->expire_time <= current_time);
952
}
953

    
954
static void qemu_run_timers(QEMUClock *clock)
955
{
956
    QEMUTimer **ptimer_head, *ts;
957
    int64_t current_time;
958
   
959
    if (!clock->enabled)
960
        return;
961

    
962
    current_time = qemu_get_clock (clock);
963
    ptimer_head = &active_timers[clock->type];
964
    for(;;) {
965
        ts = *ptimer_head;
966
        if (!ts || ts->expire_time > current_time)
967
            break;
968
        /* remove timer from the list before calling the callback */
969
        *ptimer_head = ts->next;
970
        ts->next = NULL;
971

    
972
        /* run the callback (the timer list can be modified) */
973
        ts->cb(ts->opaque);
974
    }
975
}
976

    
977
int64_t qemu_get_clock(QEMUClock *clock)
978
{
979
    switch(clock->type) {
980
    case QEMU_CLOCK_REALTIME:
981
        return get_clock() / 1000000;
982
    default:
983
    case QEMU_CLOCK_VIRTUAL:
984
        if (use_icount) {
985
            return cpu_get_icount();
986
        } else {
987
            return cpu_get_clock();
988
        }
989
    case QEMU_CLOCK_HOST:
990
        return get_clock_realtime();
991
    }
992
}
993

    
994
int64_t qemu_get_clock_ns(QEMUClock *clock)
995
{
996
    switch(clock->type) {
997
    case QEMU_CLOCK_REALTIME:
998
        return get_clock();
999
    default:
1000
    case QEMU_CLOCK_VIRTUAL:
1001
        if (use_icount) {
1002
            return cpu_get_icount();
1003
        } else {
1004
            return cpu_get_clock();
1005
        }
1006
    case QEMU_CLOCK_HOST:
1007
        return get_clock_realtime();
1008
    }
1009
}
1010

    
1011
static void init_clocks(void)
1012
{
1013
    init_get_clock();
1014
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1015
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1016
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1017

    
1018
    rtc_clock = host_clock;
1019
}
1020

    
1021
/* save a timer */
1022
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1023
{
1024
    uint64_t expire_time;
1025

    
1026
    if (qemu_timer_pending(ts)) {
1027
        expire_time = ts->expire_time;
1028
    } else {
1029
        expire_time = -1;
1030
    }
1031
    qemu_put_be64(f, expire_time);
1032
}
1033

    
1034
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1035
{
1036
    uint64_t expire_time;
1037

    
1038
    expire_time = qemu_get_be64(f);
1039
    if (expire_time != -1) {
1040
        qemu_mod_timer(ts, expire_time);
1041
    } else {
1042
        qemu_del_timer(ts);
1043
    }
1044
}
1045

    
1046
static const VMStateDescription vmstate_timers = {
1047
    .name = "timer",
1048
    .version_id = 2,
1049
    .minimum_version_id = 1,
1050
    .minimum_version_id_old = 1,
1051
    .fields      = (VMStateField []) {
1052
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
1053
        VMSTATE_INT64(dummy, TimersState),
1054
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1055
        VMSTATE_END_OF_LIST()
1056
    }
1057
};
1058

    
1059
static void qemu_run_all_timers(void)
1060
{
1061
    /* rearm timer, if not periodic */
1062
    if (alarm_timer->expired) {
1063
        alarm_timer->expired = 0;
1064
        qemu_rearm_alarm_timer(alarm_timer);
1065
    }
1066

    
1067
    alarm_timer->pending = 0;
1068

    
1069
    /* vm time timers */
1070
    if (vm_running) {
1071
        qemu_run_timers(vm_clock);
1072
    }
1073

    
1074
    qemu_run_timers(rt_clock);
1075
    qemu_run_timers(host_clock);
1076
}
1077

    
1078
#ifdef _WIN32
1079
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1080
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1081
                                        DWORD_PTR dw2)
1082
#else
1083
static void host_alarm_handler(int host_signum)
1084
#endif
1085
{
1086
    struct qemu_alarm_timer *t = alarm_timer;
1087
    if (!t)
1088
        return;
1089

    
1090
#if 0
1091
#define DISP_FREQ 1000
1092
    {
1093
        static int64_t delta_min = INT64_MAX;
1094
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1095
        static int count;
1096
        ti = qemu_get_clock(vm_clock);
1097
        if (last_clock != 0) {
1098
            delta = ti - last_clock;
1099
            if (delta < delta_min)
1100
                delta_min = delta;
1101
            if (delta > delta_max)
1102
                delta_max = delta;
1103
            delta_cum += delta;
1104
            if (++count == DISP_FREQ) {
1105
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1106
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1107
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1108
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1109
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1110
                count = 0;
1111
                delta_min = INT64_MAX;
1112
                delta_max = 0;
1113
                delta_cum = 0;
1114
            }
1115
        }
1116
        last_clock = ti;
1117
    }
1118
#endif
1119
    if (alarm_has_dynticks(t) ||
1120
        (!use_icount &&
1121
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1122
                               qemu_get_clock(vm_clock))) ||
1123
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1124
                           qemu_get_clock(rt_clock)) ||
1125
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1126
                           qemu_get_clock(host_clock))) {
1127

    
1128
        t->expired = alarm_has_dynticks(t);
1129
        t->pending = 1;
1130
        qemu_notify_event();
1131
    }
1132
}
1133

    
1134
static int64_t qemu_next_deadline(void)
1135
{
1136
    /* To avoid problems with overflow limit this to 2^32.  */
1137
    int64_t delta = INT32_MAX;
1138

    
1139
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1140
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1141
                     qemu_get_clock(vm_clock);
1142
    }
1143
    if (active_timers[QEMU_CLOCK_HOST]) {
1144
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1145
                 qemu_get_clock(host_clock);
1146
        if (hdelta < delta)
1147
            delta = hdelta;
1148
    }
1149

    
1150
    if (delta < 0)
1151
        delta = 0;
1152

    
1153
    return delta;
1154
}
1155

    
1156
#if defined(__linux__)
1157
static uint64_t qemu_next_deadline_dyntick(void)
1158
{
1159
    int64_t delta;
1160
    int64_t rtdelta;
1161

    
1162
    if (use_icount)
1163
        delta = INT32_MAX;
1164
    else
1165
        delta = (qemu_next_deadline() + 999) / 1000;
1166

    
1167
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1168
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1169
                 qemu_get_clock(rt_clock))*1000;
1170
        if (rtdelta < delta)
1171
            delta = rtdelta;
1172
    }
1173

    
1174
    if (delta < MIN_TIMER_REARM_US)
1175
        delta = MIN_TIMER_REARM_US;
1176

    
1177
    return delta;
1178
}
1179
#endif
1180

    
1181
#ifndef _WIN32
1182

    
1183
/* Sets a specific flag */
1184
static int fcntl_setfl(int fd, int flag)
1185
{
1186
    int flags;
1187

    
1188
    flags = fcntl(fd, F_GETFL);
1189
    if (flags == -1)
1190
        return -errno;
1191

    
1192
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1193
        return -errno;
1194

    
1195
    return 0;
1196
}
1197

    
1198
#if defined(__linux__)
1199

    
1200
#define RTC_FREQ 1024
1201

    
1202
static void enable_sigio_timer(int fd)
1203
{
1204
    struct sigaction act;
1205

    
1206
    /* timer signal */
1207
    sigfillset(&act.sa_mask);
1208
    act.sa_flags = 0;
1209
    act.sa_handler = host_alarm_handler;
1210

    
1211
    sigaction(SIGIO, &act, NULL);
1212
    fcntl_setfl(fd, O_ASYNC);
1213
    fcntl(fd, F_SETOWN, getpid());
1214
}
1215

    
1216
static int hpet_start_timer(struct qemu_alarm_timer *t)
1217
{
1218
    struct hpet_info info;
1219
    int r, fd;
1220

    
1221
    fd = qemu_open("/dev/hpet", O_RDONLY);
1222
    if (fd < 0)
1223
        return -1;
1224

    
1225
    /* Set frequency */
1226
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1227
    if (r < 0) {
1228
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1229
                "error, but for better emulation accuracy type:\n"
1230
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1231
        goto fail;
1232
    }
1233

    
1234
    /* Check capabilities */
1235
    r = ioctl(fd, HPET_INFO, &info);
1236
    if (r < 0)
1237
        goto fail;
1238

    
1239
    /* Enable periodic mode */
1240
    r = ioctl(fd, HPET_EPI, 0);
1241
    if (info.hi_flags && (r < 0))
1242
        goto fail;
1243

    
1244
    /* Enable interrupt */
1245
    r = ioctl(fd, HPET_IE_ON, 0);
1246
    if (r < 0)
1247
        goto fail;
1248

    
1249
    enable_sigio_timer(fd);
1250
    t->priv = (void *)(long)fd;
1251

    
1252
    return 0;
1253
fail:
1254
    close(fd);
1255
    return -1;
1256
}
1257

    
1258
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1259
{
1260
    int fd = (long)t->priv;
1261

    
1262
    close(fd);
1263
}
1264

    
1265
static int rtc_start_timer(struct qemu_alarm_timer *t)
1266
{
1267
    int rtc_fd;
1268
    unsigned long current_rtc_freq = 0;
1269

    
1270
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1271
    if (rtc_fd < 0)
1272
        return -1;
1273
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1274
    if (current_rtc_freq != RTC_FREQ &&
1275
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1276
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1277
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1278
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1279
        goto fail;
1280
    }
1281
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1282
    fail:
1283
        close(rtc_fd);
1284
        return -1;
1285
    }
1286

    
1287
    enable_sigio_timer(rtc_fd);
1288

    
1289
    t->priv = (void *)(long)rtc_fd;
1290

    
1291
    return 0;
1292
}
1293

    
1294
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1295
{
1296
    int rtc_fd = (long)t->priv;
1297

    
1298
    close(rtc_fd);
1299
}
1300

    
1301
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1302
{
1303
    struct sigevent ev;
1304
    timer_t host_timer;
1305
    struct sigaction act;
1306

    
1307
    sigfillset(&act.sa_mask);
1308
    act.sa_flags = 0;
1309
    act.sa_handler = host_alarm_handler;
1310

    
1311
    sigaction(SIGALRM, &act, NULL);
1312

    
1313
    /* 
1314
     * Initialize ev struct to 0 to avoid valgrind complaining
1315
     * about uninitialized data in timer_create call
1316
     */
1317
    memset(&ev, 0, sizeof(ev));
1318
    ev.sigev_value.sival_int = 0;
1319
    ev.sigev_notify = SIGEV_SIGNAL;
1320
    ev.sigev_signo = SIGALRM;
1321

    
1322
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1323
        perror("timer_create");
1324

    
1325
        /* disable dynticks */
1326
        fprintf(stderr, "Dynamic Ticks disabled\n");
1327

    
1328
        return -1;
1329
    }
1330

    
1331
    t->priv = (void *)(long)host_timer;
1332

    
1333
    return 0;
1334
}
1335

    
1336
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1337
{
1338
    timer_t host_timer = (timer_t)(long)t->priv;
1339

    
1340
    timer_delete(host_timer);
1341
}
1342

    
1343
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1344
{
1345
    timer_t host_timer = (timer_t)(long)t->priv;
1346
    struct itimerspec timeout;
1347
    int64_t nearest_delta_us = INT64_MAX;
1348
    int64_t current_us;
1349

    
1350
    assert(alarm_has_dynticks(t));
1351
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1352
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1353
        !active_timers[QEMU_CLOCK_HOST])
1354
        return;
1355

    
1356
    nearest_delta_us = qemu_next_deadline_dyntick();
1357

    
1358
    /* check whether a timer is already running */
1359
    if (timer_gettime(host_timer, &timeout)) {
1360
        perror("gettime");
1361
        fprintf(stderr, "Internal timer error: aborting\n");
1362
        exit(1);
1363
    }
1364
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1365
    if (current_us && current_us <= nearest_delta_us)
1366
        return;
1367

    
1368
    timeout.it_interval.tv_sec = 0;
1369
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1370
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1371
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1372
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1373
        perror("settime");
1374
        fprintf(stderr, "Internal timer error: aborting\n");
1375
        exit(1);
1376
    }
1377
}
1378

    
1379
#endif /* defined(__linux__) */
1380

    
1381
static int unix_start_timer(struct qemu_alarm_timer *t)
1382
{
1383
    struct sigaction act;
1384
    struct itimerval itv;
1385
    int err;
1386

    
1387
    /* timer signal */
1388
    sigfillset(&act.sa_mask);
1389
    act.sa_flags = 0;
1390
    act.sa_handler = host_alarm_handler;
1391

    
1392
    sigaction(SIGALRM, &act, NULL);
1393

    
1394
    itv.it_interval.tv_sec = 0;
1395
    /* for i386 kernel 2.6 to get 1 ms */
1396
    itv.it_interval.tv_usec = 999;
1397
    itv.it_value.tv_sec = 0;
1398
    itv.it_value.tv_usec = 10 * 1000;
1399

    
1400
    err = setitimer(ITIMER_REAL, &itv, NULL);
1401
    if (err)
1402
        return -1;
1403

    
1404
    return 0;
1405
}
1406

    
1407
static void unix_stop_timer(struct qemu_alarm_timer *t)
1408
{
1409
    struct itimerval itv;
1410

    
1411
    memset(&itv, 0, sizeof(itv));
1412
    setitimer(ITIMER_REAL, &itv, NULL);
1413
}
1414

    
1415
#endif /* !defined(_WIN32) */
1416

    
1417

    
1418
#ifdef _WIN32
1419

    
1420
static int win32_start_timer(struct qemu_alarm_timer *t)
1421
{
1422
    TIMECAPS tc;
1423
    struct qemu_alarm_win32 *data = t->priv;
1424
    UINT flags;
1425

    
1426
    memset(&tc, 0, sizeof(tc));
1427
    timeGetDevCaps(&tc, sizeof(tc));
1428

    
1429
    data->period = tc.wPeriodMin;
1430
    timeBeginPeriod(data->period);
1431

    
1432
    flags = TIME_CALLBACK_FUNCTION;
1433
    if (alarm_has_dynticks(t))
1434
        flags |= TIME_ONESHOT;
1435
    else
1436
        flags |= TIME_PERIODIC;
1437

    
1438
    data->timerId = timeSetEvent(1,         // interval (ms)
1439
                        data->period,       // resolution
1440
                        host_alarm_handler, // function
1441
                        (DWORD)t,           // parameter
1442
                        flags);
1443

    
1444
    if (!data->timerId) {
1445
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1446
                GetLastError());
1447
        timeEndPeriod(data->period);
1448
        return -1;
1449
    }
1450

    
1451
    return 0;
1452
}
1453

    
1454
static void win32_stop_timer(struct qemu_alarm_timer *t)
1455
{
1456
    struct qemu_alarm_win32 *data = t->priv;
1457

    
1458
    timeKillEvent(data->timerId);
1459
    timeEndPeriod(data->period);
1460
}
1461

    
1462
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1463
{
1464
    struct qemu_alarm_win32 *data = t->priv;
1465

    
1466
    assert(alarm_has_dynticks(t));
1467
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1468
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1469
        !active_timers[QEMU_CLOCK_HOST])
1470
        return;
1471

    
1472
    timeKillEvent(data->timerId);
1473

    
1474
    data->timerId = timeSetEvent(1,
1475
                        data->period,
1476
                        host_alarm_handler,
1477
                        (DWORD)t,
1478
                        TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1479

    
1480
    if (!data->timerId) {
1481
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1482
                GetLastError());
1483

    
1484
        timeEndPeriod(data->period);
1485
        exit(1);
1486
    }
1487
}
1488

    
1489
#endif /* _WIN32 */
1490

    
1491
static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1492
{
1493
    if (running)
1494
        qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1495
}
1496

    
1497
static int init_timer_alarm(void)
1498
{
1499
    struct qemu_alarm_timer *t = NULL;
1500
    int i, err = -1;
1501

    
1502
    for (i = 0; alarm_timers[i].name; i++) {
1503
        t = &alarm_timers[i];
1504

    
1505
        err = t->start(t);
1506
        if (!err)
1507
            break;
1508
    }
1509

    
1510
    if (err) {
1511
        err = -ENOENT;
1512
        goto fail;
1513
    }
1514

    
1515
    /* first event is at time 0 */
1516
    t->pending = 1;
1517
    alarm_timer = t;
1518
    qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1519

    
1520
    return 0;
1521

    
1522
fail:
1523
    return err;
1524
}
1525

    
1526
static void quit_timers(void)
1527
{
1528
    struct qemu_alarm_timer *t = alarm_timer;
1529
    alarm_timer = NULL;
1530
    t->stop(t);
1531
}
1532

    
1533
/***********************************************************/
1534
/* host time/date access */
1535
void qemu_get_timedate(struct tm *tm, int offset)
1536
{
1537
    time_t ti;
1538
    struct tm *ret;
1539

    
1540
    time(&ti);
1541
    ti += offset;
1542
    if (rtc_date_offset == -1) {
1543
        if (rtc_utc)
1544
            ret = gmtime(&ti);
1545
        else
1546
            ret = localtime(&ti);
1547
    } else {
1548
        ti -= rtc_date_offset;
1549
        ret = gmtime(&ti);
1550
    }
1551

    
1552
    memcpy(tm, ret, sizeof(struct tm));
1553
}
1554

    
1555
int qemu_timedate_diff(struct tm *tm)
1556
{
1557
    time_t seconds;
1558

    
1559
    if (rtc_date_offset == -1)
1560
        if (rtc_utc)
1561
            seconds = mktimegm(tm);
1562
        else
1563
            seconds = mktime(tm);
1564
    else
1565
        seconds = mktimegm(tm) + rtc_date_offset;
1566

    
1567
    return seconds - time(NULL);
1568
}
1569

    
1570
void rtc_change_mon_event(struct tm *tm)
1571
{
1572
    QObject *data;
1573

    
1574
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1575
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1576
    qobject_decref(data);
1577
}
1578

    
1579
static void configure_rtc_date_offset(const char *startdate, int legacy)
1580
{
1581
    time_t rtc_start_date;
1582
    struct tm tm;
1583

    
1584
    if (!strcmp(startdate, "now") && legacy) {
1585
        rtc_date_offset = -1;
1586
    } else {
1587
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1588
                   &tm.tm_year,
1589
                   &tm.tm_mon,
1590
                   &tm.tm_mday,
1591
                   &tm.tm_hour,
1592
                   &tm.tm_min,
1593
                   &tm.tm_sec) == 6) {
1594
            /* OK */
1595
        } else if (sscanf(startdate, "%d-%d-%d",
1596
                          &tm.tm_year,
1597
                          &tm.tm_mon,
1598
                          &tm.tm_mday) == 3) {
1599
            tm.tm_hour = 0;
1600
            tm.tm_min = 0;
1601
            tm.tm_sec = 0;
1602
        } else {
1603
            goto date_fail;
1604
        }
1605
        tm.tm_year -= 1900;
1606
        tm.tm_mon--;
1607
        rtc_start_date = mktimegm(&tm);
1608
        if (rtc_start_date == -1) {
1609
        date_fail:
1610
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1611
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1612
            exit(1);
1613
        }
1614
        rtc_date_offset = time(NULL) - rtc_start_date;
1615
    }
1616
}
1617

    
1618
static void configure_rtc(QemuOpts *opts)
1619
{
1620
    const char *value;
1621

    
1622
    value = qemu_opt_get(opts, "base");
1623
    if (value) {
1624
        if (!strcmp(value, "utc")) {
1625
            rtc_utc = 1;
1626
        } else if (!strcmp(value, "localtime")) {
1627
            rtc_utc = 0;
1628
        } else {
1629
            configure_rtc_date_offset(value, 0);
1630
        }
1631
    }
1632
    value = qemu_opt_get(opts, "clock");
1633
    if (value) {
1634
        if (!strcmp(value, "host")) {
1635
            rtc_clock = host_clock;
1636
        } else if (!strcmp(value, "vm")) {
1637
            rtc_clock = vm_clock;
1638
        } else {
1639
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1640
            exit(1);
1641
        }
1642
    }
1643
#ifdef CONFIG_TARGET_I386
1644
    value = qemu_opt_get(opts, "driftfix");
1645
    if (value) {
1646
        if (!strcmp(buf, "slew")) {
1647
            rtc_td_hack = 1;
1648
        } else if (!strcmp(buf, "none")) {
1649
            rtc_td_hack = 0;
1650
        } else {
1651
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1652
            exit(1);
1653
        }
1654
    }
1655
#endif
1656
}
1657

    
1658
#ifdef _WIN32
1659
static void socket_cleanup(void)
1660
{
1661
    WSACleanup();
1662
}
1663

    
1664
static int socket_init(void)
1665
{
1666
    WSADATA Data;
1667
    int ret, err;
1668

    
1669
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1670
    if (ret != 0) {
1671
        err = WSAGetLastError();
1672
        fprintf(stderr, "WSAStartup: %d\n", err);
1673
        return -1;
1674
    }
1675
    atexit(socket_cleanup);
1676
    return 0;
1677
}
1678
#endif
1679

    
1680
/***********************************************************/
1681
/* Bluetooth support */
1682
static int nb_hcis;
1683
static int cur_hci;
1684
static struct HCIInfo *hci_table[MAX_NICS];
1685

    
1686
static struct bt_vlan_s {
1687
    struct bt_scatternet_s net;
1688
    int id;
1689
    struct bt_vlan_s *next;
1690
} *first_bt_vlan;
1691

    
1692
/* find or alloc a new bluetooth "VLAN" */
1693
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1694
{
1695
    struct bt_vlan_s **pvlan, *vlan;
1696
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1697
        if (vlan->id == id)
1698
            return &vlan->net;
1699
    }
1700
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1701
    vlan->id = id;
1702
    pvlan = &first_bt_vlan;
1703
    while (*pvlan != NULL)
1704
        pvlan = &(*pvlan)->next;
1705
    *pvlan = vlan;
1706
    return &vlan->net;
1707
}
1708

    
1709
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1710
{
1711
}
1712

    
1713
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1714
{
1715
    return -ENOTSUP;
1716
}
1717

    
1718
static struct HCIInfo null_hci = {
1719
    .cmd_send = null_hci_send,
1720
    .sco_send = null_hci_send,
1721
    .acl_send = null_hci_send,
1722
    .bdaddr_set = null_hci_addr_set,
1723
};
1724

    
1725
struct HCIInfo *qemu_next_hci(void)
1726
{
1727
    if (cur_hci == nb_hcis)
1728
        return &null_hci;
1729

    
1730
    return hci_table[cur_hci++];
1731
}
1732

    
1733
static struct HCIInfo *hci_init(const char *str)
1734
{
1735
    char *endp;
1736
    struct bt_scatternet_s *vlan = 0;
1737

    
1738
    if (!strcmp(str, "null"))
1739
        /* null */
1740
        return &null_hci;
1741
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1742
        /* host[:hciN] */
1743
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1744
    else if (!strncmp(str, "hci", 3)) {
1745
        /* hci[,vlan=n] */
1746
        if (str[3]) {
1747
            if (!strncmp(str + 3, ",vlan=", 6)) {
1748
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1749
                if (*endp)
1750
                    vlan = 0;
1751
            }
1752
        } else
1753
            vlan = qemu_find_bt_vlan(0);
1754
        if (vlan)
1755
           return bt_new_hci(vlan);
1756
    }
1757

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

    
1760
    return 0;
1761
}
1762

    
1763
static int bt_hci_parse(const char *str)
1764
{
1765
    struct HCIInfo *hci;
1766
    bdaddr_t bdaddr;
1767

    
1768
    if (nb_hcis >= MAX_NICS) {
1769
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1770
        return -1;
1771
    }
1772

    
1773
    hci = hci_init(str);
1774
    if (!hci)
1775
        return -1;
1776

    
1777
    bdaddr.b[0] = 0x52;
1778
    bdaddr.b[1] = 0x54;
1779
    bdaddr.b[2] = 0x00;
1780
    bdaddr.b[3] = 0x12;
1781
    bdaddr.b[4] = 0x34;
1782
    bdaddr.b[5] = 0x56 + nb_hcis;
1783
    hci->bdaddr_set(hci, bdaddr.b);
1784

    
1785
    hci_table[nb_hcis++] = hci;
1786

    
1787
    return 0;
1788
}
1789

    
1790
static void bt_vhci_add(int vlan_id)
1791
{
1792
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1793

    
1794
    if (!vlan->slave)
1795
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1796
                        "an empty scatternet %i\n", vlan_id);
1797

    
1798
    bt_vhci_init(bt_new_hci(vlan));
1799
}
1800

    
1801
static struct bt_device_s *bt_device_add(const char *opt)
1802
{
1803
    struct bt_scatternet_s *vlan;
1804
    int vlan_id = 0;
1805
    char *endp = strstr(opt, ",vlan=");
1806
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1807
    char devname[10];
1808

    
1809
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1810

    
1811
    if (endp) {
1812
        vlan_id = strtol(endp + 6, &endp, 0);
1813
        if (*endp) {
1814
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1815
            return 0;
1816
        }
1817
    }
1818

    
1819
    vlan = qemu_find_bt_vlan(vlan_id);
1820

    
1821
    if (!vlan->slave)
1822
        fprintf(stderr, "qemu: warning: adding a slave device to "
1823
                        "an empty scatternet %i\n", vlan_id);
1824

    
1825
    if (!strcmp(devname, "keyboard"))
1826
        return bt_keyboard_init(vlan);
1827

    
1828
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1829
    return 0;
1830
}
1831

    
1832
static int bt_parse(const char *opt)
1833
{
1834
    const char *endp, *p;
1835
    int vlan;
1836

    
1837
    if (strstart(opt, "hci", &endp)) {
1838
        if (!*endp || *endp == ',') {
1839
            if (*endp)
1840
                if (!strstart(endp, ",vlan=", 0))
1841
                    opt = endp + 1;
1842

    
1843
            return bt_hci_parse(opt);
1844
       }
1845
    } else if (strstart(opt, "vhci", &endp)) {
1846
        if (!*endp || *endp == ',') {
1847
            if (*endp) {
1848
                if (strstart(endp, ",vlan=", &p)) {
1849
                    vlan = strtol(p, (char **) &endp, 0);
1850
                    if (*endp) {
1851
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1852
                        return 1;
1853
                    }
1854
                } else {
1855
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1856
                    return 1;
1857
                }
1858
            } else
1859
                vlan = 0;
1860

    
1861
            bt_vhci_add(vlan);
1862
            return 0;
1863
        }
1864
    } else if (strstart(opt, "device:", &endp))
1865
        return !bt_device_add(endp);
1866

    
1867
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1868
    return 1;
1869
}
1870

    
1871
/***********************************************************/
1872
/* QEMU Block devices */
1873

    
1874
#define HD_ALIAS "index=%d,media=disk"
1875
#define CDROM_ALIAS "index=2,media=cdrom"
1876
#define FD_ALIAS "index=%d,if=floppy"
1877
#define PFLASH_ALIAS "if=pflash"
1878
#define MTD_ALIAS "if=mtd"
1879
#define SD_ALIAS "index=0,if=sd"
1880

    
1881
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1882
{
1883
    va_list ap;
1884
    char optstr[1024];
1885
    QemuOpts *opts;
1886

    
1887
    va_start(ap, fmt);
1888
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1889
    va_end(ap);
1890

    
1891
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
1892
    if (!opts) {
1893
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1894
                __FUNCTION__, optstr);
1895
        return NULL;
1896
    }
1897
    if (file)
1898
        qemu_opt_set(opts, "file", file);
1899
    return opts;
1900
}
1901

    
1902
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1903
{
1904
    DriveInfo *dinfo;
1905

    
1906
    /* seek interface, bus and unit */
1907

    
1908
    QTAILQ_FOREACH(dinfo, &drives, next) {
1909
        if (dinfo->type == type &&
1910
            dinfo->bus == bus &&
1911
            dinfo->unit == unit)
1912
            return dinfo;
1913
    }
1914

    
1915
    return NULL;
1916
}
1917

    
1918
DriveInfo *drive_get_by_id(const char *id)
1919
{
1920
    DriveInfo *dinfo;
1921

    
1922
    QTAILQ_FOREACH(dinfo, &drives, next) {
1923
        if (strcmp(id, dinfo->id))
1924
            continue;
1925
        return dinfo;
1926
    }
1927
    return NULL;
1928
}
1929

    
1930
int drive_get_max_bus(BlockInterfaceType type)
1931
{
1932
    int max_bus;
1933
    DriveInfo *dinfo;
1934

    
1935
    max_bus = -1;
1936
    QTAILQ_FOREACH(dinfo, &drives, next) {
1937
        if(dinfo->type == type &&
1938
           dinfo->bus > max_bus)
1939
            max_bus = dinfo->bus;
1940
    }
1941
    return max_bus;
1942
}
1943

    
1944
const char *drive_get_serial(BlockDriverState *bdrv)
1945
{
1946
    DriveInfo *dinfo;
1947

    
1948
    QTAILQ_FOREACH(dinfo, &drives, next) {
1949
        if (dinfo->bdrv == bdrv)
1950
            return dinfo->serial;
1951
    }
1952

    
1953
    return "\0";
1954
}
1955

    
1956
BlockInterfaceErrorAction drive_get_on_error(
1957
    BlockDriverState *bdrv, int is_read)
1958
{
1959
    DriveInfo *dinfo;
1960

    
1961
    QTAILQ_FOREACH(dinfo, &drives, next) {
1962
        if (dinfo->bdrv == bdrv)
1963
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1964
    }
1965

    
1966
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1967
}
1968

    
1969
static void bdrv_format_print(void *opaque, const char *name)
1970
{
1971
    fprintf(stderr, " %s", name);
1972
}
1973

    
1974
void drive_uninit(DriveInfo *dinfo)
1975
{
1976
    qemu_opts_del(dinfo->opts);
1977
    bdrv_delete(dinfo->bdrv);
1978
    QTAILQ_REMOVE(&drives, dinfo, next);
1979
    qemu_free(dinfo);
1980
}
1981

    
1982
static int parse_block_error_action(const char *buf, int is_read)
1983
{
1984
    if (!strcmp(buf, "ignore")) {
1985
        return BLOCK_ERR_IGNORE;
1986
    } else if (!is_read && !strcmp(buf, "enospc")) {
1987
        return BLOCK_ERR_STOP_ENOSPC;
1988
    } else if (!strcmp(buf, "stop")) {
1989
        return BLOCK_ERR_STOP_ANY;
1990
    } else if (!strcmp(buf, "report")) {
1991
        return BLOCK_ERR_REPORT;
1992
    } else {
1993
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1994
            buf, is_read ? "read" : "write");
1995
        return -1;
1996
    }
1997
}
1998

    
1999
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2000
                      int *fatal_error)
2001
{
2002
    const char *buf;
2003
    const char *file = NULL;
2004
    char devname[128];
2005
    const char *serial;
2006
    const char *mediastr = "";
2007
    BlockInterfaceType type;
2008
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2009
    int bus_id, unit_id;
2010
    int cyls, heads, secs, translation;
2011
    BlockDriver *drv = NULL;
2012
    QEMUMachine *machine = opaque;
2013
    int max_devs;
2014
    int index;
2015
    int cache;
2016
    int aio = 0;
2017
    int ro = 0;
2018
    int bdrv_flags;
2019
    int on_read_error, on_write_error;
2020
    const char *devaddr;
2021
    DriveInfo *dinfo;
2022
    int snapshot = 0;
2023

    
2024
    *fatal_error = 1;
2025

    
2026
    translation = BIOS_ATA_TRANSLATION_AUTO;
2027
    cache = 1;
2028

    
2029
    if (machine && machine->use_scsi) {
2030
        type = IF_SCSI;
2031
        max_devs = MAX_SCSI_DEVS;
2032
        pstrcpy(devname, sizeof(devname), "scsi");
2033
    } else {
2034
        type = IF_IDE;
2035
        max_devs = MAX_IDE_DEVS;
2036
        pstrcpy(devname, sizeof(devname), "ide");
2037
    }
2038
    media = MEDIA_DISK;
2039

    
2040
    /* extract parameters */
2041
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
2042
    unit_id = qemu_opt_get_number(opts, "unit", -1);
2043
    index   = qemu_opt_get_number(opts, "index", -1);
2044

    
2045
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
2046
    heads = qemu_opt_get_number(opts, "heads", 0);
2047
    secs  = qemu_opt_get_number(opts, "secs", 0);
2048

    
2049
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2050
    ro = qemu_opt_get_bool(opts, "readonly", 0);
2051

    
2052
    file = qemu_opt_get(opts, "file");
2053
    serial = qemu_opt_get(opts, "serial");
2054

    
2055
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2056
        pstrcpy(devname, sizeof(devname), buf);
2057
        if (!strcmp(buf, "ide")) {
2058
            type = IF_IDE;
2059
            max_devs = MAX_IDE_DEVS;
2060
        } else if (!strcmp(buf, "scsi")) {
2061
            type = IF_SCSI;
2062
            max_devs = MAX_SCSI_DEVS;
2063
        } else if (!strcmp(buf, "floppy")) {
2064
            type = IF_FLOPPY;
2065
            max_devs = 0;
2066
        } else if (!strcmp(buf, "pflash")) {
2067
            type = IF_PFLASH;
2068
            max_devs = 0;
2069
        } else if (!strcmp(buf, "mtd")) {
2070
            type = IF_MTD;
2071
            max_devs = 0;
2072
        } else if (!strcmp(buf, "sd")) {
2073
            type = IF_SD;
2074
            max_devs = 0;
2075
        } else if (!strcmp(buf, "virtio")) {
2076
            type = IF_VIRTIO;
2077
            max_devs = 0;
2078
        } else if (!strcmp(buf, "xen")) {
2079
            type = IF_XEN;
2080
            max_devs = 0;
2081
        } else if (!strcmp(buf, "none")) {
2082
            type = IF_NONE;
2083
            max_devs = 0;
2084
        } else {
2085
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2086
            return NULL;
2087
        }
2088
    }
2089

    
2090
    if (cyls || heads || secs) {
2091
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2092
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2093
            return NULL;
2094
        }
2095
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
2096
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2097
            return NULL;
2098
        }
2099
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
2100
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2101
            return NULL;
2102
        }
2103
    }
2104

    
2105
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2106
        if (!cyls) {
2107
            fprintf(stderr,
2108
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2109
                    buf);
2110
            return NULL;
2111
        }
2112
        if (!strcmp(buf, "none"))
2113
            translation = BIOS_ATA_TRANSLATION_NONE;
2114
        else if (!strcmp(buf, "lba"))
2115
            translation = BIOS_ATA_TRANSLATION_LBA;
2116
        else if (!strcmp(buf, "auto"))
2117
            translation = BIOS_ATA_TRANSLATION_AUTO;
2118
        else {
2119
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2120
            return NULL;
2121
        }
2122
    }
2123

    
2124
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2125
        if (!strcmp(buf, "disk")) {
2126
            media = MEDIA_DISK;
2127
        } else if (!strcmp(buf, "cdrom")) {
2128
            if (cyls || secs || heads) {
2129
                fprintf(stderr,
2130
                        "qemu: '%s' invalid physical CHS format\n", buf);
2131
                return NULL;
2132
            }
2133
            media = MEDIA_CDROM;
2134
        } else {
2135
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2136
            return NULL;
2137
        }
2138
    }
2139

    
2140
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2141
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2142
            cache = 0;
2143
        else if (!strcmp(buf, "writethrough"))
2144
            cache = 1;
2145
        else if (!strcmp(buf, "writeback"))
2146
            cache = 2;
2147
        else {
2148
           fprintf(stderr, "qemu: invalid cache option\n");
2149
           return NULL;
2150
        }
2151
    }
2152

    
2153
#ifdef CONFIG_LINUX_AIO
2154
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2155
        if (!strcmp(buf, "threads"))
2156
            aio = 0;
2157
        else if (!strcmp(buf, "native"))
2158
            aio = 1;
2159
        else {
2160
           fprintf(stderr, "qemu: invalid aio option\n");
2161
           return NULL;
2162
        }
2163
    }
2164
#endif
2165

    
2166
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2167
       if (strcmp(buf, "?") == 0) {
2168
            fprintf(stderr, "qemu: Supported formats:");
2169
            bdrv_iterate_format(bdrv_format_print, NULL);
2170
            fprintf(stderr, "\n");
2171
            return NULL;
2172
        }
2173
        drv = bdrv_find_whitelisted_format(buf);
2174
        if (!drv) {
2175
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2176
            return NULL;
2177
        }
2178
    }
2179

    
2180
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2181
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2182
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2183
            fprintf(stderr, "werror is no supported by this format\n");
2184
            return NULL;
2185
        }
2186

    
2187
        on_write_error = parse_block_error_action(buf, 0);
2188
        if (on_write_error < 0) {
2189
            return NULL;
2190
        }
2191
    }
2192

    
2193
    on_read_error = BLOCK_ERR_REPORT;
2194
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2195
        if (type != IF_IDE && type != IF_VIRTIO) {
2196
            fprintf(stderr, "rerror is no supported by this format\n");
2197
            return NULL;
2198
        }
2199

    
2200
        on_read_error = parse_block_error_action(buf, 1);
2201
        if (on_read_error < 0) {
2202
            return NULL;
2203
        }
2204
    }
2205

    
2206
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2207
        if (type != IF_VIRTIO) {
2208
            fprintf(stderr, "addr is not supported\n");
2209
            return NULL;
2210
        }
2211
    }
2212

    
2213
    /* compute bus and unit according index */
2214

    
2215
    if (index != -1) {
2216
        if (bus_id != 0 || unit_id != -1) {
2217
            fprintf(stderr,
2218
                    "qemu: index cannot be used with bus and unit\n");
2219
            return NULL;
2220
        }
2221
        if (max_devs == 0)
2222
        {
2223
            unit_id = index;
2224
            bus_id = 0;
2225
        } else {
2226
            unit_id = index % max_devs;
2227
            bus_id = index / max_devs;
2228
        }
2229
    }
2230

    
2231
    /* if user doesn't specify a unit_id,
2232
     * try to find the first free
2233
     */
2234

    
2235
    if (unit_id == -1) {
2236
       unit_id = 0;
2237
       while (drive_get(type, bus_id, unit_id) != NULL) {
2238
           unit_id++;
2239
           if (max_devs && unit_id >= max_devs) {
2240
               unit_id -= max_devs;
2241
               bus_id++;
2242
           }
2243
       }
2244
    }
2245

    
2246
    /* check unit id */
2247

    
2248
    if (max_devs && unit_id >= max_devs) {
2249
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2250
                unit_id, max_devs - 1);
2251
        return NULL;
2252
    }
2253

    
2254
    /*
2255
     * ignore multiple definitions
2256
     */
2257

    
2258
    if (drive_get(type, bus_id, unit_id) != NULL) {
2259
        *fatal_error = 0;
2260
        return NULL;
2261
    }
2262

    
2263
    /* init */
2264

    
2265
    dinfo = qemu_mallocz(sizeof(*dinfo));
2266
    if ((buf = qemu_opts_id(opts)) != NULL) {
2267
        dinfo->id = qemu_strdup(buf);
2268
    } else {
2269
        /* no id supplied -> create one */
2270
        dinfo->id = qemu_mallocz(32);
2271
        if (type == IF_IDE || type == IF_SCSI)
2272
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2273
        if (max_devs)
2274
            snprintf(dinfo->id, 32, "%s%i%s%i",
2275
                     devname, bus_id, mediastr, unit_id);
2276
        else
2277
            snprintf(dinfo->id, 32, "%s%s%i",
2278
                     devname, mediastr, unit_id);
2279
    }
2280
    dinfo->bdrv = bdrv_new(dinfo->id);
2281
    dinfo->devaddr = devaddr;
2282
    dinfo->type = type;
2283
    dinfo->bus = bus_id;
2284
    dinfo->unit = unit_id;
2285
    dinfo->on_read_error = on_read_error;
2286
    dinfo->on_write_error = on_write_error;
2287
    dinfo->opts = opts;
2288
    if (serial)
2289
        strncpy(dinfo->serial, serial, sizeof(serial));
2290
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2291

    
2292
    switch(type) {
2293
    case IF_IDE:
2294
    case IF_SCSI:
2295
    case IF_XEN:
2296
    case IF_NONE:
2297
        switch(media) {
2298
        case MEDIA_DISK:
2299
            if (cyls != 0) {
2300
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2301
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2302
            }
2303
            break;
2304
        case MEDIA_CDROM:
2305
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2306
            break;
2307
        }
2308
        break;
2309
    case IF_SD:
2310
        /* FIXME: This isn't really a floppy, but it's a reasonable
2311
           approximation.  */
2312
    case IF_FLOPPY:
2313
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2314
        break;
2315
    case IF_PFLASH:
2316
    case IF_MTD:
2317
        break;
2318
    case IF_VIRTIO:
2319
        /* add virtio block device */
2320
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2321
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
2322
        qemu_opt_set(opts, "drive", dinfo->id);
2323
        if (devaddr)
2324
            qemu_opt_set(opts, "addr", devaddr);
2325
        break;
2326
    case IF_COUNT:
2327
        abort();
2328
    }
2329
    if (!file) {
2330
        *fatal_error = 0;
2331
        return NULL;
2332
    }
2333
    bdrv_flags = 0;
2334
    if (snapshot) {
2335
        bdrv_flags |= BDRV_O_SNAPSHOT;
2336
        cache = 2; /* always use write-back with snapshot */
2337
    }
2338
    if (cache == 0) /* no caching */
2339
        bdrv_flags |= BDRV_O_NOCACHE;
2340
    else if (cache == 2) /* write-back */
2341
        bdrv_flags |= BDRV_O_CACHE_WB;
2342

    
2343
    if (aio == 1) {
2344
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2345
    } else {
2346
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2347
    }
2348

    
2349
    if (ro == 1) {
2350
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2351
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2352
            return NULL;
2353
        }
2354
    }
2355
    /* 
2356
     * cdrom is read-only. Set it now, after above interface checking
2357
     * since readonly attribute not explicitly required, so no error.
2358
     */
2359
    if (media == MEDIA_CDROM) {
2360
        ro = 1;
2361
    }
2362
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2363

    
2364
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2365
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2366
                        file, strerror(errno));
2367
        return NULL;
2368
    }
2369

    
2370
    if (bdrv_key_required(dinfo->bdrv))
2371
        autostart = 0;
2372
    *fatal_error = 0;
2373
    return dinfo;
2374
}
2375

    
2376
static int drive_init_func(QemuOpts *opts, void *opaque)
2377
{
2378
    QEMUMachine *machine = opaque;
2379
    int fatal_error = 0;
2380

    
2381
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2382
        if (fatal_error)
2383
            return 1;
2384
    }
2385
    return 0;
2386
}
2387

    
2388
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2389
{
2390
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2391
        qemu_opt_set(opts, "snapshot", "on");
2392
    }
2393
    return 0;
2394
}
2395

    
2396
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2397
{
2398
    boot_set_handler = func;
2399
    boot_set_opaque = opaque;
2400
}
2401

    
2402
int qemu_boot_set(const char *boot_devices)
2403
{
2404
    if (!boot_set_handler) {
2405
        return -EINVAL;
2406
    }
2407
    return boot_set_handler(boot_set_opaque, boot_devices);
2408
}
2409

    
2410
static int parse_bootdevices(char *devices)
2411
{
2412
    /* We just do some generic consistency checks */
2413
    const char *p;
2414
    int bitmap = 0;
2415

    
2416
    for (p = devices; *p != '\0'; p++) {
2417
        /* Allowed boot devices are:
2418
         * a-b: floppy disk drives
2419
         * c-f: IDE disk drives
2420
         * g-m: machine implementation dependant drives
2421
         * n-p: network devices
2422
         * It's up to each machine implementation to check if the given boot
2423
         * devices match the actual hardware implementation and firmware
2424
         * features.
2425
         */
2426
        if (*p < 'a' || *p > 'p') {
2427
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2428
            exit(1);
2429
        }
2430
        if (bitmap & (1 << (*p - 'a'))) {
2431
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2432
            exit(1);
2433
        }
2434
        bitmap |= 1 << (*p - 'a');
2435
    }
2436
    return bitmap;
2437
}
2438

    
2439
static void restore_boot_devices(void *opaque)
2440
{
2441
    char *standard_boot_devices = opaque;
2442

    
2443
    qemu_boot_set(standard_boot_devices);
2444

    
2445
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2446
    qemu_free(standard_boot_devices);
2447
}
2448

    
2449
static void numa_add(const char *optarg)
2450
{
2451
    char option[128];
2452
    char *endptr;
2453
    unsigned long long value, endvalue;
2454
    int nodenr;
2455

    
2456
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2457
    if (!strcmp(option, "node")) {
2458
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2459
            nodenr = nb_numa_nodes;
2460
        } else {
2461
            nodenr = strtoull(option, NULL, 10);
2462
        }
2463

    
2464
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2465
            node_mem[nodenr] = 0;
2466
        } else {
2467
            value = strtoull(option, &endptr, 0);
2468
            switch (*endptr) {
2469
            case 0: case 'M': case 'm':
2470
                value <<= 20;
2471
                break;
2472
            case 'G': case 'g':
2473
                value <<= 30;
2474
                break;
2475
            }
2476
            node_mem[nodenr] = value;
2477
        }
2478
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2479
            node_cpumask[nodenr] = 0;
2480
        } else {
2481
            value = strtoull(option, &endptr, 10);
2482
            if (value >= 64) {
2483
                value = 63;
2484
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2485
            } else {
2486
                if (*endptr == '-') {
2487
                    endvalue = strtoull(endptr+1, &endptr, 10);
2488
                    if (endvalue >= 63) {
2489
                        endvalue = 62;
2490
                        fprintf(stderr,
2491
                            "only 63 CPUs in NUMA mode supported.\n");
2492
                    }
2493
                    value = (2ULL << endvalue) - (1ULL << value);
2494
                } else {
2495
                    value = 1ULL << value;
2496
                }
2497
            }
2498
            node_cpumask[nodenr] = value;
2499
        }
2500
        nb_numa_nodes++;
2501
    }
2502
    return;
2503
}
2504

    
2505
static void smp_parse(const char *optarg)
2506
{
2507
    int smp, sockets = 0, threads = 0, cores = 0;
2508
    char *endptr;
2509
    char option[128];
2510

    
2511
    smp = strtoul(optarg, &endptr, 10);
2512
    if (endptr != optarg) {
2513
        if (*endptr == ',') {
2514
            endptr++;
2515
        }
2516
    }
2517
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2518
        sockets = strtoull(option, NULL, 10);
2519
    if (get_param_value(option, 128, "cores", endptr) != 0)
2520
        cores = strtoull(option, NULL, 10);
2521
    if (get_param_value(option, 128, "threads", endptr) != 0)
2522
        threads = strtoull(option, NULL, 10);
2523
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2524
        max_cpus = strtoull(option, NULL, 10);
2525

    
2526
    /* compute missing values, prefer sockets over cores over threads */
2527
    if (smp == 0 || sockets == 0) {
2528
        sockets = sockets > 0 ? sockets : 1;
2529
        cores = cores > 0 ? cores : 1;
2530
        threads = threads > 0 ? threads : 1;
2531
        if (smp == 0) {
2532
            smp = cores * threads * sockets;
2533
        }
2534
    } else {
2535
        if (cores == 0) {
2536
            threads = threads > 0 ? threads : 1;
2537
            cores = smp / (sockets * threads);
2538
        } else {
2539
            if (sockets) {
2540
                threads = smp / (cores * sockets);
2541
            }
2542
        }
2543
    }
2544
    smp_cpus = smp;
2545
    smp_cores = cores > 0 ? cores : 1;
2546
    smp_threads = threads > 0 ? threads : 1;
2547
    if (max_cpus == 0)
2548
        max_cpus = smp_cpus;
2549
}
2550

    
2551
/***********************************************************/
2552
/* USB devices */
2553

    
2554
static int usb_device_add(const char *devname, int is_hotplug)
2555
{
2556
    const char *p;
2557
    USBDevice *dev = NULL;
2558

    
2559
    if (!usb_enabled)
2560
        return -1;
2561

    
2562
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2563
    dev = usbdevice_create(devname);
2564
    if (dev)
2565
        goto done;
2566

    
2567
    /* the other ones */
2568
    if (strstart(devname, "host:", &p)) {
2569
        dev = usb_host_device_open(p);
2570
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2571
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2572
                        bt_new_hci(qemu_find_bt_vlan(0)));
2573
    } else {
2574
        return -1;
2575
    }
2576
    if (!dev)
2577
        return -1;
2578

    
2579
done:
2580
    return 0;
2581
}
2582

    
2583
static int usb_device_del(const char *devname)
2584
{
2585
    int bus_num, addr;
2586
    const char *p;
2587

    
2588
    if (strstart(devname, "host:", &p))
2589
        return usb_host_device_close(p);
2590

    
2591
    if (!usb_enabled)
2592
        return -1;
2593

    
2594
    p = strchr(devname, '.');
2595
    if (!p)
2596
        return -1;
2597
    bus_num = strtoul(devname, NULL, 0);
2598
    addr = strtoul(p + 1, NULL, 0);
2599

    
2600
    return usb_device_delete_addr(bus_num, addr);
2601
}
2602

    
2603
static int usb_parse(const char *cmdline)
2604
{
2605
    int r;
2606
    r = usb_device_add(cmdline, 0);
2607
    if (r < 0) {
2608
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2609
    }
2610
    return r;
2611
}
2612

    
2613
void do_usb_add(Monitor *mon, const QDict *qdict)
2614
{
2615
    const char *devname = qdict_get_str(qdict, "devname");
2616
    if (usb_device_add(devname, 1) < 0) {
2617
        error_report("could not add USB device '%s'", devname);
2618
    }
2619
}
2620

    
2621
void do_usb_del(Monitor *mon, const QDict *qdict)
2622
{
2623
    const char *devname = qdict_get_str(qdict, "devname");
2624
    if (usb_device_del(devname) < 0) {
2625
        error_report("could not delete USB device '%s'", devname);
2626
    }
2627
}
2628

    
2629
/***********************************************************/
2630
/* PCMCIA/Cardbus */
2631

    
2632
static struct pcmcia_socket_entry_s {
2633
    PCMCIASocket *socket;
2634
    struct pcmcia_socket_entry_s *next;
2635
} *pcmcia_sockets = 0;
2636

    
2637
void pcmcia_socket_register(PCMCIASocket *socket)
2638
{
2639
    struct pcmcia_socket_entry_s *entry;
2640

    
2641
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2642
    entry->socket = socket;
2643
    entry->next = pcmcia_sockets;
2644
    pcmcia_sockets = entry;
2645
}
2646

    
2647
void pcmcia_socket_unregister(PCMCIASocket *socket)
2648
{
2649
    struct pcmcia_socket_entry_s *entry, **ptr;
2650

    
2651
    ptr = &pcmcia_sockets;
2652
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2653
        if (entry->socket == socket) {
2654
            *ptr = entry->next;
2655
            qemu_free(entry);
2656
        }
2657
}
2658

    
2659
void pcmcia_info(Monitor *mon)
2660
{
2661
    struct pcmcia_socket_entry_s *iter;
2662

    
2663
    if (!pcmcia_sockets)
2664
        monitor_printf(mon, "No PCMCIA sockets\n");
2665

    
2666
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2667
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2668
                       iter->socket->attached ? iter->socket->card_string :
2669
                       "Empty");
2670
}
2671

    
2672
/***********************************************************/
2673
/* I/O handling */
2674

    
2675
typedef struct IOHandlerRecord {
2676
    int fd;
2677
    IOCanRWHandler *fd_read_poll;
2678
    IOHandler *fd_read;
2679
    IOHandler *fd_write;
2680
    int deleted;
2681
    void *opaque;
2682
    /* temporary data */
2683
    struct pollfd *ufd;
2684
    struct IOHandlerRecord *next;
2685
} IOHandlerRecord;
2686

    
2687
static IOHandlerRecord *first_io_handler;
2688

    
2689
/* XXX: fd_read_poll should be suppressed, but an API change is
2690
   necessary in the character devices to suppress fd_can_read(). */
2691
int qemu_set_fd_handler2(int fd,
2692
                         IOCanRWHandler *fd_read_poll,
2693
                         IOHandler *fd_read,
2694
                         IOHandler *fd_write,
2695
                         void *opaque)
2696
{
2697
    IOHandlerRecord **pioh, *ioh;
2698

    
2699
    if (!fd_read && !fd_write) {
2700
        pioh = &first_io_handler;
2701
        for(;;) {
2702
            ioh = *pioh;
2703
            if (ioh == NULL)
2704
                break;
2705
            if (ioh->fd == fd) {
2706
                ioh->deleted = 1;
2707
                break;
2708
            }
2709
            pioh = &ioh->next;
2710
        }
2711
    } else {
2712
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2713
            if (ioh->fd == fd)
2714
                goto found;
2715
        }
2716
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2717
        ioh->next = first_io_handler;
2718
        first_io_handler = ioh;
2719
    found:
2720
        ioh->fd = fd;
2721
        ioh->fd_read_poll = fd_read_poll;
2722
        ioh->fd_read = fd_read;
2723
        ioh->fd_write = fd_write;
2724
        ioh->opaque = opaque;
2725
        ioh->deleted = 0;
2726
    }
2727
    return 0;
2728
}
2729

    
2730
int qemu_set_fd_handler(int fd,
2731
                        IOHandler *fd_read,
2732
                        IOHandler *fd_write,
2733
                        void *opaque)
2734
{
2735
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2736
}
2737

    
2738
#ifdef _WIN32
2739
/***********************************************************/
2740
/* Polling handling */
2741

    
2742
typedef struct PollingEntry {
2743
    PollingFunc *func;
2744
    void *opaque;
2745
    struct PollingEntry *next;
2746
} PollingEntry;
2747

    
2748
static PollingEntry *first_polling_entry;
2749

    
2750
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2751
{
2752
    PollingEntry **ppe, *pe;
2753
    pe = qemu_mallocz(sizeof(PollingEntry));
2754
    pe->func = func;
2755
    pe->opaque = opaque;
2756
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2757
    *ppe = pe;
2758
    return 0;
2759
}
2760

    
2761
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2762
{
2763
    PollingEntry **ppe, *pe;
2764
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2765
        pe = *ppe;
2766
        if (pe->func == func && pe->opaque == opaque) {
2767
            *ppe = pe->next;
2768
            qemu_free(pe);
2769
            break;
2770
        }
2771
    }
2772
}
2773

    
2774
/***********************************************************/
2775
/* Wait objects support */
2776
typedef struct WaitObjects {
2777
    int num;
2778
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2779
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2780
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2781
} WaitObjects;
2782

    
2783
static WaitObjects wait_objects = {0};
2784

    
2785
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2786
{
2787
    WaitObjects *w = &wait_objects;
2788

    
2789
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2790
        return -1;
2791
    w->events[w->num] = handle;
2792
    w->func[w->num] = func;
2793
    w->opaque[w->num] = opaque;
2794
    w->num++;
2795
    return 0;
2796
}
2797

    
2798
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2799
{
2800
    int i, found;
2801
    WaitObjects *w = &wait_objects;
2802

    
2803
    found = 0;
2804
    for (i = 0; i < w->num; i++) {
2805
        if (w->events[i] == handle)
2806
            found = 1;
2807
        if (found) {
2808
            w->events[i] = w->events[i + 1];
2809
            w->func[i] = w->func[i + 1];
2810
            w->opaque[i] = w->opaque[i + 1];
2811
        }
2812
    }
2813
    if (found)
2814
        w->num--;
2815
}
2816
#endif
2817

    
2818
/***********************************************************/
2819
/* ram save/restore */
2820

    
2821
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2822
#define RAM_SAVE_FLAG_COMPRESS        0x02
2823
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2824
#define RAM_SAVE_FLAG_PAGE        0x08
2825
#define RAM_SAVE_FLAG_EOS        0x10
2826

    
2827
static int is_dup_page(uint8_t *page, uint8_t ch)
2828
{
2829
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2830
    uint32_t *array = (uint32_t *)page;
2831
    int i;
2832

    
2833
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2834
        if (array[i] != val)
2835
            return 0;
2836
    }
2837

    
2838
    return 1;
2839
}
2840

    
2841
static int ram_save_block(QEMUFile *f)
2842
{
2843
    static ram_addr_t current_addr = 0;
2844
    ram_addr_t saved_addr = current_addr;
2845
    ram_addr_t addr = 0;
2846
    int found = 0;
2847

    
2848
    while (addr < last_ram_offset) {
2849
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2850
            uint8_t *p;
2851

    
2852
            cpu_physical_memory_reset_dirty(current_addr,
2853
                                            current_addr + TARGET_PAGE_SIZE,
2854
                                            MIGRATION_DIRTY_FLAG);
2855

    
2856
            p = qemu_get_ram_ptr(current_addr);
2857

    
2858
            if (is_dup_page(p, *p)) {
2859
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2860
                qemu_put_byte(f, *p);
2861
            } else {
2862
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2863
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2864
            }
2865

    
2866
            found = 1;
2867
            break;
2868
        }
2869
        addr += TARGET_PAGE_SIZE;
2870
        current_addr = (saved_addr + addr) % last_ram_offset;
2871
    }
2872

    
2873
    return found;
2874
}
2875

    
2876
static uint64_t bytes_transferred;
2877

    
2878
static ram_addr_t ram_save_remaining(void)
2879
{
2880
    ram_addr_t addr;
2881
    ram_addr_t count = 0;
2882

    
2883
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2884
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2885
            count++;
2886
    }
2887

    
2888
    return count;
2889
}
2890

    
2891
uint64_t ram_bytes_remaining(void)
2892
{
2893
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2894
}
2895

    
2896
uint64_t ram_bytes_transferred(void)
2897
{
2898
    return bytes_transferred;
2899
}
2900

    
2901
uint64_t ram_bytes_total(void)
2902
{
2903
    return last_ram_offset;
2904
}
2905

    
2906
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2907
{
2908
    ram_addr_t addr;
2909
    uint64_t bytes_transferred_last;
2910
    double bwidth = 0;
2911
    uint64_t expected_time = 0;
2912

    
2913
    if (stage < 0) {
2914
        cpu_physical_memory_set_dirty_tracking(0);
2915
        return 0;
2916
    }
2917

    
2918
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2919
        qemu_file_set_error(f);
2920
        return 0;
2921
    }
2922

    
2923
    if (stage == 1) {
2924
        bytes_transferred = 0;
2925

    
2926
        /* Make sure all dirty bits are set */
2927
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2928
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2929
                cpu_physical_memory_set_dirty(addr);
2930
        }
2931

    
2932
        /* Enable dirty memory tracking */
2933
        cpu_physical_memory_set_dirty_tracking(1);
2934

    
2935
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2936
    }
2937

    
2938
    bytes_transferred_last = bytes_transferred;
2939
    bwidth = qemu_get_clock_ns(rt_clock);
2940

    
2941
    while (!qemu_file_rate_limit(f)) {
2942
        int ret;
2943

    
2944
        ret = ram_save_block(f);
2945
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2946
        if (ret == 0) /* no more blocks */
2947
            break;
2948
    }
2949

    
2950
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2951
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2952

    
2953
    /* if we haven't transferred anything this round, force expected_time to a
2954
     * a very high value, but without crashing */
2955
    if (bwidth == 0)
2956
        bwidth = 0.000001;
2957

    
2958
    /* try transferring iterative blocks of memory */
2959
    if (stage == 3) {
2960
        /* flush all remaining blocks regardless of rate limiting */
2961
        while (ram_save_block(f) != 0) {
2962
            bytes_transferred += TARGET_PAGE_SIZE;
2963
        }
2964
        cpu_physical_memory_set_dirty_tracking(0);
2965
    }
2966

    
2967
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2968

    
2969
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2970

    
2971
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2972
}
2973

    
2974
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2975
{
2976
    ram_addr_t addr;
2977
    int flags;
2978

    
2979
    if (version_id != 3)
2980
        return -EINVAL;
2981

    
2982
    do {
2983
        addr = qemu_get_be64(f);
2984

    
2985
        flags = addr & ~TARGET_PAGE_MASK;
2986
        addr &= TARGET_PAGE_MASK;
2987

    
2988
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2989
            if (addr != last_ram_offset)
2990
                return -EINVAL;
2991
        }
2992

    
2993
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2994
            uint8_t ch = qemu_get_byte(f);
2995
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2996
#ifndef _WIN32
2997
            if (ch == 0 &&
2998
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2999
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3000
            }
3001
#endif
3002
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
3003
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3004
        }
3005
        if (qemu_file_has_error(f)) {
3006
            return -EIO;
3007
        }
3008
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3009

    
3010
    return 0;
3011
}
3012

    
3013
void qemu_service_io(void)
3014
{
3015
    qemu_notify_event();
3016
}
3017

    
3018
/***********************************************************/
3019
/* machine registration */
3020

    
3021
static QEMUMachine *first_machine = NULL;
3022
QEMUMachine *current_machine = NULL;
3023

    
3024
int qemu_register_machine(QEMUMachine *m)
3025
{
3026
    QEMUMachine **pm;
3027
    pm = &first_machine;
3028
    while (*pm != NULL)
3029
        pm = &(*pm)->next;
3030
    m->next = NULL;
3031
    *pm = m;
3032
    return 0;
3033
}
3034

    
3035
static QEMUMachine *find_machine(const char *name)
3036
{
3037
    QEMUMachine *m;
3038

    
3039
    for(m = first_machine; m != NULL; m = m->next) {
3040
        if (!strcmp(m->name, name))
3041
            return m;
3042
        if (m->alias && !strcmp(m->alias, name))
3043
            return m;
3044
    }
3045
    return NULL;
3046
}
3047

    
3048
static QEMUMachine *find_default_machine(void)
3049
{
3050
    QEMUMachine *m;
3051

    
3052
    for(m = first_machine; m != NULL; m = m->next) {
3053
        if (m->is_default) {
3054
            return m;
3055
        }
3056
    }
3057
    return NULL;
3058
}
3059

    
3060
/***********************************************************/
3061
/* main execution loop */
3062

    
3063
static void gui_update(void *opaque)
3064
{
3065
    uint64_t interval = GUI_REFRESH_INTERVAL;
3066
    DisplayState *ds = opaque;
3067
    DisplayChangeListener *dcl = ds->listeners;
3068

    
3069
    qemu_flush_coalesced_mmio_buffer();
3070
    dpy_refresh(ds);
3071

    
3072
    while (dcl != NULL) {
3073
        if (dcl->gui_timer_interval &&
3074
            dcl->gui_timer_interval < interval)
3075
            interval = dcl->gui_timer_interval;
3076
        dcl = dcl->next;
3077
    }
3078
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3079
}
3080

    
3081
static void nographic_update(void *opaque)
3082
{
3083
    uint64_t interval = GUI_REFRESH_INTERVAL;
3084

    
3085
    qemu_flush_coalesced_mmio_buffer();
3086
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3087
}
3088

    
3089
void cpu_synchronize_all_states(void)
3090
{
3091
    CPUState *cpu;
3092

    
3093
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3094
        cpu_synchronize_state(cpu);
3095
    }
3096
}
3097

    
3098
void cpu_synchronize_all_post_reset(void)
3099
{
3100
    CPUState *cpu;
3101

    
3102
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3103
        cpu_synchronize_post_reset(cpu);
3104
    }
3105
}
3106

    
3107
void cpu_synchronize_all_post_init(void)
3108
{
3109
    CPUState *cpu;
3110

    
3111
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3112
        cpu_synchronize_post_init(cpu);
3113
    }
3114
}
3115

    
3116
struct vm_change_state_entry {
3117
    VMChangeStateHandler *cb;
3118
    void *opaque;
3119
    QLIST_ENTRY (vm_change_state_entry) entries;
3120
};
3121

    
3122
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3123

    
3124
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3125
                                                     void *opaque)
3126
{
3127
    VMChangeStateEntry *e;
3128

    
3129
    e = qemu_mallocz(sizeof (*e));
3130

    
3131
    e->cb = cb;
3132
    e->opaque = opaque;
3133
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3134
    return e;
3135
}
3136

    
3137
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3138
{
3139
    QLIST_REMOVE (e, entries);
3140
    qemu_free (e);
3141
}
3142

    
3143
static void vm_state_notify(int running, int reason)
3144
{
3145
    VMChangeStateEntry *e;
3146

    
3147
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3148
        e->cb(e->opaque, running, reason);
3149
    }
3150
}
3151

    
3152
static void resume_all_vcpus(void);
3153
static void pause_all_vcpus(void);
3154

    
3155
void vm_start(void)
3156
{
3157
    if (!vm_running) {
3158
        cpu_enable_ticks();
3159
        vm_running = 1;
3160
        vm_state_notify(1, 0);
3161
        resume_all_vcpus();
3162
    }
3163
}
3164

    
3165
/* reset/shutdown handler */
3166

    
3167
typedef struct QEMUResetEntry {
3168
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3169
    QEMUResetHandler *func;
3170
    void *opaque;
3171
} QEMUResetEntry;
3172

    
3173
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3174
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3175
static int reset_requested;
3176
static int shutdown_requested;
3177
static int powerdown_requested;
3178
static int debug_requested;
3179
static int vmstop_requested;
3180

    
3181
int qemu_shutdown_requested(void)
3182
{
3183
    int r = shutdown_requested;
3184
    shutdown_requested = 0;
3185
    return r;
3186
}
3187

    
3188
int qemu_reset_requested(void)
3189
{
3190
    int r = reset_requested;
3191
    reset_requested = 0;
3192
    return r;
3193
}
3194

    
3195
int qemu_powerdown_requested(void)
3196
{
3197
    int r = powerdown_requested;
3198
    powerdown_requested = 0;
3199
    return r;
3200
}
3201

    
3202
static int qemu_debug_requested(void)
3203
{
3204
    int r = debug_requested;
3205
    debug_requested = 0;
3206
    return r;
3207
}
3208

    
3209
static int qemu_vmstop_requested(void)
3210
{
3211
    int r = vmstop_requested;
3212
    vmstop_requested = 0;
3213
    return r;
3214
}
3215

    
3216
static void do_vm_stop(int reason)
3217
{
3218
    if (vm_running) {
3219
        cpu_disable_ticks();
3220
        vm_running = 0;
3221
        pause_all_vcpus();
3222
        vm_state_notify(0, reason);
3223
        monitor_protocol_event(QEVENT_STOP, NULL);
3224
    }
3225
}
3226

    
3227
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3228
{
3229
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3230

    
3231
    re->func = func;
3232
    re->opaque = opaque;
3233
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3234
}
3235

    
3236
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3237
{
3238
    QEMUResetEntry *re;
3239

    
3240
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3241
        if (re->func == func && re->opaque == opaque) {
3242
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3243
            qemu_free(re);
3244
            return;
3245
        }
3246
    }
3247
}
3248

    
3249
void qemu_system_reset(void)
3250
{
3251
    QEMUResetEntry *re, *nre;
3252

    
3253
    /* reset all devices */
3254
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3255
        re->func(re->opaque);
3256
    }
3257
    monitor_protocol_event(QEVENT_RESET, NULL);
3258
    cpu_synchronize_all_post_reset();
3259
}
3260

    
3261
void qemu_system_reset_request(void)
3262
{
3263
    if (no_reboot) {
3264
        shutdown_requested = 1;
3265
    } else {
3266
        reset_requested = 1;
3267
    }
3268
    qemu_notify_event();
3269
}
3270

    
3271
void qemu_system_shutdown_request(void)
3272
{
3273
    shutdown_requested = 1;
3274
    qemu_notify_event();
3275
}
3276

    
3277
void qemu_system_powerdown_request(void)
3278
{
3279
    powerdown_requested = 1;
3280
    qemu_notify_event();
3281
}
3282

    
3283
#ifdef CONFIG_IOTHREAD
3284
static void qemu_system_vmstop_request(int reason)
3285
{
3286
    vmstop_requested = reason;
3287
    qemu_notify_event();
3288
}
3289
#endif
3290

    
3291
#ifndef _WIN32
3292
static int io_thread_fd = -1;
3293

    
3294
static void qemu_event_increment(void)
3295
{
3296
    /* Write 8 bytes to be compatible with eventfd.  */
3297
    static uint64_t val = 1;
3298
    ssize_t ret;
3299

    
3300
    if (io_thread_fd == -1)
3301
        return;
3302

    
3303
    do {
3304
        ret = write(io_thread_fd, &val, sizeof(val));
3305
    } while (ret < 0 && errno == EINTR);
3306

    
3307
    /* EAGAIN is fine, a read must be pending.  */
3308
    if (ret < 0 && errno != EAGAIN) {
3309
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3310
                strerror(errno));
3311
        exit (1);
3312
    }
3313
}
3314

    
3315
static void qemu_event_read(void *opaque)
3316
{
3317
    int fd = (unsigned long)opaque;
3318
    ssize_t len;
3319
    char buffer[512];
3320

    
3321
    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
3322
    do {
3323
        len = read(fd, buffer, sizeof(buffer));
3324
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3325
}
3326

    
3327
static int qemu_event_init(void)
3328
{
3329
    int err;
3330
    int fds[2];
3331

    
3332
    err = qemu_eventfd(fds);
3333
    if (err == -1)
3334
        return -errno;
3335

    
3336
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3337
    if (err < 0)
3338
        goto fail;
3339

    
3340
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3341
    if (err < 0)
3342
        goto fail;
3343

    
3344
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3345
                         (void *)(unsigned long)fds[0]);
3346

    
3347
    io_thread_fd = fds[1];
3348
    return 0;
3349

    
3350
fail:
3351
    close(fds[0]);
3352
    close(fds[1]);
3353
    return err;
3354
}
3355
#else
3356
HANDLE qemu_event_handle;
3357

    
3358
static void dummy_event_handler(void *opaque)
3359
{
3360
}
3361

    
3362
static int qemu_event_init(void)
3363
{
3364
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3365
    if (!qemu_event_handle) {
3366
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3367
        return -1;
3368
    }
3369
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3370
    return 0;
3371
}
3372

    
3373
static void qemu_event_increment(void)
3374
{
3375
    if (!SetEvent(qemu_event_handle)) {
3376
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3377
                GetLastError());
3378
        exit (1);
3379
    }
3380
}
3381
#endif
3382

    
3383
static int cpu_can_run(CPUState *env)
3384
{
3385
    if (env->stop)
3386
        return 0;
3387
    if (env->stopped)
3388
        return 0;
3389
    if (!vm_running)
3390
        return 0;
3391
    return 1;
3392
}
3393

    
3394
#ifndef CONFIG_IOTHREAD
3395
static int qemu_init_main_loop(void)
3396
{
3397
    return qemu_event_init();
3398
}
3399

    
3400
void qemu_init_vcpu(void *_env)
3401
{
3402
    CPUState *env = _env;
3403

    
3404
    env->nr_cores = smp_cores;
3405
    env->nr_threads = smp_threads;
3406
    if (kvm_enabled())
3407
        kvm_init_vcpu(env);
3408
    return;
3409
}
3410

    
3411
int qemu_cpu_self(void *env)
3412
{
3413
    return 1;
3414
}
3415

    
3416
static void resume_all_vcpus(void)
3417
{
3418
}
3419

    
3420
static void pause_all_vcpus(void)
3421
{
3422
}
3423

    
3424
void qemu_cpu_kick(void *env)
3425
{
3426
    return;
3427
}
3428

    
3429
void qemu_notify_event(void)
3430
{
3431
    CPUState *env = cpu_single_env;
3432

    
3433
    qemu_event_increment ();
3434
    if (env) {
3435
        cpu_exit(env);
3436
    }
3437
    if (next_cpu && env != next_cpu) {
3438
        cpu_exit(next_cpu);
3439
    }
3440
}
3441

    
3442
void qemu_mutex_lock_iothread(void) {}
3443
void qemu_mutex_unlock_iothread(void) {}
3444

    
3445
void vm_stop(int reason)
3446
{
3447
    do_vm_stop(reason);
3448
}
3449

    
3450
#else /* CONFIG_IOTHREAD */
3451

    
3452
#include "qemu-thread.h"
3453

    
3454
QemuMutex qemu_global_mutex;
3455
static QemuMutex qemu_fair_mutex;
3456

    
3457
static QemuThread io_thread;
3458

    
3459
static QemuThread *tcg_cpu_thread;
3460
static QemuCond *tcg_halt_cond;
3461

    
3462
static int qemu_system_ready;
3463
/* cpu creation */
3464
static QemuCond qemu_cpu_cond;
3465
/* system init */
3466
static QemuCond qemu_system_cond;
3467
static QemuCond qemu_pause_cond;
3468

    
3469
static void tcg_block_io_signals(void);
3470
static void kvm_block_io_signals(CPUState *env);
3471
static void unblock_io_signals(void);
3472
static int tcg_has_work(void);
3473
static int cpu_has_work(CPUState *env);
3474

    
3475
static int qemu_init_main_loop(void)
3476
{
3477
    int ret;
3478

    
3479
    ret = qemu_event_init();
3480
    if (ret)
3481
        return ret;
3482

    
3483
    qemu_cond_init(&qemu_pause_cond);
3484
    qemu_mutex_init(&qemu_fair_mutex);
3485
    qemu_mutex_init(&qemu_global_mutex);
3486
    qemu_mutex_lock(&qemu_global_mutex);
3487

    
3488
    unblock_io_signals();
3489
    qemu_thread_self(&io_thread);
3490

    
3491
    return 0;
3492
}
3493

    
3494
static void qemu_wait_io_event_common(CPUState *env)
3495
{
3496
    if (env->stop) {
3497
        env->stop = 0;
3498
        env->stopped = 1;
3499
        qemu_cond_signal(&qemu_pause_cond);
3500
    }
3501
}
3502

    
3503
static void qemu_wait_io_event(CPUState *env)
3504
{
3505
    while (!tcg_has_work())
3506
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3507

    
3508
    qemu_mutex_unlock(&qemu_global_mutex);
3509

    
3510
    /*
3511
     * Users of qemu_global_mutex can be starved, having no chance
3512
     * to acquire it since this path will get to it first.
3513
     * So use another lock to provide fairness.
3514
     */
3515
    qemu_mutex_lock(&qemu_fair_mutex);
3516
    qemu_mutex_unlock(&qemu_fair_mutex);
3517

    
3518
    qemu_mutex_lock(&qemu_global_mutex);
3519
    qemu_wait_io_event_common(env);
3520
}
3521

    
3522
static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3523
{
3524
    struct timespec ts;
3525
    int r, e;
3526
    siginfo_t siginfo;
3527
    sigset_t waitset;
3528

    
3529
    ts.tv_sec = timeout / 1000;
3530
    ts.tv_nsec = (timeout % 1000) * 1000000;
3531

    
3532
    sigemptyset(&waitset);
3533
    sigaddset(&waitset, SIG_IPI);
3534

    
3535
    qemu_mutex_unlock(&qemu_global_mutex);
3536
    r = sigtimedwait(&waitset, &siginfo, &ts);
3537
    e = errno;
3538
    qemu_mutex_lock(&qemu_global_mutex);
3539

    
3540
    if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3541
        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3542
        exit(1);
3543
    }
3544
}
3545

    
3546
static void qemu_kvm_wait_io_event(CPUState *env)
3547
{
3548
    while (!cpu_has_work(env))
3549
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3550

    
3551
    qemu_kvm_eat_signal(env, 0);
3552
    qemu_wait_io_event_common(env);
3553
}
3554

    
3555
static int qemu_cpu_exec(CPUState *env);
3556

    
3557
static void *kvm_cpu_thread_fn(void *arg)
3558
{
3559
    CPUState *env = arg;
3560

    
3561
    qemu_thread_self(env->thread);
3562
    if (kvm_enabled())
3563
        kvm_init_vcpu(env);
3564

    
3565
    kvm_block_io_signals(env);
3566

    
3567
    /* signal CPU creation */
3568
    qemu_mutex_lock(&qemu_global_mutex);
3569
    env->created = 1;
3570
    qemu_cond_signal(&qemu_cpu_cond);
3571

    
3572
    /* and wait for machine initialization */
3573
    while (!qemu_system_ready)
3574
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3575

    
3576
    while (1) {
3577
        if (cpu_can_run(env))
3578
            qemu_cpu_exec(env);
3579
        qemu_kvm_wait_io_event(env);
3580
    }
3581

    
3582
    return NULL;
3583
}
3584

    
3585
static void tcg_cpu_exec(void);
3586

    
3587
static void *tcg_cpu_thread_fn(void *arg)
3588
{
3589
    CPUState *env = arg;
3590

    
3591
    tcg_block_io_signals();
3592
    qemu_thread_self(env->thread);
3593

    
3594
    /* signal CPU creation */
3595
    qemu_mutex_lock(&qemu_global_mutex);
3596
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3597
        env->created = 1;
3598
    qemu_cond_signal(&qemu_cpu_cond);
3599

    
3600
    /* and wait for machine initialization */
3601
    while (!qemu_system_ready)
3602
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3603

    
3604
    while (1) {
3605
        tcg_cpu_exec();
3606
        qemu_wait_io_event(cur_cpu);
3607
    }
3608

    
3609
    return NULL;
3610
}
3611

    
3612
void qemu_cpu_kick(void *_env)
3613
{
3614
    CPUState *env = _env;
3615
    qemu_cond_broadcast(env->halt_cond);
3616
    if (kvm_enabled())
3617
        qemu_thread_signal(env->thread, SIG_IPI);
3618
}
3619

    
3620
int qemu_cpu_self(void *_env)
3621
{
3622
    CPUState *env = _env;
3623
    QemuThread this;
3624
 
3625
    qemu_thread_self(&this);
3626
 
3627
    return qemu_thread_equal(&this, env->thread);
3628
}
3629

    
3630
static void cpu_signal(int sig)
3631
{
3632
    if (cpu_single_env)
3633
        cpu_exit(cpu_single_env);
3634
}
3635

    
3636
static void tcg_block_io_signals(void)
3637
{
3638
    sigset_t set;
3639
    struct sigaction sigact;
3640

    
3641
    sigemptyset(&set);
3642
    sigaddset(&set, SIGUSR2);
3643
    sigaddset(&set, SIGIO);
3644
    sigaddset(&set, SIGALRM);
3645
    sigaddset(&set, SIGCHLD);
3646
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3647

    
3648
    sigemptyset(&set);
3649
    sigaddset(&set, SIG_IPI);
3650
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3651

    
3652
    memset(&sigact, 0, sizeof(sigact));
3653
    sigact.sa_handler = cpu_signal;
3654
    sigaction(SIG_IPI, &sigact, NULL);
3655
}
3656

    
3657
static void dummy_signal(int sig)
3658
{
3659
}
3660

    
3661
static void kvm_block_io_signals(CPUState *env)
3662
{
3663
    int r;
3664
    sigset_t set;
3665
    struct sigaction sigact;
3666

    
3667
    sigemptyset(&set);
3668
    sigaddset(&set, SIGUSR2);
3669
    sigaddset(&set, SIGIO);
3670
    sigaddset(&set, SIGALRM);
3671
    sigaddset(&set, SIGCHLD);
3672
    sigaddset(&set, SIG_IPI);
3673
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3674

    
3675
    pthread_sigmask(SIG_BLOCK, NULL, &set);
3676
    sigdelset(&set, SIG_IPI);
3677

    
3678
    memset(&sigact, 0, sizeof(sigact));
3679
    sigact.sa_handler = dummy_signal;
3680
    sigaction(SIG_IPI, &sigact, NULL);
3681

    
3682
    r = kvm_set_signal_mask(env, &set);
3683
    if (r) {
3684
        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3685
        exit(1);
3686
    }
3687
}
3688

    
3689
static void unblock_io_signals(void)
3690
{
3691
    sigset_t set;
3692

    
3693
    sigemptyset(&set);
3694
    sigaddset(&set, SIGUSR2);
3695
    sigaddset(&set, SIGIO);
3696
    sigaddset(&set, SIGALRM);
3697
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3698

    
3699
    sigemptyset(&set);
3700
    sigaddset(&set, SIG_IPI);
3701
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3702
}
3703

    
3704
static void qemu_signal_lock(unsigned int msecs)
3705
{
3706
    qemu_mutex_lock(&qemu_fair_mutex);
3707

    
3708
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3709
        qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3710
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3711
            break;
3712
    }
3713
    qemu_mutex_unlock(&qemu_fair_mutex);
3714
}
3715

    
3716
void qemu_mutex_lock_iothread(void)
3717
{
3718
    if (kvm_enabled()) {
3719
        qemu_mutex_lock(&qemu_fair_mutex);
3720
        qemu_mutex_lock(&qemu_global_mutex);
3721
        qemu_mutex_unlock(&qemu_fair_mutex);
3722
    } else
3723
        qemu_signal_lock(100);
3724
}
3725

    
3726
void qemu_mutex_unlock_iothread(void)
3727
{
3728
    qemu_mutex_unlock(&qemu_global_mutex);
3729
}
3730

    
3731
static int all_vcpus_paused(void)
3732
{
3733
    CPUState *penv = first_cpu;
3734

    
3735
    while (penv) {
3736
        if (!penv->stopped)
3737
            return 0;
3738
        penv = (CPUState *)penv->next_cpu;
3739
    }
3740

    
3741
    return 1;
3742
}
3743

    
3744
static void pause_all_vcpus(void)
3745
{
3746
    CPUState *penv = first_cpu;
3747

    
3748
    while (penv) {
3749
        penv->stop = 1;
3750
        qemu_thread_signal(penv->thread, SIG_IPI);
3751
        qemu_cpu_kick(penv);
3752
        penv = (CPUState *)penv->next_cpu;
3753
    }
3754

    
3755
    while (!all_vcpus_paused()) {
3756
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3757
        penv = first_cpu;
3758
        while (penv) {
3759
            qemu_thread_signal(penv->thread, SIG_IPI);
3760
            penv = (CPUState *)penv->next_cpu;
3761
        }
3762
    }
3763
}
3764

    
3765
static void resume_all_vcpus(void)
3766
{
3767
    CPUState *penv = first_cpu;
3768

    
3769
    while (penv) {
3770
        penv->stop = 0;
3771
        penv->stopped = 0;
3772
        qemu_thread_signal(penv->thread, SIG_IPI);
3773
        qemu_cpu_kick(penv);
3774
        penv = (CPUState *)penv->next_cpu;
3775
    }
3776
}
3777

    
3778
static void tcg_init_vcpu(void *_env)
3779
{
3780
    CPUState *env = _env;
3781
    /* share a single thread for all cpus with TCG */
3782
    if (!tcg_cpu_thread) {
3783
        env->thread = qemu_mallocz(sizeof(QemuThread));
3784
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3785
        qemu_cond_init(env->halt_cond);
3786
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3787
        while (env->created == 0)
3788
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3789
        tcg_cpu_thread = env->thread;
3790
        tcg_halt_cond = env->halt_cond;
3791
    } else {
3792
        env->thread = tcg_cpu_thread;
3793
        env->halt_cond = tcg_halt_cond;
3794
    }
3795
}
3796

    
3797
static void kvm_start_vcpu(CPUState *env)
3798
{
3799
    env->thread = qemu_mallocz(sizeof(QemuThread));
3800
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3801
    qemu_cond_init(env->halt_cond);
3802
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3803
    while (env->created == 0)
3804
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3805
}
3806

    
3807
void qemu_init_vcpu(void *_env)
3808
{
3809
    CPUState *env = _env;
3810

    
3811
    env->nr_cores = smp_cores;
3812
    env->nr_threads = smp_threads;
3813
    if (kvm_enabled())
3814
        kvm_start_vcpu(env);
3815
    else
3816
        tcg_init_vcpu(env);
3817
}
3818

    
3819
void qemu_notify_event(void)
3820
{
3821
    qemu_event_increment();
3822
}
3823

    
3824
void vm_stop(int reason)
3825
{
3826
    QemuThread me;
3827
    qemu_thread_self(&me);
3828

    
3829
    if (!qemu_thread_equal(&me, &io_thread)) {
3830
        qemu_system_vmstop_request(reason);
3831
        /*
3832
         * FIXME: should not return to device code in case
3833
         * vm_stop() has been requested.
3834
         */
3835
        if (cpu_single_env) {
3836
            cpu_exit(cpu_single_env);
3837
            cpu_single_env->stop = 1;
3838
        }
3839
        return;
3840
    }
3841
    do_vm_stop(reason);
3842
}
3843

    
3844
#endif
3845

    
3846

    
3847
#ifdef _WIN32
3848
static void host_main_loop_wait(int *timeout)
3849
{
3850
    int ret, ret2, i;
3851
    PollingEntry *pe;
3852

    
3853

    
3854
    /* XXX: need to suppress polling by better using win32 events */
3855
    ret = 0;
3856
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3857
        ret |= pe->func(pe->opaque);
3858
    }
3859
    if (ret == 0) {
3860
        int err;
3861
        WaitObjects *w = &wait_objects;
3862

    
3863
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3864
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3865
            if (w->func[ret - WAIT_OBJECT_0])
3866
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3867

    
3868
            /* Check for additional signaled events */
3869
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3870

    
3871
                /* Check if event is signaled */
3872
                ret2 = WaitForSingleObject(w->events[i], 0);
3873
                if(ret2 == WAIT_OBJECT_0) {
3874
                    if (w->func[i])
3875
                        w->func[i](w->opaque[i]);
3876
                } else if (ret2 == WAIT_TIMEOUT) {
3877
                } else {
3878
                    err = GetLastError();
3879
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3880
                }
3881
            }
3882
        } else if (ret == WAIT_TIMEOUT) {
3883
        } else {
3884
            err = GetLastError();
3885
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3886
        }
3887
    }
3888

    
3889
    *timeout = 0;
3890
}
3891
#else
3892
static void host_main_loop_wait(int *timeout)
3893
{
3894
}
3895
#endif
3896

    
3897
void main_loop_wait(int timeout)
3898
{
3899
    IOHandlerRecord *ioh;
3900
    fd_set rfds, wfds, xfds;
3901
    int ret, nfds;
3902
    struct timeval tv;
3903

    
3904
    qemu_bh_update_timeout(&timeout);
3905

    
3906
    host_main_loop_wait(&timeout);
3907

    
3908
    /* poll any events */
3909
    /* XXX: separate device handlers from system ones */
3910
    nfds = -1;
3911
    FD_ZERO(&rfds);
3912
    FD_ZERO(&wfds);
3913
    FD_ZERO(&xfds);
3914
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3915
        if (ioh->deleted)
3916
            continue;
3917
        if (ioh->fd_read &&
3918
            (!ioh->fd_read_poll ||
3919
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3920
            FD_SET(ioh->fd, &rfds);
3921
            if (ioh->fd > nfds)
3922
                nfds = ioh->fd;
3923
        }
3924
        if (ioh->fd_write) {
3925
            FD_SET(ioh->fd, &wfds);
3926
            if (ioh->fd > nfds)
3927
                nfds = ioh->fd;
3928
        }
3929
    }
3930

    
3931
    tv.tv_sec = timeout / 1000;
3932
    tv.tv_usec = (timeout % 1000) * 1000;
3933

    
3934
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3935

    
3936
    qemu_mutex_unlock_iothread();
3937
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3938
    qemu_mutex_lock_iothread();
3939
    if (ret > 0) {
3940
        IOHandlerRecord **pioh;
3941

    
3942
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3943
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3944
                ioh->fd_read(ioh->opaque);
3945
            }
3946
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3947
                ioh->fd_write(ioh->opaque);
3948
            }
3949
        }
3950

    
3951
        /* remove deleted IO handlers */
3952
        pioh = &first_io_handler;
3953
        while (*pioh) {
3954
            ioh = *pioh;
3955
            if (ioh->deleted) {
3956
                *pioh = ioh->next;
3957
                qemu_free(ioh);
3958
            } else
3959
                pioh = &ioh->next;
3960
        }
3961
    }
3962

    
3963
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3964

    
3965
    qemu_run_all_timers();
3966

    
3967
    /* Check bottom-halves last in case any of the earlier events triggered
3968
       them.  */
3969
    qemu_bh_poll();
3970

    
3971
}
3972

    
3973
static int qemu_cpu_exec(CPUState *env)
3974
{
3975
    int ret;
3976
#ifdef CONFIG_PROFILER
3977
    int64_t ti;
3978
#endif
3979

    
3980
#ifdef CONFIG_PROFILER
3981
    ti = profile_getclock();
3982
#endif
3983
    if (use_icount) {
3984
        int64_t count;
3985
        int decr;
3986
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3987
        env->icount_decr.u16.low = 0;
3988
        env->icount_extra = 0;
3989
        count = qemu_icount_round (qemu_next_deadline());
3990
        qemu_icount += count;
3991
        decr = (count > 0xffff) ? 0xffff : count;
3992
        count -= decr;
3993
        env->icount_decr.u16.low = decr;
3994
        env->icount_extra = count;
3995
    }
3996
    ret = cpu_exec(env);
3997
#ifdef CONFIG_PROFILER
3998
    qemu_time += profile_getclock() - ti;
3999
#endif
4000
    if (use_icount) {
4001
        /* Fold pending instructions back into the
4002
           instruction counter, and clear the interrupt flag.  */
4003
        qemu_icount -= (env->icount_decr.u16.low
4004
                        + env->icount_extra);
4005
        env->icount_decr.u32 = 0;
4006
        env->icount_extra = 0;
4007
    }
4008
    return ret;
4009
}
4010

    
4011
static void tcg_cpu_exec(void)
4012
{
4013
    int ret = 0;
4014

    
4015
    if (next_cpu == NULL)
4016
        next_cpu = first_cpu;
4017
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4018
        CPUState *env = cur_cpu = next_cpu;
4019

    
4020
        qemu_clock_enable(vm_clock,
4021
                          (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
4022

    
4023
        if (qemu_alarm_pending())
4024
            break;
4025
        if (cpu_can_run(env))
4026
            ret = qemu_cpu_exec(env);
4027
        else if (env->stop)
4028
            break;
4029

    
4030
        if (ret == EXCP_DEBUG) {
4031
            gdb_set_stop_cpu(env);
4032
            debug_requested = 1;
4033
            break;
4034
        }
4035
    }
4036
}
4037

    
4038
static int cpu_has_work(CPUState *env)
4039
{
4040
    if (env->stop)
4041
        return 1;
4042
    if (env->stopped)
4043
        return 0;
4044
    if (!env->halted)
4045
        return 1;
4046
    if (qemu_cpu_has_work(env))
4047
        return 1;
4048
    return 0;
4049
}
4050

    
4051
static int tcg_has_work(void)
4052
{
4053
    CPUState *env;
4054

    
4055
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4056
        if (cpu_has_work(env))
4057
            return 1;
4058
    return 0;
4059
}
4060

    
4061
static int qemu_calculate_timeout(void)
4062
{
4063
#ifndef CONFIG_IOTHREAD
4064
    int timeout;
4065

    
4066
    if (!vm_running)
4067
        timeout = 5000;
4068
    else if (tcg_has_work())
4069
        timeout = 0;
4070
    else {
4071
     /* XXX: use timeout computed from timers */
4072
        int64_t add;
4073
        int64_t delta;
4074
        /* Advance virtual time to the next event.  */
4075
        delta = qemu_icount_delta();
4076
        if (delta > 0) {
4077
            /* If virtual time is ahead of real time then just
4078
               wait for IO.  */
4079
            timeout = (delta + 999999) / 1000000;
4080
        } else {
4081
            /* Wait for either IO to occur or the next
4082
               timer event.  */
4083
            add = qemu_next_deadline();
4084
            /* We advance the timer before checking for IO.
4085
               Limit the amount we advance so that early IO
4086
               activity won't get the guest too far ahead.  */
4087
            if (add > 10000000)
4088
                add = 10000000;
4089
            delta += add;
4090
            qemu_icount += qemu_icount_round (add);
4091
            timeout = delta / 1000000;
4092
            if (timeout < 0)
4093
                timeout = 0;
4094
        }
4095
    }
4096

    
4097
    return timeout;
4098
#else /* CONFIG_IOTHREAD */
4099
    return 1000;
4100
#endif
4101
}
4102

    
4103
static int vm_can_run(void)
4104
{
4105
    if (powerdown_requested)
4106
        return 0;
4107
    if (reset_requested)
4108
        return 0;
4109
    if (shutdown_requested)
4110
        return 0;
4111
    if (debug_requested)
4112
        return 0;
4113
    return 1;
4114
}
4115

    
4116
qemu_irq qemu_system_powerdown;
4117

    
4118
static void main_loop(void)
4119
{
4120
    int r;
4121

    
4122
#ifdef CONFIG_IOTHREAD
4123
    qemu_system_ready = 1;
4124
    qemu_cond_broadcast(&qemu_system_cond);
4125
#endif
4126

    
4127
    for (;;) {
4128
        do {
4129
#ifdef CONFIG_PROFILER
4130
            int64_t ti;
4131
#endif
4132
#ifndef CONFIG_IOTHREAD
4133
            tcg_cpu_exec();
4134
#endif
4135
#ifdef CONFIG_PROFILER
4136
            ti = profile_getclock();
4137
#endif
4138
            main_loop_wait(qemu_calculate_timeout());
4139
#ifdef CONFIG_PROFILER
4140
            dev_time += profile_getclock() - ti;
4141
#endif
4142
        } while (vm_can_run());
4143

    
4144
        if (qemu_debug_requested()) {
4145
            vm_stop(EXCP_DEBUG);
4146
        }
4147
        if (qemu_shutdown_requested()) {
4148
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4149
            if (no_shutdown) {
4150
                vm_stop(0);
4151
                no_shutdown = 0;
4152
            } else
4153
                break;
4154
        }
4155
        if (qemu_reset_requested()) {
4156
            pause_all_vcpus();
4157
            qemu_system_reset();
4158
            resume_all_vcpus();
4159
        }
4160
        if (qemu_powerdown_requested()) {
4161
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4162
            qemu_irq_raise(qemu_system_powerdown);
4163
        }
4164
        if ((r = qemu_vmstop_requested())) {
4165
            vm_stop(r);
4166
        }
4167
    }
4168
    pause_all_vcpus();
4169
}
4170

    
4171
static void version(void)
4172
{
4173
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4174
}
4175

    
4176
static void help(int exitcode)
4177
{
4178
    const char *options_help =
4179
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4180
           opt_help
4181
#define DEFHEADING(text) stringify(text) "\n"
4182
#include "qemu-options.h"
4183
#undef DEF
4184
#undef DEFHEADING
4185
#undef GEN_DOCS
4186
        ;
4187
    version();
4188
    printf("usage: %s [options] [disk_image]\n"
4189
           "\n"
4190
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4191
           "\n"
4192
           "%s\n"
4193
           "During emulation, the following keys are useful:\n"
4194
           "ctrl-alt-f      toggle full screen\n"
4195
           "ctrl-alt-n      switch to virtual console 'n'\n"
4196
           "ctrl-alt        toggle mouse and keyboard grab\n"
4197
           "\n"
4198
           "When using -nographic, press 'ctrl-a h' to get some help.\n",
4199
           "qemu",
4200
           options_help);
4201
    exit(exitcode);
4202
}
4203

    
4204
#define HAS_ARG 0x0001
4205

    
4206
enum {
4207
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4208
    opt_enum,
4209
#define DEFHEADING(text)
4210
#include "qemu-options.h"
4211
#undef DEF
4212
#undef DEFHEADING
4213
#undef GEN_DOCS
4214
};
4215

    
4216
typedef struct QEMUOption {
4217
    const char *name;
4218
    int flags;
4219
    int index;
4220
} QEMUOption;
4221

    
4222
static const QEMUOption qemu_options[] = {
4223
    { "h", 0, QEMU_OPTION_h },
4224
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4225
    { option, opt_arg, opt_enum },
4226
#define DEFHEADING(text)
4227
#include "qemu-options.h"
4228
#undef DEF
4229
#undef DEFHEADING
4230
#undef GEN_DOCS
4231
    { NULL },
4232
};
4233

    
4234
#ifdef HAS_AUDIO
4235
struct soundhw soundhw[] = {
4236
#ifdef HAS_AUDIO_CHOICE
4237
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4238
    {
4239
        "pcspk",
4240
        "PC speaker",
4241
        0,
4242
        1,
4243
        { .init_isa = pcspk_audio_init }
4244
    },
4245
#endif
4246

    
4247
#ifdef CONFIG_SB16
4248
    {
4249
        "sb16",
4250
        "Creative Sound Blaster 16",
4251
        0,
4252
        1,
4253
        { .init_isa = SB16_init }
4254
    },
4255
#endif
4256

    
4257
#ifdef CONFIG_CS4231A
4258
    {
4259
        "cs4231a",
4260
        "CS4231A",
4261
        0,
4262
        1,
4263
        { .init_isa = cs4231a_init }
4264
    },
4265
#endif
4266

    
4267
#ifdef CONFIG_ADLIB
4268
    {
4269
        "adlib",
4270
#ifdef HAS_YMF262
4271
        "Yamaha YMF262 (OPL3)",
4272
#else
4273
        "Yamaha YM3812 (OPL2)",
4274
#endif
4275
        0,
4276
        1,
4277
        { .init_isa = Adlib_init }
4278
    },
4279
#endif
4280

    
4281
#ifdef CONFIG_GUS
4282
    {
4283
        "gus",
4284
        "Gravis Ultrasound GF1",
4285
        0,
4286
        1,
4287
        { .init_isa = GUS_init }
4288
    },
4289
#endif
4290

    
4291
#ifdef CONFIG_AC97
4292
    {
4293
        "ac97",
4294
        "Intel 82801AA AC97 Audio",
4295
        0,
4296
        0,
4297
        { .init_pci = ac97_init }
4298
    },
4299
#endif
4300

    
4301
#ifdef CONFIG_ES1370
4302
    {
4303
        "es1370",
4304
        "ENSONIQ AudioPCI ES1370",
4305
        0,
4306
        0,
4307
        { .init_pci = es1370_init }
4308
    },
4309
#endif
4310

    
4311
#endif /* HAS_AUDIO_CHOICE */
4312

    
4313
    { NULL, NULL, 0, 0, { NULL } }
4314
};
4315

    
4316
static void select_soundhw (const char *optarg)
4317
{
4318
    struct soundhw *c;
4319

    
4320
    if (*optarg == '?') {
4321
    show_valid_cards:
4322

    
4323
        printf ("Valid sound card names (comma separated):\n");
4324
        for (c = soundhw; c->name; ++c) {
4325
            printf ("%-11s %s\n", c->name, c->descr);
4326
        }
4327
        printf ("\n-soundhw all will enable all of the above\n");
4328
        exit (*optarg != '?');
4329
    }
4330
    else {
4331
        size_t l;
4332
        const char *p;
4333
        char *e;
4334
        int bad_card = 0;
4335

    
4336
        if (!strcmp (optarg, "all")) {
4337
            for (c = soundhw; c->name; ++c) {
4338
                c->enabled = 1;
4339
            }
4340
            return;
4341
        }
4342

    
4343
        p = optarg;
4344
        while (*p) {
4345
            e = strchr (p, ',');
4346
            l = !e ? strlen (p) : (size_t) (e - p);
4347

    
4348
            for (c = soundhw; c->name; ++c) {
4349
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4350
                    c->enabled = 1;
4351
                    break;
4352
                }
4353
            }
4354

    
4355
            if (!c->name) {
4356
                if (l > 80) {
4357
                    fprintf (stderr,
4358
                             "Unknown sound card name (too big to show)\n");
4359
                }
4360
                else {
4361
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4362
                             (int) l, p);
4363
                }
4364
                bad_card = 1;
4365
            }
4366
            p += l + (e != NULL);
4367
        }
4368

    
4369
        if (bad_card)
4370
            goto show_valid_cards;
4371
    }
4372
}
4373
#endif
4374

    
4375
static void select_vgahw (const char *p)
4376
{
4377
    const char *opts;
4378

    
4379
    default_vga = 0;
4380
    vga_interface_type = VGA_NONE;
4381
    if (strstart(p, "std", &opts)) {
4382
        vga_interface_type = VGA_STD;
4383
    } else if (strstart(p, "cirrus", &opts)) {
4384
        vga_interface_type = VGA_CIRRUS;
4385
    } else if (strstart(p, "vmware", &opts)) {
4386
        vga_interface_type = VGA_VMWARE;
4387
    } else if (strstart(p, "xenfb", &opts)) {
4388
        vga_interface_type = VGA_XENFB;
4389
    } else if (!strstart(p, "none", &opts)) {
4390
    invalid_vga:
4391
        fprintf(stderr, "Unknown vga type: %s\n", p);
4392
        exit(1);
4393
    }
4394
    while (*opts) {
4395
        const char *nextopt;
4396

    
4397
        if (strstart(opts, ",retrace=", &nextopt)) {
4398
            opts = nextopt;
4399
            if (strstart(opts, "dumb", &nextopt))
4400
                vga_retrace_method = VGA_RETRACE_DUMB;
4401
            else if (strstart(opts, "precise", &nextopt))
4402
                vga_retrace_method = VGA_RETRACE_PRECISE;
4403
            else goto invalid_vga;
4404
        } else goto invalid_vga;
4405
        opts = nextopt;
4406
    }
4407
}
4408

    
4409
#ifdef TARGET_I386
4410
static int balloon_parse(const char *arg)
4411
{
4412
    QemuOpts *opts;
4413

    
4414
    if (strcmp(arg, "none") == 0) {
4415
        return 0;
4416
    }
4417

    
4418
    if (!strncmp(arg, "virtio", 6)) {
4419
        if (arg[6] == ',') {
4420
            /* have params -> parse them */
4421
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
4422
            if (!opts)
4423
                return  -1;
4424
        } else {
4425
            /* create empty opts */
4426
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4427
        }
4428
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4429
        return 0;
4430
    }
4431

    
4432
    return -1;
4433
}
4434
#endif
4435

    
4436
#ifdef _WIN32
4437
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4438
{
4439
    exit(STATUS_CONTROL_C_EXIT);
4440
    return TRUE;
4441
}
4442
#endif
4443

    
4444
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4445
{
4446
    int ret;
4447

    
4448
    if(strlen(str) != 36)
4449
        return -1;
4450

    
4451
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4452
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4453
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4454

    
4455
    if(ret != 16)
4456
        return -1;
4457

    
4458
#ifdef TARGET_I386
4459
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4460
#endif
4461

    
4462
    return 0;
4463
}
4464

    
4465
#ifndef _WIN32
4466

    
4467
static void termsig_handler(int signal)
4468
{
4469
    qemu_system_shutdown_request();
4470
}
4471

    
4472
static void sigchld_handler(int signal)
4473
{
4474
    waitpid(-1, NULL, WNOHANG);
4475
}
4476

    
4477
static void sighandler_setup(void)
4478
{
4479
    struct sigaction act;
4480

    
4481
    memset(&act, 0, sizeof(act));
4482
    act.sa_handler = termsig_handler;
4483
    sigaction(SIGINT,  &act, NULL);
4484
    sigaction(SIGHUP,  &act, NULL);
4485
    sigaction(SIGTERM, &act, NULL);
4486

    
4487
    act.sa_handler = sigchld_handler;
4488
    act.sa_flags = SA_NOCLDSTOP;
4489
    sigaction(SIGCHLD, &act, NULL);
4490
}
4491

    
4492
#endif
4493

    
4494
#ifdef _WIN32
4495
/* Look for support files in the same directory as the executable.  */
4496
static char *find_datadir(const char *argv0)
4497
{
4498
    char *p;
4499
    char buf[MAX_PATH];
4500
    DWORD len;
4501

    
4502
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4503
    if (len == 0) {
4504
        return NULL;
4505
    }
4506

    
4507
    buf[len] = 0;
4508
    p = buf + len - 1;
4509
    while (p != buf && *p != '\\')
4510
        p--;
4511
    *p = 0;
4512
    if (access(buf, R_OK) == 0) {
4513
        return qemu_strdup(buf);
4514
    }
4515
    return NULL;
4516
}
4517
#else /* !_WIN32 */
4518

    
4519
/* Find a likely location for support files using the location of the binary.
4520
   For installed binaries this will be "$bindir/../share/qemu".  When
4521
   running from the build tree this will be "$bindir/../pc-bios".  */
4522
#define SHARE_SUFFIX "/share/qemu"
4523
#define BUILD_SUFFIX "/pc-bios"
4524
static char *find_datadir(const char *argv0)
4525
{
4526
    char *dir;
4527
    char *p = NULL;
4528
    char *res;
4529
    char buf[PATH_MAX];
4530
    size_t max_len;
4531

    
4532
#if defined(__linux__)
4533
    {
4534
        int len;
4535
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4536
        if (len > 0) {
4537
            buf[len] = 0;
4538
            p = buf;
4539
        }
4540
    }
4541
#elif defined(__FreeBSD__)
4542
    {
4543
        int len;
4544
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4545
        if (len > 0) {
4546
            buf[len] = 0;
4547
            p = buf;
4548
        }
4549
    }
4550
#endif
4551
    /* If we don't have any way of figuring out the actual executable
4552
       location then try argv[0].  */
4553
    if (!p) {
4554
        p = realpath(argv0, buf);
4555
        if (!p) {
4556
            return NULL;
4557
        }
4558
    }
4559
    dir = dirname(p);
4560
    dir = dirname(dir);
4561

    
4562
    max_len = strlen(dir) +
4563
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4564
    res = qemu_mallocz(max_len);
4565
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4566
    if (access(res, R_OK)) {
4567
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4568
        if (access(res, R_OK)) {
4569
            qemu_free(res);
4570
            res = NULL;
4571
        }
4572
    }
4573

    
4574
    return res;
4575
}
4576
#undef SHARE_SUFFIX
4577
#undef BUILD_SUFFIX
4578
#endif
4579

    
4580
char *qemu_find_file(int type, const char *name)
4581
{
4582
    int len;
4583
    const char *subdir;
4584
    char *buf;
4585

    
4586
    /* If name contains path separators then try it as a straight path.  */
4587
    if ((strchr(name, '/') || strchr(name, '\\'))
4588
        && access(name, R_OK) == 0) {
4589
        return qemu_strdup(name);
4590
    }
4591
    switch (type) {
4592
    case QEMU_FILE_TYPE_BIOS:
4593
        subdir = "";
4594
        break;
4595
    case QEMU_FILE_TYPE_KEYMAP:
4596
        subdir = "keymaps/";
4597
        break;
4598
    default:
4599
        abort();
4600
    }
4601
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4602
    buf = qemu_mallocz(len);
4603
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4604
    if (access(buf, R_OK)) {
4605
        qemu_free(buf);
4606
        return NULL;
4607
    }
4608
    return buf;
4609
}
4610

    
4611
static int device_help_func(QemuOpts *opts, void *opaque)
4612
{
4613
    return qdev_device_help(opts);
4614
}
4615

    
4616
static int device_init_func(QemuOpts *opts, void *opaque)
4617
{
4618
    DeviceState *dev;
4619

    
4620
    dev = qdev_device_add(opts);
4621
    if (!dev)
4622
        return -1;
4623
    return 0;
4624
}
4625

    
4626
static int chardev_init_func(QemuOpts *opts, void *opaque)
4627
{
4628
    CharDriverState *chr;
4629

    
4630
    chr = qemu_chr_open_opts(opts, NULL);
4631
    if (!chr)
4632
        return -1;
4633
    return 0;
4634
}
4635

    
4636
static int mon_init_func(QemuOpts *opts, void *opaque)
4637
{
4638
    CharDriverState *chr;
4639
    const char *chardev;
4640
    const char *mode;
4641
    int flags;
4642

    
4643
    mode = qemu_opt_get(opts, "mode");
4644
    if (mode == NULL) {
4645
        mode = "readline";
4646
    }
4647
    if (strcmp(mode, "readline") == 0) {
4648
        flags = MONITOR_USE_READLINE;
4649
    } else if (strcmp(mode, "control") == 0) {
4650
        flags = MONITOR_USE_CONTROL;
4651
    } else {
4652
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4653
        exit(1);
4654
    }
4655

    
4656
    if (qemu_opt_get_bool(opts, "default", 0))
4657
        flags |= MONITOR_IS_DEFAULT;
4658

    
4659
    chardev = qemu_opt_get(opts, "chardev");
4660
    chr = qemu_chr_find(chardev);
4661
    if (chr == NULL) {
4662
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4663
        exit(1);
4664
    }
4665

    
4666
    monitor_init(chr, flags);
4667
    return 0;
4668
}
4669

    
4670
static void monitor_parse(const char *optarg, const char *mode)
4671
{
4672
    static int monitor_device_index = 0;
4673
    QemuOpts *opts;
4674
    const char *p;
4675
    char label[32];
4676
    int def = 0;
4677

    
4678
    if (strstart(optarg, "chardev:", &p)) {
4679
        snprintf(label, sizeof(label), "%s", p);
4680
    } else {
4681
        if (monitor_device_index) {
4682
            snprintf(label, sizeof(label), "monitor%d",
4683
                     monitor_device_index);
4684
        } else {
4685
            snprintf(label, sizeof(label), "monitor");
4686
            def = 1;
4687
        }
4688
        opts = qemu_chr_parse_compat(label, optarg);
4689
        if (!opts) {
4690
            fprintf(stderr, "parse error: %s\n", optarg);
4691
            exit(1);
4692
        }
4693
    }
4694

    
4695
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4696
    if (!opts) {
4697
        fprintf(stderr, "duplicate chardev: %s\n", label);
4698
        exit(1);
4699
    }
4700
    qemu_opt_set(opts, "mode", mode);
4701
    qemu_opt_set(opts, "chardev", label);
4702
    if (def)
4703
        qemu_opt_set(opts, "default", "on");
4704
    monitor_device_index++;
4705
}
4706

    
4707
struct device_config {
4708
    enum {
4709
        DEV_USB,       /* -usbdevice     */
4710
        DEV_BT,        /* -bt            */
4711
        DEV_SERIAL,    /* -serial        */
4712
        DEV_PARALLEL,  /* -parallel      */
4713
        DEV_VIRTCON,   /* -virtioconsole */
4714
        DEV_DEBUGCON,  /* -debugcon */
4715
    } type;
4716
    const char *cmdline;
4717
    QTAILQ_ENTRY(device_config) next;
4718
};
4719
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4720

    
4721
static void add_device_config(int type, const char *cmdline)
4722
{
4723
    struct device_config *conf;
4724

    
4725
    conf = qemu_mallocz(sizeof(*conf));
4726
    conf->type = type;
4727
    conf->cmdline = cmdline;
4728
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4729
}
4730

    
4731
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4732
{
4733
    struct device_config *conf;
4734
    int rc;
4735

    
4736
    QTAILQ_FOREACH(conf, &device_configs, next) {
4737
        if (conf->type != type)
4738
            continue;
4739
        rc = func(conf->cmdline);
4740
        if (0 != rc)
4741
            return rc;
4742
    }
4743
    return 0;
4744
}
4745

    
4746
static int serial_parse(const char *devname)
4747
{
4748
    static int index = 0;
4749
    char label[32];
4750

    
4751
    if (strcmp(devname, "none") == 0)
4752
        return 0;
4753
    if (index == MAX_SERIAL_PORTS) {
4754
        fprintf(stderr, "qemu: too many serial ports\n");
4755
        exit(1);
4756
    }
4757
    snprintf(label, sizeof(label), "serial%d", index);
4758
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
4759
    if (!serial_hds[index]) {
4760
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4761
                devname, strerror(errno));
4762
        return -1;
4763
    }
4764
    index++;
4765
    return 0;
4766
}
4767

    
4768
static int parallel_parse(const char *devname)
4769
{
4770
    static int index = 0;
4771
    char label[32];
4772

    
4773
    if (strcmp(devname, "none") == 0)
4774
        return 0;
4775
    if (index == MAX_PARALLEL_PORTS) {
4776
        fprintf(stderr, "qemu: too many parallel ports\n");
4777
        exit(1);
4778
    }
4779
    snprintf(label, sizeof(label), "parallel%d", index);
4780
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4781
    if (!parallel_hds[index]) {
4782
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4783
                devname, strerror(errno));
4784
        return -1;
4785
    }
4786
    index++;
4787
    return 0;
4788
}
4789

    
4790
static int virtcon_parse(const char *devname)
4791
{
4792
    static int index = 0;
4793
    char label[32];
4794
    QemuOpts *bus_opts, *dev_opts;
4795

    
4796
    if (strcmp(devname, "none") == 0)
4797
        return 0;
4798
    if (index == MAX_VIRTIO_CONSOLES) {
4799
        fprintf(stderr, "qemu: too many virtio consoles\n");
4800
        exit(1);
4801
    }
4802

    
4803
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4804
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4805

    
4806
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4807
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4808

    
4809
    snprintf(label, sizeof(label), "virtcon%d", index);
4810
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4811
    if (!virtcon_hds[index]) {
4812
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4813
                devname, strerror(errno));
4814
        return -1;
4815
    }
4816
    qemu_opt_set(dev_opts, "chardev", label);
4817

    
4818
    index++;
4819
    return 0;
4820
}
4821

    
4822
static int debugcon_parse(const char *devname)
4823
{   
4824
    QemuOpts *opts;
4825

    
4826
    if (!qemu_chr_open("debugcon", devname, NULL)) {
4827
        exit(1);
4828
    }
4829
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4830
    if (!opts) {
4831
        fprintf(stderr, "qemu: already have a debugcon device\n");
4832
        exit(1);
4833
    }
4834
    qemu_opt_set(opts, "driver", "isa-debugcon");
4835
    qemu_opt_set(opts, "chardev", "debugcon");
4836
    return 0;
4837
}
4838

    
4839
static const QEMUOption *lookup_opt(int argc, char **argv,
4840
                                    const char **poptarg, int *poptind)
4841
{
4842
    const QEMUOption *popt;
4843
    int optind = *poptind;
4844
    char *r = argv[optind];
4845
    const char *optarg;
4846

    
4847
    loc_set_cmdline(argv, optind, 1);
4848
    optind++;
4849
    /* Treat --foo the same as -foo.  */
4850
    if (r[1] == '-')
4851
        r++;
4852
    popt = qemu_options;
4853
    for(;;) {
4854
        if (!popt->name) {
4855
            error_report("invalid option");
4856
            exit(1);
4857
        }
4858
        if (!strcmp(popt->name, r + 1))
4859
            break;
4860
        popt++;
4861
    }
4862
    if (popt->flags & HAS_ARG) {
4863
        if (optind >= argc) {
4864
            error_report("requires an argument");
4865
            exit(1);
4866
        }
4867
        optarg = argv[optind++];
4868
        loc_set_cmdline(argv, optind - 2, 2);
4869
    } else {
4870
        optarg = NULL;
4871
    }
4872

    
4873
    *poptarg = optarg;
4874
    *poptind = optind;
4875

    
4876
    return popt;
4877
}
4878

    
4879
int main(int argc, char **argv, char **envp)
4880
{
4881
    const char *gdbstub_dev = NULL;
4882
    uint32_t boot_devices_bitmap = 0;
4883
    int i;
4884
    int snapshot, linux_boot, net_boot;
4885
    const char *icount_option = NULL;
4886
    const char *initrd_filename;
4887
    const char *kernel_filename, *kernel_cmdline;
4888
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4889
    DisplayState *ds;
4890
    DisplayChangeListener *dcl;
4891
    int cyls, heads, secs, translation;
4892
    QemuOpts *hda_opts = NULL, *opts;
4893
    int optind;
4894
    const char *optarg;
4895
    const char *loadvm = NULL;
4896
    QEMUMachine *machine;
4897
    const char *cpu_model;
4898
#ifndef _WIN32
4899
    int fds[2];
4900
#endif
4901
    int tb_size;
4902
    const char *pid_file = NULL;
4903
    const char *incoming = NULL;
4904
#ifndef _WIN32
4905
    int fd = 0;
4906
    struct passwd *pwd = NULL;
4907
    const char *chroot_dir = NULL;
4908
    const char *run_as = NULL;
4909
#endif
4910
    CPUState *env;
4911
    int show_vnc_port = 0;
4912
    int defconfig = 1;
4913

    
4914
    error_set_progname(argv[0]);
4915

    
4916
    init_clocks();
4917

    
4918
    qemu_cache_utils_init(envp);
4919

    
4920
    QLIST_INIT (&vm_change_state_head);
4921
#ifndef _WIN32
4922
    {
4923
        struct sigaction act;
4924
        sigfillset(&act.sa_mask);
4925
        act.sa_flags = 0;
4926
        act.sa_handler = SIG_IGN;
4927
        sigaction(SIGPIPE, &act, NULL);
4928
    }
4929
#else
4930
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4931
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4932
       QEMU to run on a single CPU */
4933
    {
4934
        HANDLE h;
4935
        DWORD mask, smask;
4936
        int i;
4937
        h = GetCurrentProcess();
4938
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4939
            for(i = 0; i < 32; i++) {
4940
                if (mask & (1 << i))
4941
                    break;
4942
            }
4943
            if (i != 32) {
4944
                mask = 1 << i;
4945
                SetProcessAffinityMask(h, mask);
4946
            }
4947
        }
4948
    }
4949
#endif
4950

    
4951
    module_call_init(MODULE_INIT_MACHINE);
4952
    machine = find_default_machine();
4953
    cpu_model = NULL;
4954
    initrd_filename = NULL;
4955
    ram_size = 0;
4956
    snapshot = 0;
4957
    kernel_filename = NULL;
4958
    kernel_cmdline = "";
4959
    cyls = heads = secs = 0;
4960
    translation = BIOS_ATA_TRANSLATION_AUTO;
4961

    
4962
    for (i = 0; i < MAX_NODES; i++) {
4963
        node_mem[i] = 0;
4964
        node_cpumask[i] = 0;
4965
    }
4966

    
4967
    nb_numa_nodes = 0;
4968
    nb_nics = 0;
4969

    
4970
    tb_size = 0;
4971
    autostart= 1;
4972

    
4973
    /* first pass of option parsing */
4974
    optind = 1;
4975
    while (optind < argc) {
4976
        if (argv[optind][0] != '-') {
4977
            /* disk image */
4978
            optind++;
4979
            continue;
4980
        } else {
4981
            const QEMUOption *popt;
4982

    
4983
            popt = lookup_opt(argc, argv, &optarg, &optind);
4984
            switch (popt->index) {
4985
            case QEMU_OPTION_nodefconfig:
4986
                defconfig=0;
4987
                break;
4988
            }
4989
        }
4990
    }
4991

    
4992
    if (defconfig) {
4993
        const char *fname;
4994
        FILE *fp;
4995

    
4996
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
4997
        fp = fopen(fname, "r");
4998
        if (fp) {
4999
            if (qemu_config_parse(fp, fname) != 0) {
5000
                exit(1);
5001
            }
5002
            fclose(fp);
5003
        }
5004

    
5005
        fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
5006
        fp = fopen(fname, "r");
5007
        if (fp) {
5008
            if (qemu_config_parse(fp, fname) != 0) {
5009
                exit(1);
5010
            }
5011
            fclose(fp);
5012
        }
5013
    }
5014
#if defined(cpudef_setup)
5015
    cpudef_setup(); /* parse cpu definitions in target config file */
5016
#endif
5017

    
5018
    /* second pass of option parsing */
5019
    optind = 1;
5020
    for(;;) {
5021
        if (optind >= argc)
5022
            break;
5023
        if (argv[optind][0] != '-') {
5024
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5025
        } else {
5026
            const QEMUOption *popt;
5027

    
5028
            popt = lookup_opt(argc, argv, &optarg, &optind);
5029
            switch(popt->index) {
5030
            case QEMU_OPTION_M:
5031
                machine = find_machine(optarg);
5032
                if (!machine) {
5033
                    QEMUMachine *m;
5034
                    printf("Supported machines are:\n");
5035
                    for(m = first_machine; m != NULL; m = m->next) {
5036
                        if (m->alias)
5037
                            printf("%-10s %s (alias of %s)\n",
5038
                                   m->alias, m->desc, m->name);
5039
                        printf("%-10s %s%s\n",
5040
                               m->name, m->desc,
5041
                               m->is_default ? " (default)" : "");
5042
                    }
5043
                    exit(*optarg != '?');
5044
                }
5045
                break;
5046
            case QEMU_OPTION_cpu:
5047
                /* hw initialization will check this */
5048
                if (*optarg == '?') {
5049
/* XXX: implement xxx_cpu_list for targets that still miss it */
5050
#if defined(cpu_list_id)
5051
                    cpu_list_id(stdout, &fprintf, optarg);
5052
#elif defined(cpu_list)
5053
                    cpu_list(stdout, &fprintf);                /* deprecated */
5054
#endif
5055
                    exit(0);
5056
                } else {
5057
                    cpu_model = optarg;
5058
                }
5059
                break;
5060
            case QEMU_OPTION_initrd:
5061
                initrd_filename = optarg;
5062
                break;
5063
            case QEMU_OPTION_hda:
5064
                if (cyls == 0)
5065
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
5066
                else
5067
                    hda_opts = drive_add(optarg, HD_ALIAS
5068
                             ",cyls=%d,heads=%d,secs=%d%s",
5069
                             0, cyls, heads, secs,
5070
                             translation == BIOS_ATA_TRANSLATION_LBA ?
5071
                                 ",trans=lba" :
5072
                             translation == BIOS_ATA_TRANSLATION_NONE ?
5073
                                 ",trans=none" : "");
5074
                 break;
5075
            case QEMU_OPTION_hdb:
5076
            case QEMU_OPTION_hdc:
5077
            case QEMU_OPTION_hdd:
5078
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5079
                break;
5080
            case QEMU_OPTION_drive:
5081
                drive_add(NULL, "%s", optarg);
5082
                break;
5083
            case QEMU_OPTION_set:
5084
                if (qemu_set_option(optarg) != 0)
5085
                    exit(1);
5086
                break;
5087
            case QEMU_OPTION_global:
5088
                if (qemu_global_option(optarg) != 0)
5089
                    exit(1);
5090
                break;
5091
            case QEMU_OPTION_mtdblock:
5092
                drive_add(optarg, MTD_ALIAS);
5093
                break;
5094
            case QEMU_OPTION_sd:
5095
                drive_add(optarg, SD_ALIAS);
5096
                break;
5097
            case QEMU_OPTION_pflash:
5098
                drive_add(optarg, PFLASH_ALIAS);
5099
                break;
5100
            case QEMU_OPTION_snapshot:
5101
                snapshot = 1;
5102
                break;
5103
            case QEMU_OPTION_hdachs:
5104
                {
5105
                    const char *p;
5106
                    p = optarg;
5107
                    cyls = strtol(p, (char **)&p, 0);
5108
                    if (cyls < 1 || cyls > 16383)
5109
                        goto chs_fail;
5110
                    if (*p != ',')
5111
                        goto chs_fail;
5112
                    p++;
5113
                    heads = strtol(p, (char **)&p, 0);
5114
                    if (heads < 1 || heads > 16)
5115
                        goto chs_fail;
5116
                    if (*p != ',')
5117
                        goto chs_fail;
5118
                    p++;
5119
                    secs = strtol(p, (char **)&p, 0);
5120
                    if (secs < 1 || secs > 63)
5121
                        goto chs_fail;
5122
                    if (*p == ',') {
5123
                        p++;
5124
                        if (!strcmp(p, "none"))
5125
                            translation = BIOS_ATA_TRANSLATION_NONE;
5126
                        else if (!strcmp(p, "lba"))
5127
                            translation = BIOS_ATA_TRANSLATION_LBA;
5128
                        else if (!strcmp(p, "auto"))
5129
                            translation = BIOS_ATA_TRANSLATION_AUTO;
5130
                        else
5131
                            goto chs_fail;
5132
                    } else if (*p != '\0') {
5133
                    chs_fail:
5134
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
5135
                        exit(1);
5136
                    }
5137
                    if (hda_opts != NULL) {
5138
                        char num[16];
5139
                        snprintf(num, sizeof(num), "%d", cyls);
5140
                        qemu_opt_set(hda_opts, "cyls", num);
5141
                        snprintf(num, sizeof(num), "%d", heads);
5142
                        qemu_opt_set(hda_opts, "heads", num);
5143
                        snprintf(num, sizeof(num), "%d", secs);
5144
                        qemu_opt_set(hda_opts, "secs", num);
5145
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
5146
                            qemu_opt_set(hda_opts, "trans", "lba");
5147
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
5148
                            qemu_opt_set(hda_opts, "trans", "none");
5149
                    }
5150
                }
5151
                break;
5152
            case QEMU_OPTION_numa:
5153
                if (nb_numa_nodes >= MAX_NODES) {
5154
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
5155
                    exit(1);
5156
                }
5157
                numa_add(optarg);
5158
                break;
5159
            case QEMU_OPTION_nographic:
5160
                display_type = DT_NOGRAPHIC;
5161
                break;
5162
#ifdef CONFIG_CURSES
5163
            case QEMU_OPTION_curses:
5164
                display_type = DT_CURSES;
5165
                break;
5166
#endif
5167
            case QEMU_OPTION_portrait:
5168
                graphic_rotate = 1;
5169
                break;
5170
            case QEMU_OPTION_kernel:
5171
                kernel_filename = optarg;
5172
                break;
5173
            case QEMU_OPTION_append:
5174
                kernel_cmdline = optarg;
5175
                break;
5176
            case QEMU_OPTION_cdrom:
5177
                drive_add(optarg, CDROM_ALIAS);
5178
                break;
5179
            case QEMU_OPTION_boot:
5180
                {
5181
                    static const char * const params[] = {
5182
                        "order", "once", "menu", NULL
5183
                    };
5184
                    char buf[sizeof(boot_devices)];
5185
                    char *standard_boot_devices;
5186
                    int legacy = 0;
5187

    
5188
                    if (!strchr(optarg, '=')) {
5189
                        legacy = 1;
5190
                        pstrcpy(buf, sizeof(buf), optarg);
5191
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5192
                        fprintf(stderr,
5193
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5194
                                buf, optarg);
5195
                        exit(1);
5196
                    }
5197

    
5198
                    if (legacy ||
5199
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
5200
                        boot_devices_bitmap = parse_bootdevices(buf);
5201
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
5202
                    }
5203
                    if (!legacy) {
5204
                        if (get_param_value(buf, sizeof(buf),
5205
                                            "once", optarg)) {
5206
                            boot_devices_bitmap |= parse_bootdevices(buf);
5207
                            standard_boot_devices = qemu_strdup(boot_devices);
5208
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
5209
                            qemu_register_reset(restore_boot_devices,
5210
                                                standard_boot_devices);
5211
                        }
5212
                        if (get_param_value(buf, sizeof(buf),
5213
                                            "menu", optarg)) {
5214
                            if (!strcmp(buf, "on")) {
5215
                                boot_menu = 1;
5216
                            } else if (!strcmp(buf, "off")) {
5217
                                boot_menu = 0;
5218
                            } else {
5219
                                fprintf(stderr,
5220
                                        "qemu: invalid option value '%s'\n",
5221
                                        buf);
5222
                                exit(1);
5223
                            }
5224
                        }
5225
                    }
5226
                }
5227
                break;
5228
            case QEMU_OPTION_fda:
5229
            case QEMU_OPTION_fdb:
5230
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5231
                break;
5232
#ifdef TARGET_I386
5233
            case QEMU_OPTION_no_fd_bootchk:
5234
                fd_bootchk = 0;
5235
                break;
5236
#endif
5237
            case QEMU_OPTION_netdev:
5238
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
5239
                    exit(1);
5240
                }
5241
                break;
5242
            case QEMU_OPTION_net:
5243
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
5244
                    exit(1);
5245
                }
5246
                break;
5247
#ifdef CONFIG_SLIRP
5248
            case QEMU_OPTION_tftp:
5249
                legacy_tftp_prefix = optarg;
5250
                break;
5251
            case QEMU_OPTION_bootp:
5252
                legacy_bootp_filename = optarg;
5253
                break;
5254
#ifndef _WIN32
5255
            case QEMU_OPTION_smb:
5256
                if (net_slirp_smb(optarg) < 0)
5257
                    exit(1);
5258
                break;
5259
#endif
5260
            case QEMU_OPTION_redir:
5261
                if (net_slirp_redir(optarg) < 0)
5262
                    exit(1);
5263
                break;
5264
#endif
5265
            case QEMU_OPTION_bt:
5266
                add_device_config(DEV_BT, optarg);
5267
                break;
5268
#ifdef HAS_AUDIO
5269
            case QEMU_OPTION_audio_help:
5270
                AUD_help ();
5271
                exit (0);
5272
                break;
5273
            case QEMU_OPTION_soundhw:
5274
                select_soundhw (optarg);
5275
                break;
5276
#endif
5277
            case QEMU_OPTION_h:
5278
                help(0);
5279
                break;
5280
            case QEMU_OPTION_version:
5281
                version();
5282
                exit(0);
5283
                break;
5284
            case QEMU_OPTION_m: {
5285
                uint64_t value;
5286
                char *ptr;
5287

    
5288
                value = strtoul(optarg, &ptr, 10);
5289
                switch (*ptr) {
5290
                case 0: case 'M': case 'm':
5291
                    value <<= 20;
5292
                    break;
5293
                case 'G': case 'g':
5294
                    value <<= 30;
5295
                    break;
5296
                default:
5297
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5298
                    exit(1);
5299
                }
5300

    
5301
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5302
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5303
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5304
                    exit(1);
5305
                }
5306
                if (value != (uint64_t)(ram_addr_t)value) {
5307
                    fprintf(stderr, "qemu: ram size too large\n");
5308
                    exit(1);
5309
                }
5310
                ram_size = value;
5311
                break;
5312
            }
5313
            case QEMU_OPTION_mempath:
5314
                mem_path = optarg;
5315
                break;
5316
#ifdef MAP_POPULATE
5317
            case QEMU_OPTION_mem_prealloc:
5318
                mem_prealloc = 1;
5319
                break;
5320
#endif
5321
            case QEMU_OPTION_d:
5322
                {
5323
                    int mask;
5324
                    const CPULogItem *item;
5325

    
5326
                    mask = cpu_str_to_log_mask(optarg);
5327
                    if (!mask) {
5328
                        printf("Log items (comma separated):\n");
5329
                    for(item = cpu_log_items; item->mask != 0; item++) {
5330
                        printf("%-10s %s\n", item->name, item->help);
5331
                    }
5332
                    exit(1);
5333
                    }
5334
                    cpu_set_log(mask);
5335
                }
5336
                break;
5337
            case QEMU_OPTION_s:
5338
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5339
                break;
5340
            case QEMU_OPTION_gdb:
5341
                gdbstub_dev = optarg;
5342
                break;
5343
            case QEMU_OPTION_L:
5344
                data_dir = optarg;
5345
                break;
5346
            case QEMU_OPTION_bios:
5347
                bios_name = optarg;
5348
                break;
5349
            case QEMU_OPTION_singlestep:
5350
                singlestep = 1;
5351
                break;
5352
            case QEMU_OPTION_S:
5353
                autostart = 0;
5354
                break;
5355
            case QEMU_OPTION_k:
5356
                keyboard_layout = optarg;
5357
                break;
5358
            case QEMU_OPTION_localtime:
5359
                rtc_utc = 0;
5360
                break;
5361
            case QEMU_OPTION_vga:
5362
                select_vgahw (optarg);
5363
                break;
5364
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5365
            case QEMU_OPTION_g:
5366
                {
5367
                    const char *p;
5368
                    int w, h, depth;
5369
                    p = optarg;
5370
                    w = strtol(p, (char **)&p, 10);
5371
                    if (w <= 0) {
5372
                    graphic_error:
5373
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5374
                        exit(1);
5375
                    }
5376
                    if (*p != 'x')
5377
                        goto graphic_error;
5378
                    p++;
5379
                    h = strtol(p, (char **)&p, 10);
5380
                    if (h <= 0)
5381
                        goto graphic_error;
5382
                    if (*p == 'x') {
5383
                        p++;
5384
                        depth = strtol(p, (char **)&p, 10);
5385
                        if (depth != 8 && depth != 15 && depth != 16 &&
5386
                            depth != 24 && depth != 32)
5387
                            goto graphic_error;
5388
                    } else if (*p == '\0') {
5389
                        depth = graphic_depth;
5390
                    } else {
5391
                        goto graphic_error;
5392
                    }
5393

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

    
5720
    /* If no data_dir is specified then try to find it relative to the
5721
       executable path.  */
5722
    if (!data_dir) {
5723
        data_dir = find_datadir(argv[0]);
5724
    }
5725
    /* If all else fails use the install patch specified when building.  */
5726
    if (!data_dir) {
5727
        data_dir = CONFIG_QEMU_SHAREDIR;
5728
    }
5729

    
5730
    /*
5731
     * Default to max_cpus = smp_cpus, in case the user doesn't
5732
     * specify a max_cpus value.
5733
     */
5734
    if (!max_cpus)
5735
        max_cpus = smp_cpus;
5736

    
5737
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5738
    if (smp_cpus > machine->max_cpus) {
5739
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5740
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5741
                machine->max_cpus);
5742
        exit(1);
5743
    }
5744

    
5745
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5746
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5747

    
5748
    if (machine->no_serial) {
5749
        default_serial = 0;
5750
    }
5751
    if (machine->no_parallel) {
5752
        default_parallel = 0;
5753
    }
5754
    if (!machine->use_virtcon) {
5755
        default_virtcon = 0;
5756
    }
5757
    if (machine->no_vga) {
5758
        default_vga = 0;
5759
    }
5760
    if (machine->no_floppy) {
5761
        default_floppy = 0;
5762
    }
5763
    if (machine->no_cdrom) {
5764
        default_cdrom = 0;
5765
    }
5766
    if (machine->no_sdcard) {
5767
        default_sdcard = 0;
5768
    }
5769

    
5770
    if (display_type == DT_NOGRAPHIC) {
5771
        if (default_parallel)
5772
            add_device_config(DEV_PARALLEL, "null");
5773
        if (default_serial && default_monitor) {
5774
            add_device_config(DEV_SERIAL, "mon:stdio");
5775
        } else if (default_virtcon && default_monitor) {
5776
            add_device_config(DEV_VIRTCON, "mon:stdio");
5777
        } else {
5778
            if (default_serial)
5779
                add_device_config(DEV_SERIAL, "stdio");
5780
            if (default_virtcon)
5781
                add_device_config(DEV_VIRTCON, "stdio");
5782
            if (default_monitor)
5783
                monitor_parse("stdio", "readline");
5784
        }
5785
    } else {
5786
        if (default_serial)
5787
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5788
        if (default_parallel)
5789
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5790
        if (default_monitor)
5791
            monitor_parse("vc:80Cx24C", "readline");
5792
        if (default_virtcon)
5793
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5794
    }
5795
    if (default_vga)
5796
        vga_interface_type = VGA_CIRRUS;
5797

    
5798
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5799
        exit(1);
5800

    
5801
#ifndef _WIN32
5802
    if (daemonize) {
5803
        pid_t pid;
5804

    
5805
        if (pipe(fds) == -1)
5806
            exit(1);
5807

    
5808
        pid = fork();
5809
        if (pid > 0) {
5810
            uint8_t status;
5811
            ssize_t len;
5812

    
5813
            close(fds[1]);
5814

    
5815
        again:
5816
            len = read(fds[0], &status, 1);
5817
            if (len == -1 && (errno == EINTR))
5818
                goto again;
5819

    
5820
            if (len != 1)
5821
                exit(1);
5822
            else if (status == 1) {
5823
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5824
                exit(1);
5825
            } else
5826
                exit(0);
5827
        } else if (pid < 0)
5828
            exit(1);
5829

    
5830
        close(fds[0]);
5831
        qemu_set_cloexec(fds[1]);
5832

    
5833
        setsid();
5834

    
5835
        pid = fork();
5836
        if (pid > 0)
5837
            exit(0);
5838
        else if (pid < 0)
5839
            exit(1);
5840

    
5841
        umask(027);
5842

    
5843
        signal(SIGTSTP, SIG_IGN);
5844
        signal(SIGTTOU, SIG_IGN);
5845
        signal(SIGTTIN, SIG_IGN);
5846
    }
5847
#endif
5848

    
5849
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5850
#ifndef _WIN32
5851
        if (daemonize) {
5852
            uint8_t status = 1;
5853
            if (write(fds[1], &status, 1) != 1) {
5854
                perror("daemonize. Writing to pipe\n");
5855
            }
5856
        } else
5857
#endif
5858
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5859
        exit(1);
5860
    }
5861

    
5862
    if (kvm_enabled()) {
5863
        int ret;
5864

    
5865
        ret = kvm_init(smp_cpus);
5866
        if (ret < 0) {
5867
            fprintf(stderr, "failed to initialize KVM\n");
5868
            exit(1);
5869
        }
5870
    }
5871

    
5872
    if (qemu_init_main_loop()) {
5873
        fprintf(stderr, "qemu_init_main_loop failed\n");
5874
        exit(1);
5875
    }
5876
    linux_boot = (kernel_filename != NULL);
5877

    
5878
    if (!linux_boot && *kernel_cmdline != '\0') {
5879
        fprintf(stderr, "-append only allowed with -kernel option\n");
5880
        exit(1);
5881
    }
5882

    
5883
    if (!linux_boot && initrd_filename != NULL) {
5884
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5885
        exit(1);
5886
    }
5887

    
5888
#ifndef _WIN32
5889
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5890
    setvbuf(stdout, NULL, _IOLBF, 0);
5891
#endif
5892

    
5893
    if (init_timer_alarm() < 0) {
5894
        fprintf(stderr, "could not initialize alarm timer\n");
5895
        exit(1);
5896
    }
5897
    configure_icount(icount_option);
5898

    
5899
#ifdef _WIN32
5900
    socket_init();
5901
#endif
5902

    
5903
    if (net_init_clients() < 0) {
5904
        exit(1);
5905
    }
5906

    
5907
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5908
    net_set_boot_mask(net_boot);
5909

    
5910
    /* init the bluetooth world */
5911
    if (foreach_device_config(DEV_BT, bt_parse))
5912
        exit(1);
5913

    
5914
    /* init the memory */
5915
    if (ram_size == 0)
5916
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5917

    
5918
    /* init the dynamic translator */
5919
    cpu_exec_init_all(tb_size * 1024 * 1024);
5920

    
5921
    bdrv_init_with_whitelist();
5922

    
5923
    blk_mig_init();
5924

    
5925
    if (default_cdrom) {
5926
        /* we always create the cdrom drive, even if no disk is there */
5927
        drive_add(NULL, CDROM_ALIAS);
5928
    }
5929

    
5930
    if (default_floppy) {
5931
        /* we always create at least one floppy */
5932
        drive_add(NULL, FD_ALIAS, 0);
5933
    }
5934

    
5935
    if (default_sdcard) {
5936
        /* we always create one sd slot, even if no card is in it */
5937
        drive_add(NULL, SD_ALIAS);
5938
    }
5939

    
5940
    /* open the virtual block devices */
5941
    if (snapshot)
5942
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5943
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5944
        exit(1);
5945

    
5946
    vmstate_register(0, &vmstate_timers ,&timers_state);
5947
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5948
                         ram_load, NULL);
5949

    
5950
    if (nb_numa_nodes > 0) {
5951
        int i;
5952

    
5953
        if (nb_numa_nodes > smp_cpus) {
5954
            nb_numa_nodes = smp_cpus;
5955
        }
5956

    
5957
        /* If no memory size if given for any node, assume the default case
5958
         * and distribute the available memory equally across all nodes
5959
         */
5960
        for (i = 0; i < nb_numa_nodes; i++) {
5961
            if (node_mem[i] != 0)
5962
                break;
5963
        }
5964
        if (i == nb_numa_nodes) {
5965
            uint64_t usedmem = 0;
5966

    
5967
            /* On Linux, the each node's border has to be 8MB aligned,
5968
             * the final node gets the rest.
5969
             */
5970
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5971
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5972
                usedmem += node_mem[i];
5973
            }
5974
            node_mem[i] = ram_size - usedmem;
5975
        }
5976

    
5977
        for (i = 0; i < nb_numa_nodes; i++) {
5978
            if (node_cpumask[i] != 0)
5979
                break;
5980
        }
5981
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5982
         * must cope with this anyway, because there are BIOSes out there in
5983
         * real machines which also use this scheme.
5984
         */
5985
        if (i == nb_numa_nodes) {
5986
            for (i = 0; i < smp_cpus; i++) {
5987
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5988
            }
5989
        }
5990
    }
5991

    
5992
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5993
        exit(1);
5994
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5995
        exit(1);
5996
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5997
        exit(1);
5998
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5999
        exit(1);
6000

    
6001
    module_call_init(MODULE_INIT_DEVICE);
6002

    
6003
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
6004
        exit(0);
6005

    
6006
    if (watchdog) {
6007
        i = select_watchdog(watchdog);
6008
        if (i > 0)
6009
            exit (i == 1 ? 1 : 0);
6010
    }
6011

    
6012
    if (machine->compat_props) {
6013
        qdev_prop_register_global_list(machine->compat_props);
6014
    }
6015
    qemu_add_globals();
6016

    
6017
    machine->init(ram_size, boot_devices,
6018
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6019

    
6020
    cpu_synchronize_all_post_init();
6021

    
6022
#ifndef _WIN32
6023
    /* must be after terminal init, SDL library changes signal handlers */
6024
    sighandler_setup();
6025
#endif
6026

    
6027
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
6028
        for (i = 0; i < nb_numa_nodes; i++) {
6029
            if (node_cpumask[i] & (1 << env->cpu_index)) {
6030
                env->numa_node = i;
6031
            }
6032
        }
6033
    }
6034

    
6035
    current_machine = machine;
6036

    
6037
    /* init USB devices */
6038
    if (usb_enabled) {
6039
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
6040
            exit(1);
6041
    }
6042

    
6043
    /* init generic devices */
6044
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6045
        exit(1);
6046

    
6047
    net_check_clients();
6048

    
6049
    /* just use the first displaystate for the moment */
6050
    ds = get_displaystate();
6051

    
6052
    if (display_type == DT_DEFAULT) {
6053
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6054
        display_type = DT_SDL;
6055
#else
6056
        display_type = DT_VNC;
6057
        vnc_display = "localhost:0,to=99";
6058
        show_vnc_port = 1;
6059
#endif
6060
    }
6061
        
6062

    
6063
    switch (display_type) {
6064
    case DT_NOGRAPHIC:
6065
        break;
6066
#if defined(CONFIG_CURSES)
6067
    case DT_CURSES:
6068
        curses_display_init(ds, full_screen);
6069
        break;
6070
#endif
6071
#if defined(CONFIG_SDL)
6072
    case DT_SDL:
6073
        sdl_display_init(ds, full_screen, no_frame);
6074
        break;
6075
#elif defined(CONFIG_COCOA)
6076
    case DT_SDL:
6077
        cocoa_display_init(ds, full_screen);
6078
        break;
6079
#endif
6080
    case DT_VNC:
6081
        vnc_display_init(ds);
6082
        if (vnc_display_open(ds, vnc_display) < 0)
6083
            exit(1);
6084

    
6085
        if (show_vnc_port) {
6086
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6087
        }
6088
        break;
6089
    default:
6090
        break;
6091
    }
6092
    dpy_resize(ds);
6093

    
6094
    dcl = ds->listeners;
6095
    while (dcl != NULL) {
6096
        if (dcl->dpy_refresh != NULL) {
6097
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6098
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6099
        }
6100
        dcl = dcl->next;
6101
    }
6102

    
6103
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6104
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6105
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6106
    }
6107

    
6108
    text_consoles_set_display(ds);
6109

    
6110
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6111
        exit(1);
6112

    
6113
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6114
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6115
                gdbstub_dev);
6116
        exit(1);
6117
    }
6118

    
6119
    qdev_machine_creation_done();
6120

    
6121
    if (rom_load_all() != 0) {
6122
        fprintf(stderr, "rom loading failed\n");
6123
        exit(1);
6124
    }
6125

    
6126
    qemu_system_reset();
6127
    if (loadvm) {
6128
        if (load_vmstate(loadvm) < 0) {
6129
            autostart = 0;
6130
        }
6131
    }
6132

    
6133
    if (incoming) {
6134
        qemu_start_incoming_migration(incoming);
6135
    } else if (autostart) {
6136
        vm_start();
6137
    }
6138

    
6139
#ifndef _WIN32
6140
    if (daemonize) {
6141
        uint8_t status = 0;
6142
        ssize_t len;
6143

    
6144
    again1:
6145
        len = write(fds[1], &status, 1);
6146
        if (len == -1 && (errno == EINTR))
6147
            goto again1;
6148

    
6149
        if (len != 1)
6150
            exit(1);
6151

    
6152
        if (chdir("/")) {
6153
            perror("not able to chdir to /");
6154
            exit(1);
6155
        }
6156
        TFR(fd = qemu_open("/dev/null", O_RDWR));
6157
        if (fd == -1)
6158
            exit(1);
6159
    }
6160

    
6161
    if (run_as) {
6162
        pwd = getpwnam(run_as);
6163
        if (!pwd) {
6164
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6165
            exit(1);
6166
        }
6167
    }
6168

    
6169
    if (chroot_dir) {
6170
        if (chroot(chroot_dir) < 0) {
6171
            fprintf(stderr, "chroot failed\n");
6172
            exit(1);
6173
        }
6174
        if (chdir("/")) {
6175
            perror("not able to chdir to /");
6176
            exit(1);
6177
        }
6178
    }
6179

    
6180
    if (run_as) {
6181
        if (setgid(pwd->pw_gid) < 0) {
6182
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6183
            exit(1);
6184
        }
6185
        if (setuid(pwd->pw_uid) < 0) {
6186
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6187
            exit(1);
6188
        }
6189
        if (setuid(0) != -1) {
6190
            fprintf(stderr, "Dropping privileges failed\n");
6191
            exit(1);
6192
        }
6193
    }
6194

    
6195
    if (daemonize) {
6196
        dup2(fd, 0);
6197
        dup2(fd, 1);
6198
        dup2(fd, 2);
6199

    
6200
        close(fd);
6201
    }
6202
#endif
6203

    
6204
    main_loop();
6205
    quit_timers();
6206
    net_cleanup();
6207

    
6208
    return 0;
6209
}