Statistics
| Branch: | Revision:

root / vl.c @ 63255043

History | View | Annotate | Download (157.5 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
/* enable cpu_get_ticks() */
552
void cpu_enable_ticks(void)
553
{
554
    if (!timers_state.cpu_ticks_enabled) {
555
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
556
        timers_state.cpu_clock_offset -= get_clock();
557
        timers_state.cpu_ticks_enabled = 1;
558
    }
559
}
560

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

    
572
/***********************************************************/
573
/* timers */
574

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

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

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

    
593
struct qemu_alarm_timer {
594
    char const *name;
595
    int (*start)(struct qemu_alarm_timer *t);
596
    void (*stop)(struct qemu_alarm_timer *t);
597
    void (*rearm)(struct qemu_alarm_timer *t);
598
    void *priv;
599

    
600
    char expired;
601
    char pending;
602
};
603

    
604
static struct qemu_alarm_timer *alarm_timer;
605

    
606
static inline int qemu_alarm_pending(void)
607
{
608
    return alarm_timer->pending;
609
}
610

    
611
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
612
{
613
    return !!t->rearm;
614
}
615

    
616
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
617
{
618
    if (!alarm_has_dynticks(t))
619
        return;
620

    
621
    t->rearm(t);
622
}
623

    
624
/* TODO: MIN_TIMER_REARM_US should be optimized */
625
#define MIN_TIMER_REARM_US 250
626

    
627
#ifdef _WIN32
628

    
629
struct qemu_alarm_win32 {
630
    MMRESULT timerId;
631
    unsigned int period;
632
} alarm_win32_data = {0, 0};
633

    
634
static int win32_start_timer(struct qemu_alarm_timer *t);
635
static void win32_stop_timer(struct qemu_alarm_timer *t);
636
static void win32_rearm_timer(struct qemu_alarm_timer *t);
637

    
638
#else
639

    
640
static int unix_start_timer(struct qemu_alarm_timer *t);
641
static void unix_stop_timer(struct qemu_alarm_timer *t);
642

    
643
#ifdef __linux__
644

    
645
static int dynticks_start_timer(struct qemu_alarm_timer *t);
646
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
647
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
648

    
649
static int hpet_start_timer(struct qemu_alarm_timer *t);
650
static void hpet_stop_timer(struct qemu_alarm_timer *t);
651

    
652
static int rtc_start_timer(struct qemu_alarm_timer *t);
653
static void rtc_stop_timer(struct qemu_alarm_timer *t);
654

    
655
#endif /* __linux__ */
656

    
657
#endif /* _WIN32 */
658

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

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

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

    
695
static void icount_adjust_rt(void * opaque)
696
{
697
    qemu_mod_timer(icount_rt_timer,
698
                   qemu_get_clock(rt_clock) + 1000);
699
    icount_adjust();
700
}
701

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

    
709
static void configure_icount(const char *option)
710
{
711
    if (!option)
712
        return;
713

    
714
    if (strcmp(option, "auto") != 0) {
715
        icount_time_shift = strtol(option, NULL, 0);
716
        use_icount = 1;
717
        return;
718
    }
719

    
720
    use_icount = 2;
721

    
722
    /* 125MIPS seems a reasonable initial guess at the guest speed.
723
       It will be corrected fairly quickly anyway.  */
724
    icount_time_shift = 3;
725

    
726
    /* Have both realtime and virtual time triggers for speed adjustment.
727
       The realtime trigger catches emulated time passing too slowly,
728
       the virtual time trigger catches emulated time passing too fast.
729
       Realtime triggers occur even when idle, so use them less frequently
730
       than VM triggers.  */
731
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
732
    qemu_mod_timer(icount_rt_timer,
733
                   qemu_get_clock(rt_clock) + 1000);
734
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
735
    qemu_mod_timer(icount_vm_timer,
736
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
737
}
738

    
739
static int64_t qemu_icount_round(int64_t count)
740
{
741
    return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
742
}
743

    
744
static struct qemu_alarm_timer alarm_timers[] = {
745
#ifndef _WIN32
746
#ifdef __linux__
747
    {"dynticks", dynticks_start_timer,
748
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
749
    /* HPET - if available - is preferred */
750
    {"hpet", hpet_start_timer, hpet_stop_timer, NULL, NULL},
751
    /* ...otherwise try RTC */
752
    {"rtc", rtc_start_timer, rtc_stop_timer, NULL, NULL},
753
#endif
754
    {"unix", unix_start_timer, unix_stop_timer, NULL, NULL},
755
#else
756
    {"dynticks", win32_start_timer,
757
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
758
    {"win32", win32_start_timer,
759
     win32_stop_timer, NULL, &alarm_win32_data},
760
#endif
761
    {NULL, }
762
};
763

    
764
static void show_available_alarms(void)
765
{
766
    int i;
767

    
768
    printf("Available alarm timers, in order of precedence:\n");
769
    for (i = 0; alarm_timers[i].name; i++)
770
        printf("%s\n", alarm_timers[i].name);
771
}
772

    
773
static void configure_alarms(char const *opt)
774
{
775
    int i;
776
    int cur = 0;
777
    int count = ARRAY_SIZE(alarm_timers) - 1;
778
    char *arg;
779
    char *name;
780
    struct qemu_alarm_timer tmp;
781

    
782
    if (!strcmp(opt, "?")) {
783
        show_available_alarms();
784
        exit(0);
785
    }
786

    
787
    arg = qemu_strdup(opt);
788

    
789
    /* Reorder the array */
790
    name = strtok(arg, ",");
791
    while (name) {
792
        for (i = 0; i < count && alarm_timers[i].name; i++) {
793
            if (!strcmp(alarm_timers[i].name, name))
794
                break;
795
        }
796

    
797
        if (i == count) {
798
            fprintf(stderr, "Unknown clock %s\n", name);
799
            goto next;
800
        }
801

    
802
        if (i < cur)
803
            /* Ignore */
804
            goto next;
805

    
806
        /* Swap */
807
        tmp = alarm_timers[i];
808
        alarm_timers[i] = alarm_timers[cur];
809
        alarm_timers[cur] = tmp;
810

    
811
        cur++;
812
next:
813
        name = strtok(NULL, ",");
814
    }
815

    
816
    qemu_free(arg);
817

    
818
    if (cur) {
819
        /* Disable remaining timers */
820
        for (i = cur; i < count; i++)
821
            alarm_timers[i].name = NULL;
822
    } else {
823
        show_available_alarms();
824
        exit(1);
825
    }
826
}
827

    
828
#define QEMU_NUM_CLOCKS 3
829

    
830
QEMUClock *rt_clock;
831
QEMUClock *vm_clock;
832
QEMUClock *host_clock;
833

    
834
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
835

    
836
static QEMUClock *qemu_new_clock(int type)
837
{
838
    QEMUClock *clock;
839
    clock = qemu_mallocz(sizeof(QEMUClock));
840
    clock->type = type;
841
    clock->enabled = 1;
842
    return clock;
843
}
844

    
845
static void qemu_clock_enable(QEMUClock *clock, int enabled)
846
{
847
    clock->enabled = enabled;
848
}
849

    
850
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
851
{
852
    QEMUTimer *ts;
853

    
854
    ts = qemu_mallocz(sizeof(QEMUTimer));
855
    ts->clock = clock;
856
    ts->cb = cb;
857
    ts->opaque = opaque;
858
    return ts;
859
}
860

    
861
void qemu_free_timer(QEMUTimer *ts)
862
{
863
    qemu_free(ts);
864
}
865

    
866
/* stop a timer, but do not dealloc it */
867
void qemu_del_timer(QEMUTimer *ts)
868
{
869
    QEMUTimer **pt, *t;
870

    
871
    /* NOTE: this code must be signal safe because
872
       qemu_timer_expired() can be called from a signal. */
873
    pt = &active_timers[ts->clock->type];
874
    for(;;) {
875
        t = *pt;
876
        if (!t)
877
            break;
878
        if (t == ts) {
879
            *pt = t->next;
880
            break;
881
        }
882
        pt = &t->next;
883
    }
884
}
885

    
886
/* modify the current timer so that it will be fired when current_time
887
   >= expire_time. The corresponding callback will be called. */
888
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
889
{
890
    QEMUTimer **pt, *t;
891

    
892
    qemu_del_timer(ts);
893

    
894
    /* add the timer in the sorted list */
895
    /* NOTE: this code must be signal safe because
896
       qemu_timer_expired() can be called from a signal. */
897
    pt = &active_timers[ts->clock->type];
898
    for(;;) {
899
        t = *pt;
900
        if (!t)
901
            break;
902
        if (t->expire_time > expire_time)
903
            break;
904
        pt = &t->next;
905
    }
906
    ts->expire_time = expire_time;
907
    ts->next = *pt;
908
    *pt = ts;
909

    
910
    /* Rearm if necessary  */
911
    if (pt == &active_timers[ts->clock->type]) {
912
        if (!alarm_timer->pending) {
913
            qemu_rearm_alarm_timer(alarm_timer);
914
        }
915
        /* Interrupt execution to force deadline recalculation.  */
916
        if (use_icount)
917
            qemu_notify_event();
918
    }
919
}
920

    
921
int qemu_timer_pending(QEMUTimer *ts)
922
{
923
    QEMUTimer *t;
924
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
925
        if (t == ts)
926
            return 1;
927
    }
928
    return 0;
929
}
930

    
931
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
932
{
933
    if (!timer_head)
934
        return 0;
935
    return (timer_head->expire_time <= current_time);
936
}
937

    
938
static void qemu_run_timers(QEMUClock *clock)
939
{
940
    QEMUTimer **ptimer_head, *ts;
941
    int64_t current_time;
942
   
943
    if (!clock->enabled)
944
        return;
945

    
946
    current_time = qemu_get_clock (clock);
947
    ptimer_head = &active_timers[clock->type];
948
    for(;;) {
949
        ts = *ptimer_head;
950
        if (!ts || ts->expire_time > current_time)
951
            break;
952
        /* remove timer from the list before calling the callback */
953
        *ptimer_head = ts->next;
954
        ts->next = NULL;
955

    
956
        /* run the callback (the timer list can be modified) */
957
        ts->cb(ts->opaque);
958
    }
959
}
960

    
961
int64_t qemu_get_clock(QEMUClock *clock)
962
{
963
    switch(clock->type) {
964
    case QEMU_CLOCK_REALTIME:
965
        return get_clock() / 1000000;
966
    default:
967
    case QEMU_CLOCK_VIRTUAL:
968
        if (use_icount) {
969
            return cpu_get_icount();
970
        } else {
971
            return cpu_get_clock();
972
        }
973
    case QEMU_CLOCK_HOST:
974
        return get_clock_realtime();
975
    }
976
}
977

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

    
995
static void init_clocks(void)
996
{
997
    init_get_clock();
998
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
999
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1000
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1001

    
1002
    rtc_clock = host_clock;
1003
}
1004

    
1005
/* save a timer */
1006
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1007
{
1008
    uint64_t expire_time;
1009

    
1010
    if (qemu_timer_pending(ts)) {
1011
        expire_time = ts->expire_time;
1012
    } else {
1013
        expire_time = -1;
1014
    }
1015
    qemu_put_be64(f, expire_time);
1016
}
1017

    
1018
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1019
{
1020
    uint64_t expire_time;
1021

    
1022
    expire_time = qemu_get_be64(f);
1023
    if (expire_time != -1) {
1024
        qemu_mod_timer(ts, expire_time);
1025
    } else {
1026
        qemu_del_timer(ts);
1027
    }
1028
}
1029

    
1030
static const VMStateDescription vmstate_timers = {
1031
    .name = "timer",
1032
    .version_id = 2,
1033
    .minimum_version_id = 1,
1034
    .minimum_version_id_old = 1,
1035
    .fields      = (VMStateField []) {
1036
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
1037
        VMSTATE_INT64(dummy, TimersState),
1038
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1039
        VMSTATE_END_OF_LIST()
1040
    }
1041
};
1042

    
1043
static void qemu_run_all_timers(void)
1044
{
1045
    /* rearm timer, if not periodic */
1046
    if (alarm_timer->expired) {
1047
        alarm_timer->expired = 0;
1048
        qemu_rearm_alarm_timer(alarm_timer);
1049
    }
1050

    
1051
    alarm_timer->pending = 0;
1052

    
1053
    /* vm time timers */
1054
    if (vm_running) {
1055
        qemu_run_timers(vm_clock);
1056
    }
1057

    
1058
    qemu_run_timers(rt_clock);
1059
    qemu_run_timers(host_clock);
1060
}
1061

    
1062
#ifdef _WIN32
1063
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1064
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1065
                                        DWORD_PTR dw2)
1066
#else
1067
static void host_alarm_handler(int host_signum)
1068
#endif
1069
{
1070
    struct qemu_alarm_timer *t = alarm_timer;
1071
    if (!t)
1072
        return;
1073

    
1074
#if 0
1075
#define DISP_FREQ 1000
1076
    {
1077
        static int64_t delta_min = INT64_MAX;
1078
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1079
        static int count;
1080
        ti = qemu_get_clock(vm_clock);
1081
        if (last_clock != 0) {
1082
            delta = ti - last_clock;
1083
            if (delta < delta_min)
1084
                delta_min = delta;
1085
            if (delta > delta_max)
1086
                delta_max = delta;
1087
            delta_cum += delta;
1088
            if (++count == DISP_FREQ) {
1089
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1090
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1091
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1092
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1093
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1094
                count = 0;
1095
                delta_min = INT64_MAX;
1096
                delta_max = 0;
1097
                delta_cum = 0;
1098
            }
1099
        }
1100
        last_clock = ti;
1101
    }
1102
#endif
1103
    if (alarm_has_dynticks(t) ||
1104
        (!use_icount &&
1105
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1106
                               qemu_get_clock(vm_clock))) ||
1107
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1108
                           qemu_get_clock(rt_clock)) ||
1109
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1110
                           qemu_get_clock(host_clock))) {
1111

    
1112
        t->expired = alarm_has_dynticks(t);
1113
        t->pending = 1;
1114
        qemu_notify_event();
1115
    }
1116
}
1117

    
1118
static int64_t qemu_next_deadline(void)
1119
{
1120
    /* To avoid problems with overflow limit this to 2^32.  */
1121
    int64_t delta = INT32_MAX;
1122

    
1123
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1124
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1125
                     qemu_get_clock(vm_clock);
1126
    }
1127
    if (active_timers[QEMU_CLOCK_HOST]) {
1128
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1129
                 qemu_get_clock(host_clock);
1130
        if (hdelta < delta)
1131
            delta = hdelta;
1132
    }
1133

    
1134
    if (delta < 0)
1135
        delta = 0;
1136

    
1137
    return delta;
1138
}
1139

    
1140
#if defined(__linux__)
1141
static uint64_t qemu_next_deadline_dyntick(void)
1142
{
1143
    int64_t delta;
1144
    int64_t rtdelta;
1145

    
1146
    if (use_icount)
1147
        delta = INT32_MAX;
1148
    else
1149
        delta = (qemu_next_deadline() + 999) / 1000;
1150

    
1151
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1152
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1153
                 qemu_get_clock(rt_clock))*1000;
1154
        if (rtdelta < delta)
1155
            delta = rtdelta;
1156
    }
1157

    
1158
    if (delta < MIN_TIMER_REARM_US)
1159
        delta = MIN_TIMER_REARM_US;
1160

    
1161
    return delta;
1162
}
1163
#endif
1164

    
1165
#ifndef _WIN32
1166

    
1167
/* Sets a specific flag */
1168
static int fcntl_setfl(int fd, int flag)
1169
{
1170
    int flags;
1171

    
1172
    flags = fcntl(fd, F_GETFL);
1173
    if (flags == -1)
1174
        return -errno;
1175

    
1176
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1177
        return -errno;
1178

    
1179
    return 0;
1180
}
1181

    
1182
#if defined(__linux__)
1183

    
1184
#define RTC_FREQ 1024
1185

    
1186
static void enable_sigio_timer(int fd)
1187
{
1188
    struct sigaction act;
1189

    
1190
    /* timer signal */
1191
    sigfillset(&act.sa_mask);
1192
    act.sa_flags = 0;
1193
    act.sa_handler = host_alarm_handler;
1194

    
1195
    sigaction(SIGIO, &act, NULL);
1196
    fcntl_setfl(fd, O_ASYNC);
1197
    fcntl(fd, F_SETOWN, getpid());
1198
}
1199

    
1200
static int hpet_start_timer(struct qemu_alarm_timer *t)
1201
{
1202
    struct hpet_info info;
1203
    int r, fd;
1204

    
1205
    fd = qemu_open("/dev/hpet", O_RDONLY);
1206
    if (fd < 0)
1207
        return -1;
1208

    
1209
    /* Set frequency */
1210
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1211
    if (r < 0) {
1212
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1213
                "error, but for better emulation accuracy type:\n"
1214
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1215
        goto fail;
1216
    }
1217

    
1218
    /* Check capabilities */
1219
    r = ioctl(fd, HPET_INFO, &info);
1220
    if (r < 0)
1221
        goto fail;
1222

    
1223
    /* Enable periodic mode */
1224
    r = ioctl(fd, HPET_EPI, 0);
1225
    if (info.hi_flags && (r < 0))
1226
        goto fail;
1227

    
1228
    /* Enable interrupt */
1229
    r = ioctl(fd, HPET_IE_ON, 0);
1230
    if (r < 0)
1231
        goto fail;
1232

    
1233
    enable_sigio_timer(fd);
1234
    t->priv = (void *)(long)fd;
1235

    
1236
    return 0;
1237
fail:
1238
    close(fd);
1239
    return -1;
1240
}
1241

    
1242
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1243
{
1244
    int fd = (long)t->priv;
1245

    
1246
    close(fd);
1247
}
1248

    
1249
static int rtc_start_timer(struct qemu_alarm_timer *t)
1250
{
1251
    int rtc_fd;
1252
    unsigned long current_rtc_freq = 0;
1253

    
1254
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1255
    if (rtc_fd < 0)
1256
        return -1;
1257
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1258
    if (current_rtc_freq != RTC_FREQ &&
1259
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1260
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1261
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1262
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1263
        goto fail;
1264
    }
1265
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1266
    fail:
1267
        close(rtc_fd);
1268
        return -1;
1269
    }
1270

    
1271
    enable_sigio_timer(rtc_fd);
1272

    
1273
    t->priv = (void *)(long)rtc_fd;
1274

    
1275
    return 0;
1276
}
1277

    
1278
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1279
{
1280
    int rtc_fd = (long)t->priv;
1281

    
1282
    close(rtc_fd);
1283
}
1284

    
1285
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1286
{
1287
    struct sigevent ev;
1288
    timer_t host_timer;
1289
    struct sigaction act;
1290

    
1291
    sigfillset(&act.sa_mask);
1292
    act.sa_flags = 0;
1293
    act.sa_handler = host_alarm_handler;
1294

    
1295
    sigaction(SIGALRM, &act, NULL);
1296

    
1297
    /* 
1298
     * Initialize ev struct to 0 to avoid valgrind complaining
1299
     * about uninitialized data in timer_create call
1300
     */
1301
    memset(&ev, 0, sizeof(ev));
1302
    ev.sigev_value.sival_int = 0;
1303
    ev.sigev_notify = SIGEV_SIGNAL;
1304
    ev.sigev_signo = SIGALRM;
1305

    
1306
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1307
        perror("timer_create");
1308

    
1309
        /* disable dynticks */
1310
        fprintf(stderr, "Dynamic Ticks disabled\n");
1311

    
1312
        return -1;
1313
    }
1314

    
1315
    t->priv = (void *)(long)host_timer;
1316

    
1317
    return 0;
1318
}
1319

    
1320
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1321
{
1322
    timer_t host_timer = (timer_t)(long)t->priv;
1323

    
1324
    timer_delete(host_timer);
1325
}
1326

    
1327
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1328
{
1329
    timer_t host_timer = (timer_t)(long)t->priv;
1330
    struct itimerspec timeout;
1331
    int64_t nearest_delta_us = INT64_MAX;
1332
    int64_t current_us;
1333

    
1334
    assert(alarm_has_dynticks(t));
1335
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1336
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1337
        !active_timers[QEMU_CLOCK_HOST])
1338
        return;
1339

    
1340
    nearest_delta_us = qemu_next_deadline_dyntick();
1341

    
1342
    /* check whether a timer is already running */
1343
    if (timer_gettime(host_timer, &timeout)) {
1344
        perror("gettime");
1345
        fprintf(stderr, "Internal timer error: aborting\n");
1346
        exit(1);
1347
    }
1348
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1349
    if (current_us && current_us <= nearest_delta_us)
1350
        return;
1351

    
1352
    timeout.it_interval.tv_sec = 0;
1353
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1354
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1355
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1356
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1357
        perror("settime");
1358
        fprintf(stderr, "Internal timer error: aborting\n");
1359
        exit(1);
1360
    }
1361
}
1362

    
1363
#endif /* defined(__linux__) */
1364

    
1365
static int unix_start_timer(struct qemu_alarm_timer *t)
1366
{
1367
    struct sigaction act;
1368
    struct itimerval itv;
1369
    int err;
1370

    
1371
    /* timer signal */
1372
    sigfillset(&act.sa_mask);
1373
    act.sa_flags = 0;
1374
    act.sa_handler = host_alarm_handler;
1375

    
1376
    sigaction(SIGALRM, &act, NULL);
1377

    
1378
    itv.it_interval.tv_sec = 0;
1379
    /* for i386 kernel 2.6 to get 1 ms */
1380
    itv.it_interval.tv_usec = 999;
1381
    itv.it_value.tv_sec = 0;
1382
    itv.it_value.tv_usec = 10 * 1000;
1383

    
1384
    err = setitimer(ITIMER_REAL, &itv, NULL);
1385
    if (err)
1386
        return -1;
1387

    
1388
    return 0;
1389
}
1390

    
1391
static void unix_stop_timer(struct qemu_alarm_timer *t)
1392
{
1393
    struct itimerval itv;
1394

    
1395
    memset(&itv, 0, sizeof(itv));
1396
    setitimer(ITIMER_REAL, &itv, NULL);
1397
}
1398

    
1399
#endif /* !defined(_WIN32) */
1400

    
1401

    
1402
#ifdef _WIN32
1403

    
1404
static int win32_start_timer(struct qemu_alarm_timer *t)
1405
{
1406
    TIMECAPS tc;
1407
    struct qemu_alarm_win32 *data = t->priv;
1408
    UINT flags;
1409

    
1410
    memset(&tc, 0, sizeof(tc));
1411
    timeGetDevCaps(&tc, sizeof(tc));
1412

    
1413
    data->period = tc.wPeriodMin;
1414
    timeBeginPeriod(data->period);
1415

    
1416
    flags = TIME_CALLBACK_FUNCTION;
1417
    if (alarm_has_dynticks(t))
1418
        flags |= TIME_ONESHOT;
1419
    else
1420
        flags |= TIME_PERIODIC;
1421

    
1422
    data->timerId = timeSetEvent(1,         // interval (ms)
1423
                        data->period,       // resolution
1424
                        host_alarm_handler, // function
1425
                        (DWORD)t,           // parameter
1426
                        flags);
1427

    
1428
    if (!data->timerId) {
1429
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1430
                GetLastError());
1431
        timeEndPeriod(data->period);
1432
        return -1;
1433
    }
1434

    
1435
    return 0;
1436
}
1437

    
1438
static void win32_stop_timer(struct qemu_alarm_timer *t)
1439
{
1440
    struct qemu_alarm_win32 *data = t->priv;
1441

    
1442
    timeKillEvent(data->timerId);
1443
    timeEndPeriod(data->period);
1444
}
1445

    
1446
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1447
{
1448
    struct qemu_alarm_win32 *data = t->priv;
1449

    
1450
    assert(alarm_has_dynticks(t));
1451
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1452
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1453
        !active_timers[QEMU_CLOCK_HOST])
1454
        return;
1455

    
1456
    timeKillEvent(data->timerId);
1457

    
1458
    data->timerId = timeSetEvent(1,
1459
                        data->period,
1460
                        host_alarm_handler,
1461
                        (DWORD)t,
1462
                        TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1463

    
1464
    if (!data->timerId) {
1465
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1466
                GetLastError());
1467

    
1468
        timeEndPeriod(data->period);
1469
        exit(1);
1470
    }
1471
}
1472

    
1473
#endif /* _WIN32 */
1474

    
1475
static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1476
{
1477
    if (running)
1478
        qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1479
}
1480

    
1481
static int init_timer_alarm(void)
1482
{
1483
    struct qemu_alarm_timer *t = NULL;
1484
    int i, err = -1;
1485

    
1486
    for (i = 0; alarm_timers[i].name; i++) {
1487
        t = &alarm_timers[i];
1488

    
1489
        err = t->start(t);
1490
        if (!err)
1491
            break;
1492
    }
1493

    
1494
    if (err) {
1495
        err = -ENOENT;
1496
        goto fail;
1497
    }
1498

    
1499
    /* first event is at time 0 */
1500
    t->pending = 1;
1501
    alarm_timer = t;
1502
    qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1503

    
1504
    return 0;
1505

    
1506
fail:
1507
    return err;
1508
}
1509

    
1510
static void quit_timers(void)
1511
{
1512
    struct qemu_alarm_timer *t = alarm_timer;
1513
    alarm_timer = NULL;
1514
    t->stop(t);
1515
}
1516

    
1517
/***********************************************************/
1518
/* host time/date access */
1519
void qemu_get_timedate(struct tm *tm, int offset)
1520
{
1521
    time_t ti;
1522
    struct tm *ret;
1523

    
1524
    time(&ti);
1525
    ti += offset;
1526
    if (rtc_date_offset == -1) {
1527
        if (rtc_utc)
1528
            ret = gmtime(&ti);
1529
        else
1530
            ret = localtime(&ti);
1531
    } else {
1532
        ti -= rtc_date_offset;
1533
        ret = gmtime(&ti);
1534
    }
1535

    
1536
    memcpy(tm, ret, sizeof(struct tm));
1537
}
1538

    
1539
int qemu_timedate_diff(struct tm *tm)
1540
{
1541
    time_t seconds;
1542

    
1543
    if (rtc_date_offset == -1)
1544
        if (rtc_utc)
1545
            seconds = mktimegm(tm);
1546
        else
1547
            seconds = mktime(tm);
1548
    else
1549
        seconds = mktimegm(tm) + rtc_date_offset;
1550

    
1551
    return seconds - time(NULL);
1552
}
1553

    
1554
void rtc_change_mon_event(struct tm *tm)
1555
{
1556
    QObject *data;
1557

    
1558
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1559
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1560
    qobject_decref(data);
1561
}
1562

    
1563
static void configure_rtc_date_offset(const char *startdate, int legacy)
1564
{
1565
    time_t rtc_start_date;
1566
    struct tm tm;
1567

    
1568
    if (!strcmp(startdate, "now") && legacy) {
1569
        rtc_date_offset = -1;
1570
    } else {
1571
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1572
                   &tm.tm_year,
1573
                   &tm.tm_mon,
1574
                   &tm.tm_mday,
1575
                   &tm.tm_hour,
1576
                   &tm.tm_min,
1577
                   &tm.tm_sec) == 6) {
1578
            /* OK */
1579
        } else if (sscanf(startdate, "%d-%d-%d",
1580
                          &tm.tm_year,
1581
                          &tm.tm_mon,
1582
                          &tm.tm_mday) == 3) {
1583
            tm.tm_hour = 0;
1584
            tm.tm_min = 0;
1585
            tm.tm_sec = 0;
1586
        } else {
1587
            goto date_fail;
1588
        }
1589
        tm.tm_year -= 1900;
1590
        tm.tm_mon--;
1591
        rtc_start_date = mktimegm(&tm);
1592
        if (rtc_start_date == -1) {
1593
        date_fail:
1594
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1595
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1596
            exit(1);
1597
        }
1598
        rtc_date_offset = time(NULL) - rtc_start_date;
1599
    }
1600
}
1601

    
1602
static void configure_rtc(QemuOpts *opts)
1603
{
1604
    const char *value;
1605

    
1606
    value = qemu_opt_get(opts, "base");
1607
    if (value) {
1608
        if (!strcmp(value, "utc")) {
1609
            rtc_utc = 1;
1610
        } else if (!strcmp(value, "localtime")) {
1611
            rtc_utc = 0;
1612
        } else {
1613
            configure_rtc_date_offset(value, 0);
1614
        }
1615
    }
1616
    value = qemu_opt_get(opts, "clock");
1617
    if (value) {
1618
        if (!strcmp(value, "host")) {
1619
            rtc_clock = host_clock;
1620
        } else if (!strcmp(value, "vm")) {
1621
            rtc_clock = vm_clock;
1622
        } else {
1623
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1624
            exit(1);
1625
        }
1626
    }
1627
#ifdef CONFIG_TARGET_I386
1628
    value = qemu_opt_get(opts, "driftfix");
1629
    if (value) {
1630
        if (!strcmp(buf, "slew")) {
1631
            rtc_td_hack = 1;
1632
        } else if (!strcmp(buf, "none")) {
1633
            rtc_td_hack = 0;
1634
        } else {
1635
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1636
            exit(1);
1637
        }
1638
    }
1639
#endif
1640
}
1641

    
1642
#ifdef _WIN32
1643
static void socket_cleanup(void)
1644
{
1645
    WSACleanup();
1646
}
1647

    
1648
static int socket_init(void)
1649
{
1650
    WSADATA Data;
1651
    int ret, err;
1652

    
1653
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1654
    if (ret != 0) {
1655
        err = WSAGetLastError();
1656
        fprintf(stderr, "WSAStartup: %d\n", err);
1657
        return -1;
1658
    }
1659
    atexit(socket_cleanup);
1660
    return 0;
1661
}
1662
#endif
1663

    
1664
/***********************************************************/
1665
/* Bluetooth support */
1666
static int nb_hcis;
1667
static int cur_hci;
1668
static struct HCIInfo *hci_table[MAX_NICS];
1669

    
1670
static struct bt_vlan_s {
1671
    struct bt_scatternet_s net;
1672
    int id;
1673
    struct bt_vlan_s *next;
1674
} *first_bt_vlan;
1675

    
1676
/* find or alloc a new bluetooth "VLAN" */
1677
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1678
{
1679
    struct bt_vlan_s **pvlan, *vlan;
1680
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1681
        if (vlan->id == id)
1682
            return &vlan->net;
1683
    }
1684
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1685
    vlan->id = id;
1686
    pvlan = &first_bt_vlan;
1687
    while (*pvlan != NULL)
1688
        pvlan = &(*pvlan)->next;
1689
    *pvlan = vlan;
1690
    return &vlan->net;
1691
}
1692

    
1693
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1694
{
1695
}
1696

    
1697
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1698
{
1699
    return -ENOTSUP;
1700
}
1701

    
1702
static struct HCIInfo null_hci = {
1703
    .cmd_send = null_hci_send,
1704
    .sco_send = null_hci_send,
1705
    .acl_send = null_hci_send,
1706
    .bdaddr_set = null_hci_addr_set,
1707
};
1708

    
1709
struct HCIInfo *qemu_next_hci(void)
1710
{
1711
    if (cur_hci == nb_hcis)
1712
        return &null_hci;
1713

    
1714
    return hci_table[cur_hci++];
1715
}
1716

    
1717
static struct HCIInfo *hci_init(const char *str)
1718
{
1719
    char *endp;
1720
    struct bt_scatternet_s *vlan = 0;
1721

    
1722
    if (!strcmp(str, "null"))
1723
        /* null */
1724
        return &null_hci;
1725
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1726
        /* host[:hciN] */
1727
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1728
    else if (!strncmp(str, "hci", 3)) {
1729
        /* hci[,vlan=n] */
1730
        if (str[3]) {
1731
            if (!strncmp(str + 3, ",vlan=", 6)) {
1732
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1733
                if (*endp)
1734
                    vlan = 0;
1735
            }
1736
        } else
1737
            vlan = qemu_find_bt_vlan(0);
1738
        if (vlan)
1739
           return bt_new_hci(vlan);
1740
    }
1741

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

    
1744
    return 0;
1745
}
1746

    
1747
static int bt_hci_parse(const char *str)
1748
{
1749
    struct HCIInfo *hci;
1750
    bdaddr_t bdaddr;
1751

    
1752
    if (nb_hcis >= MAX_NICS) {
1753
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1754
        return -1;
1755
    }
1756

    
1757
    hci = hci_init(str);
1758
    if (!hci)
1759
        return -1;
1760

    
1761
    bdaddr.b[0] = 0x52;
1762
    bdaddr.b[1] = 0x54;
1763
    bdaddr.b[2] = 0x00;
1764
    bdaddr.b[3] = 0x12;
1765
    bdaddr.b[4] = 0x34;
1766
    bdaddr.b[5] = 0x56 + nb_hcis;
1767
    hci->bdaddr_set(hci, bdaddr.b);
1768

    
1769
    hci_table[nb_hcis++] = hci;
1770

    
1771
    return 0;
1772
}
1773

    
1774
static void bt_vhci_add(int vlan_id)
1775
{
1776
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1777

    
1778
    if (!vlan->slave)
1779
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1780
                        "an empty scatternet %i\n", vlan_id);
1781

    
1782
    bt_vhci_init(bt_new_hci(vlan));
1783
}
1784

    
1785
static struct bt_device_s *bt_device_add(const char *opt)
1786
{
1787
    struct bt_scatternet_s *vlan;
1788
    int vlan_id = 0;
1789
    char *endp = strstr(opt, ",vlan=");
1790
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1791
    char devname[10];
1792

    
1793
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1794

    
1795
    if (endp) {
1796
        vlan_id = strtol(endp + 6, &endp, 0);
1797
        if (*endp) {
1798
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1799
            return 0;
1800
        }
1801
    }
1802

    
1803
    vlan = qemu_find_bt_vlan(vlan_id);
1804

    
1805
    if (!vlan->slave)
1806
        fprintf(stderr, "qemu: warning: adding a slave device to "
1807
                        "an empty scatternet %i\n", vlan_id);
1808

    
1809
    if (!strcmp(devname, "keyboard"))
1810
        return bt_keyboard_init(vlan);
1811

    
1812
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1813
    return 0;
1814
}
1815

    
1816
static int bt_parse(const char *opt)
1817
{
1818
    const char *endp, *p;
1819
    int vlan;
1820

    
1821
    if (strstart(opt, "hci", &endp)) {
1822
        if (!*endp || *endp == ',') {
1823
            if (*endp)
1824
                if (!strstart(endp, ",vlan=", 0))
1825
                    opt = endp + 1;
1826

    
1827
            return bt_hci_parse(opt);
1828
       }
1829
    } else if (strstart(opt, "vhci", &endp)) {
1830
        if (!*endp || *endp == ',') {
1831
            if (*endp) {
1832
                if (strstart(endp, ",vlan=", &p)) {
1833
                    vlan = strtol(p, (char **) &endp, 0);
1834
                    if (*endp) {
1835
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1836
                        return 1;
1837
                    }
1838
                } else {
1839
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1840
                    return 1;
1841
                }
1842
            } else
1843
                vlan = 0;
1844

    
1845
            bt_vhci_add(vlan);
1846
            return 0;
1847
        }
1848
    } else if (strstart(opt, "device:", &endp))
1849
        return !bt_device_add(endp);
1850

    
1851
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1852
    return 1;
1853
}
1854

    
1855
/***********************************************************/
1856
/* QEMU Block devices */
1857

    
1858
#define HD_ALIAS "index=%d,media=disk"
1859
#define CDROM_ALIAS "index=2,media=cdrom"
1860
#define FD_ALIAS "index=%d,if=floppy"
1861
#define PFLASH_ALIAS "if=pflash"
1862
#define MTD_ALIAS "if=mtd"
1863
#define SD_ALIAS "index=0,if=sd"
1864

    
1865
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1866
{
1867
    va_list ap;
1868
    char optstr[1024];
1869
    QemuOpts *opts;
1870

    
1871
    va_start(ap, fmt);
1872
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1873
    va_end(ap);
1874

    
1875
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
1876
    if (!opts) {
1877
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1878
                __FUNCTION__, optstr);
1879
        return NULL;
1880
    }
1881
    if (file)
1882
        qemu_opt_set(opts, "file", file);
1883
    return opts;
1884
}
1885

    
1886
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1887
{
1888
    DriveInfo *dinfo;
1889

    
1890
    /* seek interface, bus and unit */
1891

    
1892
    QTAILQ_FOREACH(dinfo, &drives, next) {
1893
        if (dinfo->type == type &&
1894
            dinfo->bus == bus &&
1895
            dinfo->unit == unit)
1896
            return dinfo;
1897
    }
1898

    
1899
    return NULL;
1900
}
1901

    
1902
DriveInfo *drive_get_by_id(const char *id)
1903
{
1904
    DriveInfo *dinfo;
1905

    
1906
    QTAILQ_FOREACH(dinfo, &drives, next) {
1907
        if (strcmp(id, dinfo->id))
1908
            continue;
1909
        return dinfo;
1910
    }
1911
    return NULL;
1912
}
1913

    
1914
int drive_get_max_bus(BlockInterfaceType type)
1915
{
1916
    int max_bus;
1917
    DriveInfo *dinfo;
1918

    
1919
    max_bus = -1;
1920
    QTAILQ_FOREACH(dinfo, &drives, next) {
1921
        if(dinfo->type == type &&
1922
           dinfo->bus > max_bus)
1923
            max_bus = dinfo->bus;
1924
    }
1925
    return max_bus;
1926
}
1927

    
1928
const char *drive_get_serial(BlockDriverState *bdrv)
1929
{
1930
    DriveInfo *dinfo;
1931

    
1932
    QTAILQ_FOREACH(dinfo, &drives, next) {
1933
        if (dinfo->bdrv == bdrv)
1934
            return dinfo->serial;
1935
    }
1936

    
1937
    return "\0";
1938
}
1939

    
1940
BlockInterfaceErrorAction drive_get_on_error(
1941
    BlockDriverState *bdrv, int is_read)
1942
{
1943
    DriveInfo *dinfo;
1944

    
1945
    QTAILQ_FOREACH(dinfo, &drives, next) {
1946
        if (dinfo->bdrv == bdrv)
1947
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1948
    }
1949

    
1950
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1951
}
1952

    
1953
static void bdrv_format_print(void *opaque, const char *name)
1954
{
1955
    fprintf(stderr, " %s", name);
1956
}
1957

    
1958
void drive_uninit(DriveInfo *dinfo)
1959
{
1960
    qemu_opts_del(dinfo->opts);
1961
    bdrv_delete(dinfo->bdrv);
1962
    QTAILQ_REMOVE(&drives, dinfo, next);
1963
    qemu_free(dinfo);
1964
}
1965

    
1966
static int parse_block_error_action(const char *buf, int is_read)
1967
{
1968
    if (!strcmp(buf, "ignore")) {
1969
        return BLOCK_ERR_IGNORE;
1970
    } else if (!is_read && !strcmp(buf, "enospc")) {
1971
        return BLOCK_ERR_STOP_ENOSPC;
1972
    } else if (!strcmp(buf, "stop")) {
1973
        return BLOCK_ERR_STOP_ANY;
1974
    } else if (!strcmp(buf, "report")) {
1975
        return BLOCK_ERR_REPORT;
1976
    } else {
1977
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1978
            buf, is_read ? "read" : "write");
1979
        return -1;
1980
    }
1981
}
1982

    
1983
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1984
                      int *fatal_error)
1985
{
1986
    const char *buf;
1987
    const char *file = NULL;
1988
    char devname[128];
1989
    const char *serial;
1990
    const char *mediastr = "";
1991
    BlockInterfaceType type;
1992
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1993
    int bus_id, unit_id;
1994
    int cyls, heads, secs, translation;
1995
    BlockDriver *drv = NULL;
1996
    QEMUMachine *machine = opaque;
1997
    int max_devs;
1998
    int index;
1999
    int cache;
2000
    int aio = 0;
2001
    int ro = 0;
2002
    int bdrv_flags;
2003
    int on_read_error, on_write_error;
2004
    const char *devaddr;
2005
    DriveInfo *dinfo;
2006
    int snapshot = 0;
2007

    
2008
    *fatal_error = 1;
2009

    
2010
    translation = BIOS_ATA_TRANSLATION_AUTO;
2011
    cache = 1;
2012

    
2013
    if (machine && machine->use_scsi) {
2014
        type = IF_SCSI;
2015
        max_devs = MAX_SCSI_DEVS;
2016
        pstrcpy(devname, sizeof(devname), "scsi");
2017
    } else {
2018
        type = IF_IDE;
2019
        max_devs = MAX_IDE_DEVS;
2020
        pstrcpy(devname, sizeof(devname), "ide");
2021
    }
2022
    media = MEDIA_DISK;
2023

    
2024
    /* extract parameters */
2025
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
2026
    unit_id = qemu_opt_get_number(opts, "unit", -1);
2027
    index   = qemu_opt_get_number(opts, "index", -1);
2028

    
2029
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
2030
    heads = qemu_opt_get_number(opts, "heads", 0);
2031
    secs  = qemu_opt_get_number(opts, "secs", 0);
2032

    
2033
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2034
    ro = qemu_opt_get_bool(opts, "readonly", 0);
2035

    
2036
    file = qemu_opt_get(opts, "file");
2037
    serial = qemu_opt_get(opts, "serial");
2038

    
2039
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2040
        pstrcpy(devname, sizeof(devname), buf);
2041
        if (!strcmp(buf, "ide")) {
2042
            type = IF_IDE;
2043
            max_devs = MAX_IDE_DEVS;
2044
        } else if (!strcmp(buf, "scsi")) {
2045
            type = IF_SCSI;
2046
            max_devs = MAX_SCSI_DEVS;
2047
        } else if (!strcmp(buf, "floppy")) {
2048
            type = IF_FLOPPY;
2049
            max_devs = 0;
2050
        } else if (!strcmp(buf, "pflash")) {
2051
            type = IF_PFLASH;
2052
            max_devs = 0;
2053
        } else if (!strcmp(buf, "mtd")) {
2054
            type = IF_MTD;
2055
            max_devs = 0;
2056
        } else if (!strcmp(buf, "sd")) {
2057
            type = IF_SD;
2058
            max_devs = 0;
2059
        } else if (!strcmp(buf, "virtio")) {
2060
            type = IF_VIRTIO;
2061
            max_devs = 0;
2062
        } else if (!strcmp(buf, "xen")) {
2063
            type = IF_XEN;
2064
            max_devs = 0;
2065
        } else if (!strcmp(buf, "none")) {
2066
            type = IF_NONE;
2067
            max_devs = 0;
2068
        } else {
2069
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2070
            return NULL;
2071
        }
2072
    }
2073

    
2074
    if (cyls || heads || secs) {
2075
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2076
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2077
            return NULL;
2078
        }
2079
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
2080
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2081
            return NULL;
2082
        }
2083
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
2084
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2085
            return NULL;
2086
        }
2087
    }
2088

    
2089
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2090
        if (!cyls) {
2091
            fprintf(stderr,
2092
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2093
                    buf);
2094
            return NULL;
2095
        }
2096
        if (!strcmp(buf, "none"))
2097
            translation = BIOS_ATA_TRANSLATION_NONE;
2098
        else if (!strcmp(buf, "lba"))
2099
            translation = BIOS_ATA_TRANSLATION_LBA;
2100
        else if (!strcmp(buf, "auto"))
2101
            translation = BIOS_ATA_TRANSLATION_AUTO;
2102
        else {
2103
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2104
            return NULL;
2105
        }
2106
    }
2107

    
2108
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2109
        if (!strcmp(buf, "disk")) {
2110
            media = MEDIA_DISK;
2111
        } else if (!strcmp(buf, "cdrom")) {
2112
            if (cyls || secs || heads) {
2113
                fprintf(stderr,
2114
                        "qemu: '%s' invalid physical CHS format\n", buf);
2115
                return NULL;
2116
            }
2117
            media = MEDIA_CDROM;
2118
        } else {
2119
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2120
            return NULL;
2121
        }
2122
    }
2123

    
2124
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2125
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2126
            cache = 0;
2127
        else if (!strcmp(buf, "writethrough"))
2128
            cache = 1;
2129
        else if (!strcmp(buf, "writeback"))
2130
            cache = 2;
2131
        else {
2132
           fprintf(stderr, "qemu: invalid cache option\n");
2133
           return NULL;
2134
        }
2135
    }
2136

    
2137
#ifdef CONFIG_LINUX_AIO
2138
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2139
        if (!strcmp(buf, "threads"))
2140
            aio = 0;
2141
        else if (!strcmp(buf, "native"))
2142
            aio = 1;
2143
        else {
2144
           fprintf(stderr, "qemu: invalid aio option\n");
2145
           return NULL;
2146
        }
2147
    }
2148
#endif
2149

    
2150
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2151
       if (strcmp(buf, "?") == 0) {
2152
            fprintf(stderr, "qemu: Supported formats:");
2153
            bdrv_iterate_format(bdrv_format_print, NULL);
2154
            fprintf(stderr, "\n");
2155
            return NULL;
2156
        }
2157
        drv = bdrv_find_whitelisted_format(buf);
2158
        if (!drv) {
2159
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2160
            return NULL;
2161
        }
2162
    }
2163

    
2164
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2165
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2166
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2167
            fprintf(stderr, "werror is no supported by this format\n");
2168
            return NULL;
2169
        }
2170

    
2171
        on_write_error = parse_block_error_action(buf, 0);
2172
        if (on_write_error < 0) {
2173
            return NULL;
2174
        }
2175
    }
2176

    
2177
    on_read_error = BLOCK_ERR_REPORT;
2178
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2179
        if (type != IF_IDE && type != IF_VIRTIO) {
2180
            fprintf(stderr, "rerror is no supported by this format\n");
2181
            return NULL;
2182
        }
2183

    
2184
        on_read_error = parse_block_error_action(buf, 1);
2185
        if (on_read_error < 0) {
2186
            return NULL;
2187
        }
2188
    }
2189

    
2190
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2191
        if (type != IF_VIRTIO) {
2192
            fprintf(stderr, "addr is not supported\n");
2193
            return NULL;
2194
        }
2195
    }
2196

    
2197
    /* compute bus and unit according index */
2198

    
2199
    if (index != -1) {
2200
        if (bus_id != 0 || unit_id != -1) {
2201
            fprintf(stderr,
2202
                    "qemu: index cannot be used with bus and unit\n");
2203
            return NULL;
2204
        }
2205
        if (max_devs == 0)
2206
        {
2207
            unit_id = index;
2208
            bus_id = 0;
2209
        } else {
2210
            unit_id = index % max_devs;
2211
            bus_id = index / max_devs;
2212
        }
2213
    }
2214

    
2215
    /* if user doesn't specify a unit_id,
2216
     * try to find the first free
2217
     */
2218

    
2219
    if (unit_id == -1) {
2220
       unit_id = 0;
2221
       while (drive_get(type, bus_id, unit_id) != NULL) {
2222
           unit_id++;
2223
           if (max_devs && unit_id >= max_devs) {
2224
               unit_id -= max_devs;
2225
               bus_id++;
2226
           }
2227
       }
2228
    }
2229

    
2230
    /* check unit id */
2231

    
2232
    if (max_devs && unit_id >= max_devs) {
2233
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2234
                unit_id, max_devs - 1);
2235
        return NULL;
2236
    }
2237

    
2238
    /*
2239
     * ignore multiple definitions
2240
     */
2241

    
2242
    if (drive_get(type, bus_id, unit_id) != NULL) {
2243
        *fatal_error = 0;
2244
        return NULL;
2245
    }
2246

    
2247
    /* init */
2248

    
2249
    dinfo = qemu_mallocz(sizeof(*dinfo));
2250
    if ((buf = qemu_opts_id(opts)) != NULL) {
2251
        dinfo->id = qemu_strdup(buf);
2252
    } else {
2253
        /* no id supplied -> create one */
2254
        dinfo->id = qemu_mallocz(32);
2255
        if (type == IF_IDE || type == IF_SCSI)
2256
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2257
        if (max_devs)
2258
            snprintf(dinfo->id, 32, "%s%i%s%i",
2259
                     devname, bus_id, mediastr, unit_id);
2260
        else
2261
            snprintf(dinfo->id, 32, "%s%s%i",
2262
                     devname, mediastr, unit_id);
2263
    }
2264
    dinfo->bdrv = bdrv_new(dinfo->id);
2265
    dinfo->devaddr = devaddr;
2266
    dinfo->type = type;
2267
    dinfo->bus = bus_id;
2268
    dinfo->unit = unit_id;
2269
    dinfo->on_read_error = on_read_error;
2270
    dinfo->on_write_error = on_write_error;
2271
    dinfo->opts = opts;
2272
    if (serial)
2273
        strncpy(dinfo->serial, serial, sizeof(serial));
2274
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2275

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

    
2327
    if (aio == 1) {
2328
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2329
    } else {
2330
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2331
    }
2332

    
2333
    if (ro == 1) {
2334
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2335
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2336
            return NULL;
2337
        }
2338
    }
2339
    /* 
2340
     * cdrom is read-only. Set it now, after above interface checking
2341
     * since readonly attribute not explicitly required, so no error.
2342
     */
2343
    if (media == MEDIA_CDROM) {
2344
        ro = 1;
2345
    }
2346
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2347

    
2348
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2349
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2350
                        file, strerror(errno));
2351
        return NULL;
2352
    }
2353

    
2354
    if (bdrv_key_required(dinfo->bdrv))
2355
        autostart = 0;
2356
    *fatal_error = 0;
2357
    return dinfo;
2358
}
2359

    
2360
static int drive_init_func(QemuOpts *opts, void *opaque)
2361
{
2362
    QEMUMachine *machine = opaque;
2363
    int fatal_error = 0;
2364

    
2365
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2366
        if (fatal_error)
2367
            return 1;
2368
    }
2369
    return 0;
2370
}
2371

    
2372
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2373
{
2374
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2375
        qemu_opt_set(opts, "snapshot", "on");
2376
    }
2377
    return 0;
2378
}
2379

    
2380
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2381
{
2382
    boot_set_handler = func;
2383
    boot_set_opaque = opaque;
2384
}
2385

    
2386
int qemu_boot_set(const char *boot_devices)
2387
{
2388
    if (!boot_set_handler) {
2389
        return -EINVAL;
2390
    }
2391
    return boot_set_handler(boot_set_opaque, boot_devices);
2392
}
2393

    
2394
static int parse_bootdevices(char *devices)
2395
{
2396
    /* We just do some generic consistency checks */
2397
    const char *p;
2398
    int bitmap = 0;
2399

    
2400
    for (p = devices; *p != '\0'; p++) {
2401
        /* Allowed boot devices are:
2402
         * a-b: floppy disk drives
2403
         * c-f: IDE disk drives
2404
         * g-m: machine implementation dependant drives
2405
         * n-p: network devices
2406
         * It's up to each machine implementation to check if the given boot
2407
         * devices match the actual hardware implementation and firmware
2408
         * features.
2409
         */
2410
        if (*p < 'a' || *p > 'p') {
2411
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2412
            exit(1);
2413
        }
2414
        if (bitmap & (1 << (*p - 'a'))) {
2415
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2416
            exit(1);
2417
        }
2418
        bitmap |= 1 << (*p - 'a');
2419
    }
2420
    return bitmap;
2421
}
2422

    
2423
static void restore_boot_devices(void *opaque)
2424
{
2425
    char *standard_boot_devices = opaque;
2426

    
2427
    qemu_boot_set(standard_boot_devices);
2428

    
2429
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2430
    qemu_free(standard_boot_devices);
2431
}
2432

    
2433
static void numa_add(const char *optarg)
2434
{
2435
    char option[128];
2436
    char *endptr;
2437
    unsigned long long value, endvalue;
2438
    int nodenr;
2439

    
2440
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2441
    if (!strcmp(option, "node")) {
2442
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2443
            nodenr = nb_numa_nodes;
2444
        } else {
2445
            nodenr = strtoull(option, NULL, 10);
2446
        }
2447

    
2448
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2449
            node_mem[nodenr] = 0;
2450
        } else {
2451
            value = strtoull(option, &endptr, 0);
2452
            switch (*endptr) {
2453
            case 0: case 'M': case 'm':
2454
                value <<= 20;
2455
                break;
2456
            case 'G': case 'g':
2457
                value <<= 30;
2458
                break;
2459
            }
2460
            node_mem[nodenr] = value;
2461
        }
2462
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2463
            node_cpumask[nodenr] = 0;
2464
        } else {
2465
            value = strtoull(option, &endptr, 10);
2466
            if (value >= 64) {
2467
                value = 63;
2468
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2469
            } else {
2470
                if (*endptr == '-') {
2471
                    endvalue = strtoull(endptr+1, &endptr, 10);
2472
                    if (endvalue >= 63) {
2473
                        endvalue = 62;
2474
                        fprintf(stderr,
2475
                            "only 63 CPUs in NUMA mode supported.\n");
2476
                    }
2477
                    value = (2ULL << endvalue) - (1ULL << value);
2478
                } else {
2479
                    value = 1ULL << value;
2480
                }
2481
            }
2482
            node_cpumask[nodenr] = value;
2483
        }
2484
        nb_numa_nodes++;
2485
    }
2486
    return;
2487
}
2488

    
2489
static void smp_parse(const char *optarg)
2490
{
2491
    int smp, sockets = 0, threads = 0, cores = 0;
2492
    char *endptr;
2493
    char option[128];
2494

    
2495
    smp = strtoul(optarg, &endptr, 10);
2496
    if (endptr != optarg) {
2497
        if (*endptr == ',') {
2498
            endptr++;
2499
        }
2500
    }
2501
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2502
        sockets = strtoull(option, NULL, 10);
2503
    if (get_param_value(option, 128, "cores", endptr) != 0)
2504
        cores = strtoull(option, NULL, 10);
2505
    if (get_param_value(option, 128, "threads", endptr) != 0)
2506
        threads = strtoull(option, NULL, 10);
2507
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2508
        max_cpus = strtoull(option, NULL, 10);
2509

    
2510
    /* compute missing values, prefer sockets over cores over threads */
2511
    if (smp == 0 || sockets == 0) {
2512
        sockets = sockets > 0 ? sockets : 1;
2513
        cores = cores > 0 ? cores : 1;
2514
        threads = threads > 0 ? threads : 1;
2515
        if (smp == 0) {
2516
            smp = cores * threads * sockets;
2517
        }
2518
    } else {
2519
        if (cores == 0) {
2520
            threads = threads > 0 ? threads : 1;
2521
            cores = smp / (sockets * threads);
2522
        } else {
2523
            if (sockets) {
2524
                threads = smp / (cores * sockets);
2525
            }
2526
        }
2527
    }
2528
    smp_cpus = smp;
2529
    smp_cores = cores > 0 ? cores : 1;
2530
    smp_threads = threads > 0 ? threads : 1;
2531
    if (max_cpus == 0)
2532
        max_cpus = smp_cpus;
2533
}
2534

    
2535
/***********************************************************/
2536
/* USB devices */
2537

    
2538
static int usb_device_add(const char *devname, int is_hotplug)
2539
{
2540
    const char *p;
2541
    USBDevice *dev = NULL;
2542

    
2543
    if (!usb_enabled)
2544
        return -1;
2545

    
2546
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2547
    dev = usbdevice_create(devname);
2548
    if (dev)
2549
        goto done;
2550

    
2551
    /* the other ones */
2552
    if (strstart(devname, "host:", &p)) {
2553
        dev = usb_host_device_open(p);
2554
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2555
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2556
                        bt_new_hci(qemu_find_bt_vlan(0)));
2557
    } else {
2558
        return -1;
2559
    }
2560
    if (!dev)
2561
        return -1;
2562

    
2563
done:
2564
    return 0;
2565
}
2566

    
2567
static int usb_device_del(const char *devname)
2568
{
2569
    int bus_num, addr;
2570
    const char *p;
2571

    
2572
    if (strstart(devname, "host:", &p))
2573
        return usb_host_device_close(p);
2574

    
2575
    if (!usb_enabled)
2576
        return -1;
2577

    
2578
    p = strchr(devname, '.');
2579
    if (!p)
2580
        return -1;
2581
    bus_num = strtoul(devname, NULL, 0);
2582
    addr = strtoul(p + 1, NULL, 0);
2583

    
2584
    return usb_device_delete_addr(bus_num, addr);
2585
}
2586

    
2587
static int usb_parse(const char *cmdline)
2588
{
2589
    int r;
2590
    r = usb_device_add(cmdline, 0);
2591
    if (r < 0) {
2592
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2593
    }
2594
    return r;
2595
}
2596

    
2597
void do_usb_add(Monitor *mon, const QDict *qdict)
2598
{
2599
    const char *devname = qdict_get_str(qdict, "devname");
2600
    if (usb_device_add(devname, 1) < 0) {
2601
        error_report("could not add USB device '%s'", devname);
2602
    }
2603
}
2604

    
2605
void do_usb_del(Monitor *mon, const QDict *qdict)
2606
{
2607
    const char *devname = qdict_get_str(qdict, "devname");
2608
    if (usb_device_del(devname) < 0) {
2609
        error_report("could not delete USB device '%s'", devname);
2610
    }
2611
}
2612

    
2613
/***********************************************************/
2614
/* PCMCIA/Cardbus */
2615

    
2616
static struct pcmcia_socket_entry_s {
2617
    PCMCIASocket *socket;
2618
    struct pcmcia_socket_entry_s *next;
2619
} *pcmcia_sockets = 0;
2620

    
2621
void pcmcia_socket_register(PCMCIASocket *socket)
2622
{
2623
    struct pcmcia_socket_entry_s *entry;
2624

    
2625
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2626
    entry->socket = socket;
2627
    entry->next = pcmcia_sockets;
2628
    pcmcia_sockets = entry;
2629
}
2630

    
2631
void pcmcia_socket_unregister(PCMCIASocket *socket)
2632
{
2633
    struct pcmcia_socket_entry_s *entry, **ptr;
2634

    
2635
    ptr = &pcmcia_sockets;
2636
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2637
        if (entry->socket == socket) {
2638
            *ptr = entry->next;
2639
            qemu_free(entry);
2640
        }
2641
}
2642

    
2643
void pcmcia_info(Monitor *mon)
2644
{
2645
    struct pcmcia_socket_entry_s *iter;
2646

    
2647
    if (!pcmcia_sockets)
2648
        monitor_printf(mon, "No PCMCIA sockets\n");
2649

    
2650
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2651
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2652
                       iter->socket->attached ? iter->socket->card_string :
2653
                       "Empty");
2654
}
2655

    
2656
/***********************************************************/
2657
/* I/O handling */
2658

    
2659
typedef struct IOHandlerRecord {
2660
    int fd;
2661
    IOCanRWHandler *fd_read_poll;
2662
    IOHandler *fd_read;
2663
    IOHandler *fd_write;
2664
    int deleted;
2665
    void *opaque;
2666
    /* temporary data */
2667
    struct pollfd *ufd;
2668
    struct IOHandlerRecord *next;
2669
} IOHandlerRecord;
2670

    
2671
static IOHandlerRecord *first_io_handler;
2672

    
2673
/* XXX: fd_read_poll should be suppressed, but an API change is
2674
   necessary in the character devices to suppress fd_can_read(). */
2675
int qemu_set_fd_handler2(int fd,
2676
                         IOCanRWHandler *fd_read_poll,
2677
                         IOHandler *fd_read,
2678
                         IOHandler *fd_write,
2679
                         void *opaque)
2680
{
2681
    IOHandlerRecord **pioh, *ioh;
2682

    
2683
    if (!fd_read && !fd_write) {
2684
        pioh = &first_io_handler;
2685
        for(;;) {
2686
            ioh = *pioh;
2687
            if (ioh == NULL)
2688
                break;
2689
            if (ioh->fd == fd) {
2690
                ioh->deleted = 1;
2691
                break;
2692
            }
2693
            pioh = &ioh->next;
2694
        }
2695
    } else {
2696
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2697
            if (ioh->fd == fd)
2698
                goto found;
2699
        }
2700
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2701
        ioh->next = first_io_handler;
2702
        first_io_handler = ioh;
2703
    found:
2704
        ioh->fd = fd;
2705
        ioh->fd_read_poll = fd_read_poll;
2706
        ioh->fd_read = fd_read;
2707
        ioh->fd_write = fd_write;
2708
        ioh->opaque = opaque;
2709
        ioh->deleted = 0;
2710
    }
2711
    return 0;
2712
}
2713

    
2714
int qemu_set_fd_handler(int fd,
2715
                        IOHandler *fd_read,
2716
                        IOHandler *fd_write,
2717
                        void *opaque)
2718
{
2719
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2720
}
2721

    
2722
#ifdef _WIN32
2723
/***********************************************************/
2724
/* Polling handling */
2725

    
2726
typedef struct PollingEntry {
2727
    PollingFunc *func;
2728
    void *opaque;
2729
    struct PollingEntry *next;
2730
} PollingEntry;
2731

    
2732
static PollingEntry *first_polling_entry;
2733

    
2734
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2735
{
2736
    PollingEntry **ppe, *pe;
2737
    pe = qemu_mallocz(sizeof(PollingEntry));
2738
    pe->func = func;
2739
    pe->opaque = opaque;
2740
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2741
    *ppe = pe;
2742
    return 0;
2743
}
2744

    
2745
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2746
{
2747
    PollingEntry **ppe, *pe;
2748
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2749
        pe = *ppe;
2750
        if (pe->func == func && pe->opaque == opaque) {
2751
            *ppe = pe->next;
2752
            qemu_free(pe);
2753
            break;
2754
        }
2755
    }
2756
}
2757

    
2758
/***********************************************************/
2759
/* Wait objects support */
2760
typedef struct WaitObjects {
2761
    int num;
2762
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2763
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2764
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2765
} WaitObjects;
2766

    
2767
static WaitObjects wait_objects = {0};
2768

    
2769
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2770
{
2771
    WaitObjects *w = &wait_objects;
2772

    
2773
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2774
        return -1;
2775
    w->events[w->num] = handle;
2776
    w->func[w->num] = func;
2777
    w->opaque[w->num] = opaque;
2778
    w->num++;
2779
    return 0;
2780
}
2781

    
2782
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2783
{
2784
    int i, found;
2785
    WaitObjects *w = &wait_objects;
2786

    
2787
    found = 0;
2788
    for (i = 0; i < w->num; i++) {
2789
        if (w->events[i] == handle)
2790
            found = 1;
2791
        if (found) {
2792
            w->events[i] = w->events[i + 1];
2793
            w->func[i] = w->func[i + 1];
2794
            w->opaque[i] = w->opaque[i + 1];
2795
        }
2796
    }
2797
    if (found)
2798
        w->num--;
2799
}
2800
#endif
2801

    
2802
/***********************************************************/
2803
/* ram save/restore */
2804

    
2805
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2806
#define RAM_SAVE_FLAG_COMPRESS        0x02
2807
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2808
#define RAM_SAVE_FLAG_PAGE        0x08
2809
#define RAM_SAVE_FLAG_EOS        0x10
2810

    
2811
static int is_dup_page(uint8_t *page, uint8_t ch)
2812
{
2813
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2814
    uint32_t *array = (uint32_t *)page;
2815
    int i;
2816

    
2817
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2818
        if (array[i] != val)
2819
            return 0;
2820
    }
2821

    
2822
    return 1;
2823
}
2824

    
2825
static int ram_save_block(QEMUFile *f)
2826
{
2827
    static ram_addr_t current_addr = 0;
2828
    ram_addr_t saved_addr = current_addr;
2829
    ram_addr_t addr = 0;
2830
    int found = 0;
2831

    
2832
    while (addr < last_ram_offset) {
2833
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2834
            uint8_t *p;
2835

    
2836
            cpu_physical_memory_reset_dirty(current_addr,
2837
                                            current_addr + TARGET_PAGE_SIZE,
2838
                                            MIGRATION_DIRTY_FLAG);
2839

    
2840
            p = qemu_get_ram_ptr(current_addr);
2841

    
2842
            if (is_dup_page(p, *p)) {
2843
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2844
                qemu_put_byte(f, *p);
2845
            } else {
2846
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2847
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2848
            }
2849

    
2850
            found = 1;
2851
            break;
2852
        }
2853
        addr += TARGET_PAGE_SIZE;
2854
        current_addr = (saved_addr + addr) % last_ram_offset;
2855
    }
2856

    
2857
    return found;
2858
}
2859

    
2860
static uint64_t bytes_transferred;
2861

    
2862
static ram_addr_t ram_save_remaining(void)
2863
{
2864
    ram_addr_t addr;
2865
    ram_addr_t count = 0;
2866

    
2867
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2868
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2869
            count++;
2870
    }
2871

    
2872
    return count;
2873
}
2874

    
2875
uint64_t ram_bytes_remaining(void)
2876
{
2877
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2878
}
2879

    
2880
uint64_t ram_bytes_transferred(void)
2881
{
2882
    return bytes_transferred;
2883
}
2884

    
2885
uint64_t ram_bytes_total(void)
2886
{
2887
    return last_ram_offset;
2888
}
2889

    
2890
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2891
{
2892
    ram_addr_t addr;
2893
    uint64_t bytes_transferred_last;
2894
    double bwidth = 0;
2895
    uint64_t expected_time = 0;
2896

    
2897
    if (stage < 0) {
2898
        cpu_physical_memory_set_dirty_tracking(0);
2899
        return 0;
2900
    }
2901

    
2902
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2903
        qemu_file_set_error(f);
2904
        return 0;
2905
    }
2906

    
2907
    if (stage == 1) {
2908
        bytes_transferred = 0;
2909

    
2910
        /* Make sure all dirty bits are set */
2911
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2912
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2913
                cpu_physical_memory_set_dirty(addr);
2914
        }
2915

    
2916
        /* Enable dirty memory tracking */
2917
        cpu_physical_memory_set_dirty_tracking(1);
2918

    
2919
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2920
    }
2921

    
2922
    bytes_transferred_last = bytes_transferred;
2923
    bwidth = qemu_get_clock_ns(rt_clock);
2924

    
2925
    while (!qemu_file_rate_limit(f)) {
2926
        int ret;
2927

    
2928
        ret = ram_save_block(f);
2929
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2930
        if (ret == 0) /* no more blocks */
2931
            break;
2932
    }
2933

    
2934
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2935
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2936

    
2937
    /* if we haven't transferred anything this round, force expected_time to a
2938
     * a very high value, but without crashing */
2939
    if (bwidth == 0)
2940
        bwidth = 0.000001;
2941

    
2942
    /* try transferring iterative blocks of memory */
2943
    if (stage == 3) {
2944
        /* flush all remaining blocks regardless of rate limiting */
2945
        while (ram_save_block(f) != 0) {
2946
            bytes_transferred += TARGET_PAGE_SIZE;
2947
        }
2948
        cpu_physical_memory_set_dirty_tracking(0);
2949
    }
2950

    
2951
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2952

    
2953
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2954

    
2955
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2956
}
2957

    
2958
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2959
{
2960
    ram_addr_t addr;
2961
    int flags;
2962

    
2963
    if (version_id != 3)
2964
        return -EINVAL;
2965

    
2966
    do {
2967
        addr = qemu_get_be64(f);
2968

    
2969
        flags = addr & ~TARGET_PAGE_MASK;
2970
        addr &= TARGET_PAGE_MASK;
2971

    
2972
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2973
            if (addr != last_ram_offset)
2974
                return -EINVAL;
2975
        }
2976

    
2977
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2978
            uint8_t ch = qemu_get_byte(f);
2979
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2980
#ifndef _WIN32
2981
            if (ch == 0 &&
2982
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2983
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2984
            }
2985
#endif
2986
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
2987
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2988
        }
2989
        if (qemu_file_has_error(f)) {
2990
            return -EIO;
2991
        }
2992
    } while (!(flags & RAM_SAVE_FLAG_EOS));
2993

    
2994
    return 0;
2995
}
2996

    
2997
void qemu_service_io(void)
2998
{
2999
    qemu_notify_event();
3000
}
3001

    
3002
/***********************************************************/
3003
/* machine registration */
3004

    
3005
static QEMUMachine *first_machine = NULL;
3006
QEMUMachine *current_machine = NULL;
3007

    
3008
int qemu_register_machine(QEMUMachine *m)
3009
{
3010
    QEMUMachine **pm;
3011
    pm = &first_machine;
3012
    while (*pm != NULL)
3013
        pm = &(*pm)->next;
3014
    m->next = NULL;
3015
    *pm = m;
3016
    return 0;
3017
}
3018

    
3019
static QEMUMachine *find_machine(const char *name)
3020
{
3021
    QEMUMachine *m;
3022

    
3023
    for(m = first_machine; m != NULL; m = m->next) {
3024
        if (!strcmp(m->name, name))
3025
            return m;
3026
        if (m->alias && !strcmp(m->alias, name))
3027
            return m;
3028
    }
3029
    return NULL;
3030
}
3031

    
3032
static QEMUMachine *find_default_machine(void)
3033
{
3034
    QEMUMachine *m;
3035

    
3036
    for(m = first_machine; m != NULL; m = m->next) {
3037
        if (m->is_default) {
3038
            return m;
3039
        }
3040
    }
3041
    return NULL;
3042
}
3043

    
3044
/***********************************************************/
3045
/* main execution loop */
3046

    
3047
static void gui_update(void *opaque)
3048
{
3049
    uint64_t interval = GUI_REFRESH_INTERVAL;
3050
    DisplayState *ds = opaque;
3051
    DisplayChangeListener *dcl = ds->listeners;
3052

    
3053
    qemu_flush_coalesced_mmio_buffer();
3054
    dpy_refresh(ds);
3055

    
3056
    while (dcl != NULL) {
3057
        if (dcl->gui_timer_interval &&
3058
            dcl->gui_timer_interval < interval)
3059
            interval = dcl->gui_timer_interval;
3060
        dcl = dcl->next;
3061
    }
3062
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3063
}
3064

    
3065
static void nographic_update(void *opaque)
3066
{
3067
    uint64_t interval = GUI_REFRESH_INTERVAL;
3068

    
3069
    qemu_flush_coalesced_mmio_buffer();
3070
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3071
}
3072

    
3073
void cpu_synchronize_all_states(void)
3074
{
3075
    CPUState *cpu;
3076

    
3077
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3078
        cpu_synchronize_state(cpu);
3079
    }
3080
}
3081

    
3082
void cpu_synchronize_all_post_reset(void)
3083
{
3084
    CPUState *cpu;
3085

    
3086
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3087
        cpu_synchronize_post_reset(cpu);
3088
    }
3089
}
3090

    
3091
void cpu_synchronize_all_post_init(void)
3092
{
3093
    CPUState *cpu;
3094

    
3095
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3096
        cpu_synchronize_post_init(cpu);
3097
    }
3098
}
3099

    
3100
struct vm_change_state_entry {
3101
    VMChangeStateHandler *cb;
3102
    void *opaque;
3103
    QLIST_ENTRY (vm_change_state_entry) entries;
3104
};
3105

    
3106
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3107

    
3108
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3109
                                                     void *opaque)
3110
{
3111
    VMChangeStateEntry *e;
3112

    
3113
    e = qemu_mallocz(sizeof (*e));
3114

    
3115
    e->cb = cb;
3116
    e->opaque = opaque;
3117
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3118
    return e;
3119
}
3120

    
3121
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3122
{
3123
    QLIST_REMOVE (e, entries);
3124
    qemu_free (e);
3125
}
3126

    
3127
static void vm_state_notify(int running, int reason)
3128
{
3129
    VMChangeStateEntry *e;
3130

    
3131
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3132
        e->cb(e->opaque, running, reason);
3133
    }
3134
}
3135

    
3136
static void resume_all_vcpus(void);
3137
static void pause_all_vcpus(void);
3138

    
3139
void vm_start(void)
3140
{
3141
    if (!vm_running) {
3142
        cpu_enable_ticks();
3143
        vm_running = 1;
3144
        vm_state_notify(1, 0);
3145
        resume_all_vcpus();
3146
    }
3147
}
3148

    
3149
/* reset/shutdown handler */
3150

    
3151
typedef struct QEMUResetEntry {
3152
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3153
    QEMUResetHandler *func;
3154
    void *opaque;
3155
} QEMUResetEntry;
3156

    
3157
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3158
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3159
static int reset_requested;
3160
static int shutdown_requested;
3161
static int powerdown_requested;
3162
static int debug_requested;
3163
static int vmstop_requested;
3164

    
3165
int qemu_shutdown_requested(void)
3166
{
3167
    int r = shutdown_requested;
3168
    shutdown_requested = 0;
3169
    return r;
3170
}
3171

    
3172
int qemu_reset_requested(void)
3173
{
3174
    int r = reset_requested;
3175
    reset_requested = 0;
3176
    return r;
3177
}
3178

    
3179
int qemu_powerdown_requested(void)
3180
{
3181
    int r = powerdown_requested;
3182
    powerdown_requested = 0;
3183
    return r;
3184
}
3185

    
3186
static int qemu_debug_requested(void)
3187
{
3188
    int r = debug_requested;
3189
    debug_requested = 0;
3190
    return r;
3191
}
3192

    
3193
static int qemu_vmstop_requested(void)
3194
{
3195
    int r = vmstop_requested;
3196
    vmstop_requested = 0;
3197
    return r;
3198
}
3199

    
3200
static void do_vm_stop(int reason)
3201
{
3202
    if (vm_running) {
3203
        cpu_disable_ticks();
3204
        vm_running = 0;
3205
        pause_all_vcpus();
3206
        vm_state_notify(0, reason);
3207
        monitor_protocol_event(QEVENT_STOP, NULL);
3208
    }
3209
}
3210

    
3211
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3212
{
3213
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3214

    
3215
    re->func = func;
3216
    re->opaque = opaque;
3217
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3218
}
3219

    
3220
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3221
{
3222
    QEMUResetEntry *re;
3223

    
3224
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3225
        if (re->func == func && re->opaque == opaque) {
3226
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3227
            qemu_free(re);
3228
            return;
3229
        }
3230
    }
3231
}
3232

    
3233
void qemu_system_reset(void)
3234
{
3235
    QEMUResetEntry *re, *nre;
3236

    
3237
    /* reset all devices */
3238
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3239
        re->func(re->opaque);
3240
    }
3241
    monitor_protocol_event(QEVENT_RESET, NULL);
3242
    cpu_synchronize_all_post_reset();
3243
}
3244

    
3245
void qemu_system_reset_request(void)
3246
{
3247
    if (no_reboot) {
3248
        shutdown_requested = 1;
3249
    } else {
3250
        reset_requested = 1;
3251
    }
3252
    qemu_notify_event();
3253
}
3254

    
3255
void qemu_system_shutdown_request(void)
3256
{
3257
    shutdown_requested = 1;
3258
    qemu_notify_event();
3259
}
3260

    
3261
void qemu_system_powerdown_request(void)
3262
{
3263
    powerdown_requested = 1;
3264
    qemu_notify_event();
3265
}
3266

    
3267
#ifdef CONFIG_IOTHREAD
3268
static void qemu_system_vmstop_request(int reason)
3269
{
3270
    vmstop_requested = reason;
3271
    qemu_notify_event();
3272
}
3273
#endif
3274

    
3275
#ifndef _WIN32
3276
static int io_thread_fd = -1;
3277

    
3278
static void qemu_event_increment(void)
3279
{
3280
    /* Write 8 bytes to be compatible with eventfd.  */
3281
    static uint64_t val = 1;
3282
    ssize_t ret;
3283

    
3284
    if (io_thread_fd == -1)
3285
        return;
3286

    
3287
    do {
3288
        ret = write(io_thread_fd, &val, sizeof(val));
3289
    } while (ret < 0 && errno == EINTR);
3290

    
3291
    /* EAGAIN is fine, a read must be pending.  */
3292
    if (ret < 0 && errno != EAGAIN) {
3293
        fprintf(stderr, "qemu_event_increment: write() filed: %s\n",
3294
                strerror(errno));
3295
        exit (1);
3296
    }
3297
}
3298

    
3299
static void qemu_event_read(void *opaque)
3300
{
3301
    int fd = (unsigned long)opaque;
3302
    ssize_t len;
3303
    char buffer[512];
3304

    
3305
    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
3306
    do {
3307
        len = read(fd, buffer, sizeof(buffer));
3308
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3309
}
3310

    
3311
static int qemu_event_init(void)
3312
{
3313
    int err;
3314
    int fds[2];
3315

    
3316
    err = qemu_eventfd(fds);
3317
    if (err == -1)
3318
        return -errno;
3319

    
3320
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3321
    if (err < 0)
3322
        goto fail;
3323

    
3324
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3325
    if (err < 0)
3326
        goto fail;
3327

    
3328
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3329
                         (void *)(unsigned long)fds[0]);
3330

    
3331
    io_thread_fd = fds[1];
3332
    return 0;
3333

    
3334
fail:
3335
    close(fds[0]);
3336
    close(fds[1]);
3337
    return err;
3338
}
3339
#else
3340
HANDLE qemu_event_handle;
3341

    
3342
static void dummy_event_handler(void *opaque)
3343
{
3344
}
3345

    
3346
static int qemu_event_init(void)
3347
{
3348
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3349
    if (!qemu_event_handle) {
3350
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3351
        return -1;
3352
    }
3353
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3354
    return 0;
3355
}
3356

    
3357
static void qemu_event_increment(void)
3358
{
3359
    if (!SetEvent(qemu_event_handle)) {
3360
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3361
                GetLastError());
3362
        exit (1);
3363
    }
3364
}
3365
#endif
3366

    
3367
static int cpu_can_run(CPUState *env)
3368
{
3369
    if (env->stop)
3370
        return 0;
3371
    if (env->stopped)
3372
        return 0;
3373
    if (!vm_running)
3374
        return 0;
3375
    return 1;
3376
}
3377

    
3378
#ifndef CONFIG_IOTHREAD
3379
static int qemu_init_main_loop(void)
3380
{
3381
    return qemu_event_init();
3382
}
3383

    
3384
void qemu_init_vcpu(void *_env)
3385
{
3386
    CPUState *env = _env;
3387

    
3388
    env->nr_cores = smp_cores;
3389
    env->nr_threads = smp_threads;
3390
    if (kvm_enabled())
3391
        kvm_init_vcpu(env);
3392
    return;
3393
}
3394

    
3395
int qemu_cpu_self(void *env)
3396
{
3397
    return 1;
3398
}
3399

    
3400
static void resume_all_vcpus(void)
3401
{
3402
}
3403

    
3404
static void pause_all_vcpus(void)
3405
{
3406
}
3407

    
3408
void qemu_cpu_kick(void *env)
3409
{
3410
    return;
3411
}
3412

    
3413
void qemu_notify_event(void)
3414
{
3415
    CPUState *env = cpu_single_env;
3416

    
3417
    qemu_event_increment ();
3418
    if (env) {
3419
        cpu_exit(env);
3420
    }
3421
    if (next_cpu && env != next_cpu) {
3422
        cpu_exit(next_cpu);
3423
    }
3424
}
3425

    
3426
void qemu_mutex_lock_iothread(void) {}
3427
void qemu_mutex_unlock_iothread(void) {}
3428

    
3429
void vm_stop(int reason)
3430
{
3431
    do_vm_stop(reason);
3432
}
3433

    
3434
#else /* CONFIG_IOTHREAD */
3435

    
3436
#include "qemu-thread.h"
3437

    
3438
QemuMutex qemu_global_mutex;
3439
static QemuMutex qemu_fair_mutex;
3440

    
3441
static QemuThread io_thread;
3442

    
3443
static QemuThread *tcg_cpu_thread;
3444
static QemuCond *tcg_halt_cond;
3445

    
3446
static int qemu_system_ready;
3447
/* cpu creation */
3448
static QemuCond qemu_cpu_cond;
3449
/* system init */
3450
static QemuCond qemu_system_cond;
3451
static QemuCond qemu_pause_cond;
3452

    
3453
static void tcg_block_io_signals(void);
3454
static void kvm_block_io_signals(CPUState *env);
3455
static void unblock_io_signals(void);
3456
static int tcg_has_work(void);
3457
static int cpu_has_work(CPUState *env);
3458

    
3459
static int qemu_init_main_loop(void)
3460
{
3461
    int ret;
3462

    
3463
    ret = qemu_event_init();
3464
    if (ret)
3465
        return ret;
3466

    
3467
    qemu_cond_init(&qemu_pause_cond);
3468
    qemu_mutex_init(&qemu_fair_mutex);
3469
    qemu_mutex_init(&qemu_global_mutex);
3470
    qemu_mutex_lock(&qemu_global_mutex);
3471

    
3472
    unblock_io_signals();
3473
    qemu_thread_self(&io_thread);
3474

    
3475
    return 0;
3476
}
3477

    
3478
static void qemu_wait_io_event_common(CPUState *env)
3479
{
3480
    if (env->stop) {
3481
        env->stop = 0;
3482
        env->stopped = 1;
3483
        qemu_cond_signal(&qemu_pause_cond);
3484
    }
3485
}
3486

    
3487
static void qemu_wait_io_event(CPUState *env)
3488
{
3489
    while (!tcg_has_work())
3490
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3491

    
3492
    qemu_mutex_unlock(&qemu_global_mutex);
3493

    
3494
    /*
3495
     * Users of qemu_global_mutex can be starved, having no chance
3496
     * to acquire it since this path will get to it first.
3497
     * So use another lock to provide fairness.
3498
     */
3499
    qemu_mutex_lock(&qemu_fair_mutex);
3500
    qemu_mutex_unlock(&qemu_fair_mutex);
3501

    
3502
    qemu_mutex_lock(&qemu_global_mutex);
3503
    qemu_wait_io_event_common(env);
3504
}
3505

    
3506
static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3507
{
3508
    struct timespec ts;
3509
    int r, e;
3510
    siginfo_t siginfo;
3511
    sigset_t waitset;
3512

    
3513
    ts.tv_sec = timeout / 1000;
3514
    ts.tv_nsec = (timeout % 1000) * 1000000;
3515

    
3516
    sigemptyset(&waitset);
3517
    sigaddset(&waitset, SIG_IPI);
3518

    
3519
    qemu_mutex_unlock(&qemu_global_mutex);
3520
    r = sigtimedwait(&waitset, &siginfo, &ts);
3521
    e = errno;
3522
    qemu_mutex_lock(&qemu_global_mutex);
3523

    
3524
    if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3525
        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3526
        exit(1);
3527
    }
3528
}
3529

    
3530
static void qemu_kvm_wait_io_event(CPUState *env)
3531
{
3532
    while (!cpu_has_work(env))
3533
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3534

    
3535
    qemu_kvm_eat_signal(env, 0);
3536
    qemu_wait_io_event_common(env);
3537
}
3538

    
3539
static int qemu_cpu_exec(CPUState *env);
3540

    
3541
static void *kvm_cpu_thread_fn(void *arg)
3542
{
3543
    CPUState *env = arg;
3544

    
3545
    qemu_thread_self(env->thread);
3546
    if (kvm_enabled())
3547
        kvm_init_vcpu(env);
3548

    
3549
    kvm_block_io_signals(env);
3550

    
3551
    /* signal CPU creation */
3552
    qemu_mutex_lock(&qemu_global_mutex);
3553
    env->created = 1;
3554
    qemu_cond_signal(&qemu_cpu_cond);
3555

    
3556
    /* and wait for machine initialization */
3557
    while (!qemu_system_ready)
3558
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3559

    
3560
    while (1) {
3561
        if (cpu_can_run(env))
3562
            qemu_cpu_exec(env);
3563
        qemu_kvm_wait_io_event(env);
3564
    }
3565

    
3566
    return NULL;
3567
}
3568

    
3569
static void tcg_cpu_exec(void);
3570

    
3571
static void *tcg_cpu_thread_fn(void *arg)
3572
{
3573
    CPUState *env = arg;
3574

    
3575
    tcg_block_io_signals();
3576
    qemu_thread_self(env->thread);
3577

    
3578
    /* signal CPU creation */
3579
    qemu_mutex_lock(&qemu_global_mutex);
3580
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3581
        env->created = 1;
3582
    qemu_cond_signal(&qemu_cpu_cond);
3583

    
3584
    /* and wait for machine initialization */
3585
    while (!qemu_system_ready)
3586
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3587

    
3588
    while (1) {
3589
        tcg_cpu_exec();
3590
        qemu_wait_io_event(cur_cpu);
3591
    }
3592

    
3593
    return NULL;
3594
}
3595

    
3596
void qemu_cpu_kick(void *_env)
3597
{
3598
    CPUState *env = _env;
3599
    qemu_cond_broadcast(env->halt_cond);
3600
    if (kvm_enabled())
3601
        qemu_thread_signal(env->thread, SIG_IPI);
3602
}
3603

    
3604
int qemu_cpu_self(void *_env)
3605
{
3606
    CPUState *env = _env;
3607
    QemuThread this;
3608
 
3609
    qemu_thread_self(&this);
3610
 
3611
    return qemu_thread_equal(&this, env->thread);
3612
}
3613

    
3614
static void cpu_signal(int sig)
3615
{
3616
    if (cpu_single_env)
3617
        cpu_exit(cpu_single_env);
3618
}
3619

    
3620
static void tcg_block_io_signals(void)
3621
{
3622
    sigset_t set;
3623
    struct sigaction sigact;
3624

    
3625
    sigemptyset(&set);
3626
    sigaddset(&set, SIGUSR2);
3627
    sigaddset(&set, SIGIO);
3628
    sigaddset(&set, SIGALRM);
3629
    sigaddset(&set, SIGCHLD);
3630
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3631

    
3632
    sigemptyset(&set);
3633
    sigaddset(&set, SIG_IPI);
3634
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3635

    
3636
    memset(&sigact, 0, sizeof(sigact));
3637
    sigact.sa_handler = cpu_signal;
3638
    sigaction(SIG_IPI, &sigact, NULL);
3639
}
3640

    
3641
static void dummy_signal(int sig)
3642
{
3643
}
3644

    
3645
static void kvm_block_io_signals(CPUState *env)
3646
{
3647
    int r;
3648
    sigset_t set;
3649
    struct sigaction sigact;
3650

    
3651
    sigemptyset(&set);
3652
    sigaddset(&set, SIGUSR2);
3653
    sigaddset(&set, SIGIO);
3654
    sigaddset(&set, SIGALRM);
3655
    sigaddset(&set, SIGCHLD);
3656
    sigaddset(&set, SIG_IPI);
3657
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3658

    
3659
    pthread_sigmask(SIG_BLOCK, NULL, &set);
3660
    sigdelset(&set, SIG_IPI);
3661

    
3662
    memset(&sigact, 0, sizeof(sigact));
3663
    sigact.sa_handler = dummy_signal;
3664
    sigaction(SIG_IPI, &sigact, NULL);
3665

    
3666
    r = kvm_set_signal_mask(env, &set);
3667
    if (r) {
3668
        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3669
        exit(1);
3670
    }
3671
}
3672

    
3673
static void unblock_io_signals(void)
3674
{
3675
    sigset_t set;
3676

    
3677
    sigemptyset(&set);
3678
    sigaddset(&set, SIGUSR2);
3679
    sigaddset(&set, SIGIO);
3680
    sigaddset(&set, SIGALRM);
3681
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3682

    
3683
    sigemptyset(&set);
3684
    sigaddset(&set, SIG_IPI);
3685
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3686
}
3687

    
3688
static void qemu_signal_lock(unsigned int msecs)
3689
{
3690
    qemu_mutex_lock(&qemu_fair_mutex);
3691

    
3692
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3693
        qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3694
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3695
            break;
3696
    }
3697
    qemu_mutex_unlock(&qemu_fair_mutex);
3698
}
3699

    
3700
void qemu_mutex_lock_iothread(void)
3701
{
3702
    if (kvm_enabled()) {
3703
        qemu_mutex_lock(&qemu_fair_mutex);
3704
        qemu_mutex_lock(&qemu_global_mutex);
3705
        qemu_mutex_unlock(&qemu_fair_mutex);
3706
    } else
3707
        qemu_signal_lock(100);
3708
}
3709

    
3710
void qemu_mutex_unlock_iothread(void)
3711
{
3712
    qemu_mutex_unlock(&qemu_global_mutex);
3713
}
3714

    
3715
static int all_vcpus_paused(void)
3716
{
3717
    CPUState *penv = first_cpu;
3718

    
3719
    while (penv) {
3720
        if (!penv->stopped)
3721
            return 0;
3722
        penv = (CPUState *)penv->next_cpu;
3723
    }
3724

    
3725
    return 1;
3726
}
3727

    
3728
static void pause_all_vcpus(void)
3729
{
3730
    CPUState *penv = first_cpu;
3731

    
3732
    while (penv) {
3733
        penv->stop = 1;
3734
        qemu_thread_signal(penv->thread, SIG_IPI);
3735
        qemu_cpu_kick(penv);
3736
        penv = (CPUState *)penv->next_cpu;
3737
    }
3738

    
3739
    while (!all_vcpus_paused()) {
3740
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3741
        penv = first_cpu;
3742
        while (penv) {
3743
            qemu_thread_signal(penv->thread, SIG_IPI);
3744
            penv = (CPUState *)penv->next_cpu;
3745
        }
3746
    }
3747
}
3748

    
3749
static void resume_all_vcpus(void)
3750
{
3751
    CPUState *penv = first_cpu;
3752

    
3753
    while (penv) {
3754
        penv->stop = 0;
3755
        penv->stopped = 0;
3756
        qemu_thread_signal(penv->thread, SIG_IPI);
3757
        qemu_cpu_kick(penv);
3758
        penv = (CPUState *)penv->next_cpu;
3759
    }
3760
}
3761

    
3762
static void tcg_init_vcpu(void *_env)
3763
{
3764
    CPUState *env = _env;
3765
    /* share a single thread for all cpus with TCG */
3766
    if (!tcg_cpu_thread) {
3767
        env->thread = qemu_mallocz(sizeof(QemuThread));
3768
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3769
        qemu_cond_init(env->halt_cond);
3770
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3771
        while (env->created == 0)
3772
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3773
        tcg_cpu_thread = env->thread;
3774
        tcg_halt_cond = env->halt_cond;
3775
    } else {
3776
        env->thread = tcg_cpu_thread;
3777
        env->halt_cond = tcg_halt_cond;
3778
    }
3779
}
3780

    
3781
static void kvm_start_vcpu(CPUState *env)
3782
{
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, kvm_cpu_thread_fn, env);
3787
    while (env->created == 0)
3788
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3789
}
3790

    
3791
void qemu_init_vcpu(void *_env)
3792
{
3793
    CPUState *env = _env;
3794

    
3795
    env->nr_cores = smp_cores;
3796
    env->nr_threads = smp_threads;
3797
    if (kvm_enabled())
3798
        kvm_start_vcpu(env);
3799
    else
3800
        tcg_init_vcpu(env);
3801
}
3802

    
3803
void qemu_notify_event(void)
3804
{
3805
    qemu_event_increment();
3806
}
3807

    
3808
void vm_stop(int reason)
3809
{
3810
    QemuThread me;
3811
    qemu_thread_self(&me);
3812

    
3813
    if (!qemu_thread_equal(&me, &io_thread)) {
3814
        qemu_system_vmstop_request(reason);
3815
        /*
3816
         * FIXME: should not return to device code in case
3817
         * vm_stop() has been requested.
3818
         */
3819
        if (cpu_single_env) {
3820
            cpu_exit(cpu_single_env);
3821
            cpu_single_env->stop = 1;
3822
        }
3823
        return;
3824
    }
3825
    do_vm_stop(reason);
3826
}
3827

    
3828
#endif
3829

    
3830

    
3831
#ifdef _WIN32
3832
static void host_main_loop_wait(int *timeout)
3833
{
3834
    int ret, ret2, i;
3835
    PollingEntry *pe;
3836

    
3837

    
3838
    /* XXX: need to suppress polling by better using win32 events */
3839
    ret = 0;
3840
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3841
        ret |= pe->func(pe->opaque);
3842
    }
3843
    if (ret == 0) {
3844
        int err;
3845
        WaitObjects *w = &wait_objects;
3846

    
3847
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3848
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3849
            if (w->func[ret - WAIT_OBJECT_0])
3850
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3851

    
3852
            /* Check for additional signaled events */
3853
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3854

    
3855
                /* Check if event is signaled */
3856
                ret2 = WaitForSingleObject(w->events[i], 0);
3857
                if(ret2 == WAIT_OBJECT_0) {
3858
                    if (w->func[i])
3859
                        w->func[i](w->opaque[i]);
3860
                } else if (ret2 == WAIT_TIMEOUT) {
3861
                } else {
3862
                    err = GetLastError();
3863
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3864
                }
3865
            }
3866
        } else if (ret == WAIT_TIMEOUT) {
3867
        } else {
3868
            err = GetLastError();
3869
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3870
        }
3871
    }
3872

    
3873
    *timeout = 0;
3874
}
3875
#else
3876
static void host_main_loop_wait(int *timeout)
3877
{
3878
}
3879
#endif
3880

    
3881
void main_loop_wait(int timeout)
3882
{
3883
    IOHandlerRecord *ioh;
3884
    fd_set rfds, wfds, xfds;
3885
    int ret, nfds;
3886
    struct timeval tv;
3887

    
3888
    qemu_bh_update_timeout(&timeout);
3889

    
3890
    host_main_loop_wait(&timeout);
3891

    
3892
    /* poll any events */
3893
    /* XXX: separate device handlers from system ones */
3894
    nfds = -1;
3895
    FD_ZERO(&rfds);
3896
    FD_ZERO(&wfds);
3897
    FD_ZERO(&xfds);
3898
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3899
        if (ioh->deleted)
3900
            continue;
3901
        if (ioh->fd_read &&
3902
            (!ioh->fd_read_poll ||
3903
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3904
            FD_SET(ioh->fd, &rfds);
3905
            if (ioh->fd > nfds)
3906
                nfds = ioh->fd;
3907
        }
3908
        if (ioh->fd_write) {
3909
            FD_SET(ioh->fd, &wfds);
3910
            if (ioh->fd > nfds)
3911
                nfds = ioh->fd;
3912
        }
3913
    }
3914

    
3915
    tv.tv_sec = timeout / 1000;
3916
    tv.tv_usec = (timeout % 1000) * 1000;
3917

    
3918
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3919

    
3920
    qemu_mutex_unlock_iothread();
3921
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3922
    qemu_mutex_lock_iothread();
3923
    if (ret > 0) {
3924
        IOHandlerRecord **pioh;
3925

    
3926
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3927
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3928
                ioh->fd_read(ioh->opaque);
3929
            }
3930
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3931
                ioh->fd_write(ioh->opaque);
3932
            }
3933
        }
3934

    
3935
        /* remove deleted IO handlers */
3936
        pioh = &first_io_handler;
3937
        while (*pioh) {
3938
            ioh = *pioh;
3939
            if (ioh->deleted) {
3940
                *pioh = ioh->next;
3941
                qemu_free(ioh);
3942
            } else
3943
                pioh = &ioh->next;
3944
        }
3945
    }
3946

    
3947
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3948

    
3949
    qemu_run_all_timers();
3950

    
3951
    /* Check bottom-halves last in case any of the earlier events triggered
3952
       them.  */
3953
    qemu_bh_poll();
3954

    
3955
}
3956

    
3957
static int qemu_cpu_exec(CPUState *env)
3958
{
3959
    int ret;
3960
#ifdef CONFIG_PROFILER
3961
    int64_t ti;
3962
#endif
3963

    
3964
#ifdef CONFIG_PROFILER
3965
    ti = profile_getclock();
3966
#endif
3967
    if (use_icount) {
3968
        int64_t count;
3969
        int decr;
3970
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3971
        env->icount_decr.u16.low = 0;
3972
        env->icount_extra = 0;
3973
        count = qemu_icount_round (qemu_next_deadline());
3974
        qemu_icount += count;
3975
        decr = (count > 0xffff) ? 0xffff : count;
3976
        count -= decr;
3977
        env->icount_decr.u16.low = decr;
3978
        env->icount_extra = count;
3979
    }
3980
    ret = cpu_exec(env);
3981
#ifdef CONFIG_PROFILER
3982
    qemu_time += profile_getclock() - ti;
3983
#endif
3984
    if (use_icount) {
3985
        /* Fold pending instructions back into the
3986
           instruction counter, and clear the interrupt flag.  */
3987
        qemu_icount -= (env->icount_decr.u16.low
3988
                        + env->icount_extra);
3989
        env->icount_decr.u32 = 0;
3990
        env->icount_extra = 0;
3991
    }
3992
    return ret;
3993
}
3994

    
3995
static void tcg_cpu_exec(void)
3996
{
3997
    int ret = 0;
3998

    
3999
    if (next_cpu == NULL)
4000
        next_cpu = first_cpu;
4001
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4002
        CPUState *env = cur_cpu = next_cpu;
4003

    
4004
        qemu_clock_enable(vm_clock,
4005
                          (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
4006

    
4007
        if (qemu_alarm_pending())
4008
            break;
4009
        if (cpu_can_run(env))
4010
            ret = qemu_cpu_exec(env);
4011
        else if (env->stop)
4012
            break;
4013

    
4014
        if (ret == EXCP_DEBUG) {
4015
            gdb_set_stop_cpu(env);
4016
            debug_requested = 1;
4017
            break;
4018
        }
4019
    }
4020
}
4021

    
4022
static int cpu_has_work(CPUState *env)
4023
{
4024
    if (env->stop)
4025
        return 1;
4026
    if (env->stopped)
4027
        return 0;
4028
    if (!env->halted)
4029
        return 1;
4030
    if (qemu_cpu_has_work(env))
4031
        return 1;
4032
    return 0;
4033
}
4034

    
4035
static int tcg_has_work(void)
4036
{
4037
    CPUState *env;
4038

    
4039
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4040
        if (cpu_has_work(env))
4041
            return 1;
4042
    return 0;
4043
}
4044

    
4045
static int qemu_calculate_timeout(void)
4046
{
4047
#ifndef CONFIG_IOTHREAD
4048
    int timeout;
4049

    
4050
    if (!vm_running)
4051
        timeout = 5000;
4052
    else if (tcg_has_work())
4053
        timeout = 0;
4054
    else if (!use_icount)
4055
        timeout = 5000;
4056
    else {
4057
     /* XXX: use timeout computed from timers */
4058
        int64_t add;
4059
        int64_t delta;
4060
        /* Advance virtual time to the next event.  */
4061
        if (use_icount == 1) {
4062
            /* When not using an adaptive execution frequency
4063
               we tend to get badly out of sync with real time,
4064
               so just delay for a reasonable amount of time.  */
4065
            delta = 0;
4066
        } else {
4067
            delta = cpu_get_icount() - cpu_get_clock();
4068
        }
4069
        if (delta > 0) {
4070
            /* If virtual time is ahead of real time then just
4071
               wait for IO.  */
4072
            timeout = (delta / 1000000) + 1;
4073
        } else {
4074
            /* Wait for either IO to occur or the next
4075
               timer event.  */
4076
            add = qemu_next_deadline();
4077
            /* We advance the timer before checking for IO.
4078
               Limit the amount we advance so that early IO
4079
               activity won't get the guest too far ahead.  */
4080
            if (add > 10000000)
4081
                add = 10000000;
4082
            delta += add;
4083
            qemu_icount += qemu_icount_round (add);
4084
            timeout = delta / 1000000;
4085
            if (timeout < 0)
4086
                timeout = 0;
4087
        }
4088
    }
4089

    
4090
    return timeout;
4091
#else /* CONFIG_IOTHREAD */
4092
    return 1000;
4093
#endif
4094
}
4095

    
4096
static int vm_can_run(void)
4097
{
4098
    if (powerdown_requested)
4099
        return 0;
4100
    if (reset_requested)
4101
        return 0;
4102
    if (shutdown_requested)
4103
        return 0;
4104
    if (debug_requested)
4105
        return 0;
4106
    return 1;
4107
}
4108

    
4109
qemu_irq qemu_system_powerdown;
4110

    
4111
static void main_loop(void)
4112
{
4113
    int r;
4114

    
4115
#ifdef CONFIG_IOTHREAD
4116
    qemu_system_ready = 1;
4117
    qemu_cond_broadcast(&qemu_system_cond);
4118
#endif
4119

    
4120
    for (;;) {
4121
        do {
4122
#ifdef CONFIG_PROFILER
4123
            int64_t ti;
4124
#endif
4125
#ifndef CONFIG_IOTHREAD
4126
            tcg_cpu_exec();
4127
#endif
4128
#ifdef CONFIG_PROFILER
4129
            ti = profile_getclock();
4130
#endif
4131
            main_loop_wait(qemu_calculate_timeout());
4132
#ifdef CONFIG_PROFILER
4133
            dev_time += profile_getclock() - ti;
4134
#endif
4135
        } while (vm_can_run());
4136

    
4137
        if (qemu_debug_requested()) {
4138
            vm_stop(EXCP_DEBUG);
4139
        }
4140
        if (qemu_shutdown_requested()) {
4141
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4142
            if (no_shutdown) {
4143
                vm_stop(0);
4144
                no_shutdown = 0;
4145
            } else
4146
                break;
4147
        }
4148
        if (qemu_reset_requested()) {
4149
            pause_all_vcpus();
4150
            qemu_system_reset();
4151
            resume_all_vcpus();
4152
        }
4153
        if (qemu_powerdown_requested()) {
4154
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4155
            qemu_irq_raise(qemu_system_powerdown);
4156
        }
4157
        if ((r = qemu_vmstop_requested())) {
4158
            vm_stop(r);
4159
        }
4160
    }
4161
    pause_all_vcpus();
4162
}
4163

    
4164
static void version(void)
4165
{
4166
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4167
}
4168

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

    
4197
#define HAS_ARG 0x0001
4198

    
4199
enum {
4200
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4201
    opt_enum,
4202
#define DEFHEADING(text)
4203
#include "qemu-options.h"
4204
#undef DEF
4205
#undef DEFHEADING
4206
#undef GEN_DOCS
4207
};
4208

    
4209
typedef struct QEMUOption {
4210
    const char *name;
4211
    int flags;
4212
    int index;
4213
} QEMUOption;
4214

    
4215
static const QEMUOption qemu_options[] = {
4216
    { "h", 0, QEMU_OPTION_h },
4217
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4218
    { option, opt_arg, opt_enum },
4219
#define DEFHEADING(text)
4220
#include "qemu-options.h"
4221
#undef DEF
4222
#undef DEFHEADING
4223
#undef GEN_DOCS
4224
    { NULL },
4225
};
4226

    
4227
#ifdef HAS_AUDIO
4228
struct soundhw soundhw[] = {
4229
#ifdef HAS_AUDIO_CHOICE
4230
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4231
    {
4232
        "pcspk",
4233
        "PC speaker",
4234
        0,
4235
        1,
4236
        { .init_isa = pcspk_audio_init }
4237
    },
4238
#endif
4239

    
4240
#ifdef CONFIG_SB16
4241
    {
4242
        "sb16",
4243
        "Creative Sound Blaster 16",
4244
        0,
4245
        1,
4246
        { .init_isa = SB16_init }
4247
    },
4248
#endif
4249

    
4250
#ifdef CONFIG_CS4231A
4251
    {
4252
        "cs4231a",
4253
        "CS4231A",
4254
        0,
4255
        1,
4256
        { .init_isa = cs4231a_init }
4257
    },
4258
#endif
4259

    
4260
#ifdef CONFIG_ADLIB
4261
    {
4262
        "adlib",
4263
#ifdef HAS_YMF262
4264
        "Yamaha YMF262 (OPL3)",
4265
#else
4266
        "Yamaha YM3812 (OPL2)",
4267
#endif
4268
        0,
4269
        1,
4270
        { .init_isa = Adlib_init }
4271
    },
4272
#endif
4273

    
4274
#ifdef CONFIG_GUS
4275
    {
4276
        "gus",
4277
        "Gravis Ultrasound GF1",
4278
        0,
4279
        1,
4280
        { .init_isa = GUS_init }
4281
    },
4282
#endif
4283

    
4284
#ifdef CONFIG_AC97
4285
    {
4286
        "ac97",
4287
        "Intel 82801AA AC97 Audio",
4288
        0,
4289
        0,
4290
        { .init_pci = ac97_init }
4291
    },
4292
#endif
4293

    
4294
#ifdef CONFIG_ES1370
4295
    {
4296
        "es1370",
4297
        "ENSONIQ AudioPCI ES1370",
4298
        0,
4299
        0,
4300
        { .init_pci = es1370_init }
4301
    },
4302
#endif
4303

    
4304
#endif /* HAS_AUDIO_CHOICE */
4305

    
4306
    { NULL, NULL, 0, 0, { NULL } }
4307
};
4308

    
4309
static void select_soundhw (const char *optarg)
4310
{
4311
    struct soundhw *c;
4312

    
4313
    if (*optarg == '?') {
4314
    show_valid_cards:
4315

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

    
4329
        if (!strcmp (optarg, "all")) {
4330
            for (c = soundhw; c->name; ++c) {
4331
                c->enabled = 1;
4332
            }
4333
            return;
4334
        }
4335

    
4336
        p = optarg;
4337
        while (*p) {
4338
            e = strchr (p, ',');
4339
            l = !e ? strlen (p) : (size_t) (e - p);
4340

    
4341
            for (c = soundhw; c->name; ++c) {
4342
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4343
                    c->enabled = 1;
4344
                    break;
4345
                }
4346
            }
4347

    
4348
            if (!c->name) {
4349
                if (l > 80) {
4350
                    fprintf (stderr,
4351
                             "Unknown sound card name (too big to show)\n");
4352
                }
4353
                else {
4354
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4355
                             (int) l, p);
4356
                }
4357
                bad_card = 1;
4358
            }
4359
            p += l + (e != NULL);
4360
        }
4361

    
4362
        if (bad_card)
4363
            goto show_valid_cards;
4364
    }
4365
}
4366
#endif
4367

    
4368
static void select_vgahw (const char *p)
4369
{
4370
    const char *opts;
4371

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

    
4390
        if (strstart(opts, ",retrace=", &nextopt)) {
4391
            opts = nextopt;
4392
            if (strstart(opts, "dumb", &nextopt))
4393
                vga_retrace_method = VGA_RETRACE_DUMB;
4394
            else if (strstart(opts, "precise", &nextopt))
4395
                vga_retrace_method = VGA_RETRACE_PRECISE;
4396
            else goto invalid_vga;
4397
        } else goto invalid_vga;
4398
        opts = nextopt;
4399
    }
4400
}
4401

    
4402
#ifdef TARGET_I386
4403
static int balloon_parse(const char *arg)
4404
{
4405
    QemuOpts *opts;
4406

    
4407
    if (strcmp(arg, "none") == 0) {
4408
        return 0;
4409
    }
4410

    
4411
    if (!strncmp(arg, "virtio", 6)) {
4412
        if (arg[6] == ',') {
4413
            /* have params -> parse them */
4414
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, 0);
4415
            if (!opts)
4416
                return  -1;
4417
        } else {
4418
            /* create empty opts */
4419
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4420
        }
4421
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4422
        return 0;
4423
    }
4424

    
4425
    return -1;
4426
}
4427
#endif
4428

    
4429
#ifdef _WIN32
4430
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4431
{
4432
    exit(STATUS_CONTROL_C_EXIT);
4433
    return TRUE;
4434
}
4435
#endif
4436

    
4437
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4438
{
4439
    int ret;
4440

    
4441
    if(strlen(str) != 36)
4442
        return -1;
4443

    
4444
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4445
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4446
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4447

    
4448
    if(ret != 16)
4449
        return -1;
4450

    
4451
#ifdef TARGET_I386
4452
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4453
#endif
4454

    
4455
    return 0;
4456
}
4457

    
4458
#ifndef _WIN32
4459

    
4460
static void termsig_handler(int signal)
4461
{
4462
    qemu_system_shutdown_request();
4463
}
4464

    
4465
static void sigchld_handler(int signal)
4466
{
4467
    waitpid(-1, NULL, WNOHANG);
4468
}
4469

    
4470
static void sighandler_setup(void)
4471
{
4472
    struct sigaction act;
4473

    
4474
    memset(&act, 0, sizeof(act));
4475
    act.sa_handler = termsig_handler;
4476
    sigaction(SIGINT,  &act, NULL);
4477
    sigaction(SIGHUP,  &act, NULL);
4478
    sigaction(SIGTERM, &act, NULL);
4479

    
4480
    act.sa_handler = sigchld_handler;
4481
    act.sa_flags = SA_NOCLDSTOP;
4482
    sigaction(SIGCHLD, &act, NULL);
4483
}
4484

    
4485
#endif
4486

    
4487
#ifdef _WIN32
4488
/* Look for support files in the same directory as the executable.  */
4489
static char *find_datadir(const char *argv0)
4490
{
4491
    char *p;
4492
    char buf[MAX_PATH];
4493
    DWORD len;
4494

    
4495
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4496
    if (len == 0) {
4497
        return NULL;
4498
    }
4499

    
4500
    buf[len] = 0;
4501
    p = buf + len - 1;
4502
    while (p != buf && *p != '\\')
4503
        p--;
4504
    *p = 0;
4505
    if (access(buf, R_OK) == 0) {
4506
        return qemu_strdup(buf);
4507
    }
4508
    return NULL;
4509
}
4510
#else /* !_WIN32 */
4511

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

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

    
4555
    max_len = strlen(dir) +
4556
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4557
    res = qemu_mallocz(max_len);
4558
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4559
    if (access(res, R_OK)) {
4560
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4561
        if (access(res, R_OK)) {
4562
            qemu_free(res);
4563
            res = NULL;
4564
        }
4565
    }
4566

    
4567
    return res;
4568
}
4569
#undef SHARE_SUFFIX
4570
#undef BUILD_SUFFIX
4571
#endif
4572

    
4573
char *qemu_find_file(int type, const char *name)
4574
{
4575
    int len;
4576
    const char *subdir;
4577
    char *buf;
4578

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

    
4604
static int device_help_func(QemuOpts *opts, void *opaque)
4605
{
4606
    return qdev_device_help(opts);
4607
}
4608

    
4609
static int device_init_func(QemuOpts *opts, void *opaque)
4610
{
4611
    DeviceState *dev;
4612

    
4613
    dev = qdev_device_add(opts);
4614
    if (!dev)
4615
        return -1;
4616
    return 0;
4617
}
4618

    
4619
static int chardev_init_func(QemuOpts *opts, void *opaque)
4620
{
4621
    CharDriverState *chr;
4622

    
4623
    chr = qemu_chr_open_opts(opts, NULL);
4624
    if (!chr)
4625
        return -1;
4626
    return 0;
4627
}
4628

    
4629
static int mon_init_func(QemuOpts *opts, void *opaque)
4630
{
4631
    CharDriverState *chr;
4632
    const char *chardev;
4633
    const char *mode;
4634
    int flags;
4635

    
4636
    mode = qemu_opt_get(opts, "mode");
4637
    if (mode == NULL) {
4638
        mode = "readline";
4639
    }
4640
    if (strcmp(mode, "readline") == 0) {
4641
        flags = MONITOR_USE_READLINE;
4642
    } else if (strcmp(mode, "control") == 0) {
4643
        flags = MONITOR_USE_CONTROL;
4644
    } else {
4645
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4646
        exit(1);
4647
    }
4648

    
4649
    if (qemu_opt_get_bool(opts, "default", 0))
4650
        flags |= MONITOR_IS_DEFAULT;
4651

    
4652
    chardev = qemu_opt_get(opts, "chardev");
4653
    chr = qemu_chr_find(chardev);
4654
    if (chr == NULL) {
4655
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4656
        exit(1);
4657
    }
4658

    
4659
    monitor_init(chr, flags);
4660
    return 0;
4661
}
4662

    
4663
static void monitor_parse(const char *optarg, const char *mode)
4664
{
4665
    static int monitor_device_index = 0;
4666
    QemuOpts *opts;
4667
    const char *p;
4668
    char label[32];
4669
    int def = 0;
4670

    
4671
    if (strstart(optarg, "chardev:", &p)) {
4672
        snprintf(label, sizeof(label), "%s", p);
4673
    } else {
4674
        if (monitor_device_index) {
4675
            snprintf(label, sizeof(label), "monitor%d",
4676
                     monitor_device_index);
4677
        } else {
4678
            snprintf(label, sizeof(label), "monitor");
4679
            def = 1;
4680
        }
4681
        opts = qemu_chr_parse_compat(label, optarg);
4682
        if (!opts) {
4683
            fprintf(stderr, "parse error: %s\n", optarg);
4684
            exit(1);
4685
        }
4686
    }
4687

    
4688
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4689
    if (!opts) {
4690
        fprintf(stderr, "duplicate chardev: %s\n", label);
4691
        exit(1);
4692
    }
4693
    qemu_opt_set(opts, "mode", mode);
4694
    qemu_opt_set(opts, "chardev", label);
4695
    if (def)
4696
        qemu_opt_set(opts, "default", "on");
4697
    monitor_device_index++;
4698
}
4699

    
4700
struct device_config {
4701
    enum {
4702
        DEV_USB,       /* -usbdevice     */
4703
        DEV_BT,        /* -bt            */
4704
        DEV_SERIAL,    /* -serial        */
4705
        DEV_PARALLEL,  /* -parallel      */
4706
        DEV_VIRTCON,   /* -virtioconsole */
4707
        DEV_DEBUGCON,  /* -debugcon */
4708
    } type;
4709
    const char *cmdline;
4710
    QTAILQ_ENTRY(device_config) next;
4711
};
4712
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4713

    
4714
static void add_device_config(int type, const char *cmdline)
4715
{
4716
    struct device_config *conf;
4717

    
4718
    conf = qemu_mallocz(sizeof(*conf));
4719
    conf->type = type;
4720
    conf->cmdline = cmdline;
4721
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4722
}
4723

    
4724
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4725
{
4726
    struct device_config *conf;
4727
    int rc;
4728

    
4729
    QTAILQ_FOREACH(conf, &device_configs, next) {
4730
        if (conf->type != type)
4731
            continue;
4732
        rc = func(conf->cmdline);
4733
        if (0 != rc)
4734
            return rc;
4735
    }
4736
    return 0;
4737
}
4738

    
4739
static int serial_parse(const char *devname)
4740
{
4741
    static int index = 0;
4742
    char label[32];
4743

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

    
4761
static int parallel_parse(const char *devname)
4762
{
4763
    static int index = 0;
4764
    char label[32];
4765

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

    
4783
static int virtcon_parse(const char *devname)
4784
{
4785
    static int index = 0;
4786
    char label[32];
4787
    QemuOpts *bus_opts, *dev_opts;
4788

    
4789
    if (strcmp(devname, "none") == 0)
4790
        return 0;
4791
    if (index == MAX_VIRTIO_CONSOLES) {
4792
        fprintf(stderr, "qemu: too many virtio consoles\n");
4793
        exit(1);
4794
    }
4795

    
4796
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4797
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4798

    
4799
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4800
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4801

    
4802
    snprintf(label, sizeof(label), "virtcon%d", index);
4803
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4804
    if (!virtcon_hds[index]) {
4805
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4806
                devname, strerror(errno));
4807
        return -1;
4808
    }
4809
    qemu_opt_set(dev_opts, "chardev", label);
4810

    
4811
    index++;
4812
    return 0;
4813
}
4814

    
4815
static int debugcon_parse(const char *devname)
4816
{   
4817
    QemuOpts *opts;
4818

    
4819
    if (!qemu_chr_open("debugcon", devname, NULL)) {
4820
        exit(1);
4821
    }
4822
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4823
    if (!opts) {
4824
        fprintf(stderr, "qemu: already have a debugcon device\n");
4825
        exit(1);
4826
    }
4827
    qemu_opt_set(opts, "driver", "isa-debugcon");
4828
    qemu_opt_set(opts, "chardev", "debugcon");
4829
    return 0;
4830
}
4831

    
4832
static const QEMUOption *lookup_opt(int argc, char **argv,
4833
                                    const char **poptarg, int *poptind)
4834
{
4835
    const QEMUOption *popt;
4836
    int optind = *poptind;
4837
    char *r = argv[optind];
4838
    const char *optarg;
4839

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

    
4866
    *poptarg = optarg;
4867
    *poptind = optind;
4868

    
4869
    return popt;
4870
}
4871

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

    
4907
    error_set_progname(argv[0]);
4908

    
4909
    init_clocks();
4910

    
4911
    qemu_cache_utils_init(envp);
4912

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

    
4944
    module_call_init(MODULE_INIT_MACHINE);
4945
    machine = find_default_machine();
4946
    cpu_model = NULL;
4947
    initrd_filename = NULL;
4948
    ram_size = 0;
4949
    snapshot = 0;
4950
    kernel_filename = NULL;
4951
    kernel_cmdline = "";
4952
    cyls = heads = secs = 0;
4953
    translation = BIOS_ATA_TRANSLATION_AUTO;
4954

    
4955
    for (i = 0; i < MAX_NODES; i++) {
4956
        node_mem[i] = 0;
4957
        node_cpumask[i] = 0;
4958
    }
4959

    
4960
    nb_numa_nodes = 0;
4961
    nb_nics = 0;
4962

    
4963
    tb_size = 0;
4964
    autostart= 1;
4965

    
4966
    /* first pass of option parsing */
4967
    optind = 1;
4968
    while (optind < argc) {
4969
        if (argv[optind][0] != '-') {
4970
            /* disk image */
4971
            optind++;
4972
            continue;
4973
        } else {
4974
            const QEMUOption *popt;
4975

    
4976
            popt = lookup_opt(argc, argv, &optarg, &optind);
4977
            switch (popt->index) {
4978
            case QEMU_OPTION_nodefconfig:
4979
                defconfig=0;
4980
                break;
4981
            }
4982
        }
4983
    }
4984

    
4985
    if (defconfig) {
4986
        const char *fname;
4987
        FILE *fp;
4988

    
4989
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
4990
        fp = fopen(fname, "r");
4991
        if (fp) {
4992
            if (qemu_config_parse(fp, fname) != 0) {
4993
                exit(1);
4994
            }
4995
            fclose(fp);
4996
        }
4997

    
4998
        fname = CONFIG_QEMU_CONFDIR "/target-" TARGET_ARCH ".conf";
4999
        fp = fopen(fname, "r");
5000
        if (fp) {
5001
            if (qemu_config_parse(fp, fname) != 0) {
5002
                exit(1);
5003
            }
5004
            fclose(fp);
5005
        }
5006
    }
5007
#if defined(cpudef_setup)
5008
    cpudef_setup(); /* parse cpu definitions in target config file */
5009
#endif
5010

    
5011
    /* second pass of option parsing */
5012
    optind = 1;
5013
    for(;;) {
5014
        if (optind >= argc)
5015
            break;
5016
        if (argv[optind][0] != '-') {
5017
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
5018
        } else {
5019
            const QEMUOption *popt;
5020

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

    
5181
                    if (!strchr(optarg, '=')) {
5182
                        legacy = 1;
5183
                        pstrcpy(buf, sizeof(buf), optarg);
5184
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5185
                        fprintf(stderr,
5186
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5187
                                buf, optarg);
5188
                        exit(1);
5189
                    }
5190

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

    
5281
                value = strtoul(optarg, &ptr, 10);
5282
                switch (*ptr) {
5283
                case 0: case 'M': case 'm':
5284
                    value <<= 20;
5285
                    break;
5286
                case 'G': case 'g':
5287
                    value <<= 30;
5288
                    break;
5289
                default:
5290
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5291
                    exit(1);
5292
                }
5293

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

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

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

    
5713
    /* If no data_dir is specified then try to find it relative to the
5714
       executable path.  */
5715
    if (!data_dir) {
5716
        data_dir = find_datadir(argv[0]);
5717
    }
5718
    /* If all else fails use the install patch specified when building.  */
5719
    if (!data_dir) {
5720
        data_dir = CONFIG_QEMU_SHAREDIR;
5721
    }
5722

    
5723
    /*
5724
     * Default to max_cpus = smp_cpus, in case the user doesn't
5725
     * specify a max_cpus value.
5726
     */
5727
    if (!max_cpus)
5728
        max_cpus = smp_cpus;
5729

    
5730
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5731
    if (smp_cpus > machine->max_cpus) {
5732
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5733
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5734
                machine->max_cpus);
5735
        exit(1);
5736
    }
5737

    
5738
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5739
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5740

    
5741
    if (machine->no_serial) {
5742
        default_serial = 0;
5743
    }
5744
    if (machine->no_parallel) {
5745
        default_parallel = 0;
5746
    }
5747
    if (!machine->use_virtcon) {
5748
        default_virtcon = 0;
5749
    }
5750
    if (machine->no_vga) {
5751
        default_vga = 0;
5752
    }
5753
    if (machine->no_floppy) {
5754
        default_floppy = 0;
5755
    }
5756
    if (machine->no_cdrom) {
5757
        default_cdrom = 0;
5758
    }
5759
    if (machine->no_sdcard) {
5760
        default_sdcard = 0;
5761
    }
5762

    
5763
    if (display_type == DT_NOGRAPHIC) {
5764
        if (default_parallel)
5765
            add_device_config(DEV_PARALLEL, "null");
5766
        if (default_serial && default_monitor) {
5767
            add_device_config(DEV_SERIAL, "mon:stdio");
5768
        } else if (default_virtcon && default_monitor) {
5769
            add_device_config(DEV_VIRTCON, "mon:stdio");
5770
        } else {
5771
            if (default_serial)
5772
                add_device_config(DEV_SERIAL, "stdio");
5773
            if (default_virtcon)
5774
                add_device_config(DEV_VIRTCON, "stdio");
5775
            if (default_monitor)
5776
                monitor_parse("stdio", "readline");
5777
        }
5778
    } else {
5779
        if (default_serial)
5780
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5781
        if (default_parallel)
5782
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5783
        if (default_monitor)
5784
            monitor_parse("vc:80Cx24C", "readline");
5785
        if (default_virtcon)
5786
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5787
    }
5788
    if (default_vga)
5789
        vga_interface_type = VGA_CIRRUS;
5790

    
5791
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5792
        exit(1);
5793

    
5794
#ifndef _WIN32
5795
    if (daemonize) {
5796
        pid_t pid;
5797

    
5798
        if (pipe(fds) == -1)
5799
            exit(1);
5800

    
5801
        pid = fork();
5802
        if (pid > 0) {
5803
            uint8_t status;
5804
            ssize_t len;
5805

    
5806
            close(fds[1]);
5807

    
5808
        again:
5809
            len = read(fds[0], &status, 1);
5810
            if (len == -1 && (errno == EINTR))
5811
                goto again;
5812

    
5813
            if (len != 1)
5814
                exit(1);
5815
            else if (status == 1) {
5816
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5817
                exit(1);
5818
            } else
5819
                exit(0);
5820
        } else if (pid < 0)
5821
            exit(1);
5822

    
5823
        close(fds[0]);
5824
        qemu_set_cloexec(fds[1]);
5825

    
5826
        setsid();
5827

    
5828
        pid = fork();
5829
        if (pid > 0)
5830
            exit(0);
5831
        else if (pid < 0)
5832
            exit(1);
5833

    
5834
        umask(027);
5835

    
5836
        signal(SIGTSTP, SIG_IGN);
5837
        signal(SIGTTOU, SIG_IGN);
5838
        signal(SIGTTIN, SIG_IGN);
5839
    }
5840
#endif
5841

    
5842
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5843
#ifndef _WIN32
5844
        if (daemonize) {
5845
            uint8_t status = 1;
5846
            if (write(fds[1], &status, 1) != 1) {
5847
                perror("daemonize. Writing to pipe\n");
5848
            }
5849
        } else
5850
#endif
5851
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5852
        exit(1);
5853
    }
5854

    
5855
    if (kvm_enabled()) {
5856
        int ret;
5857

    
5858
        ret = kvm_init(smp_cpus);
5859
        if (ret < 0) {
5860
            fprintf(stderr, "failed to initialize KVM\n");
5861
            exit(1);
5862
        }
5863
    }
5864

    
5865
    if (qemu_init_main_loop()) {
5866
        fprintf(stderr, "qemu_init_main_loop failed\n");
5867
        exit(1);
5868
    }
5869
    linux_boot = (kernel_filename != NULL);
5870

    
5871
    if (!linux_boot && *kernel_cmdline != '\0') {
5872
        fprintf(stderr, "-append only allowed with -kernel option\n");
5873
        exit(1);
5874
    }
5875

    
5876
    if (!linux_boot && initrd_filename != NULL) {
5877
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5878
        exit(1);
5879
    }
5880

    
5881
#ifndef _WIN32
5882
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5883
    setvbuf(stdout, NULL, _IOLBF, 0);
5884
#endif
5885

    
5886
    if (init_timer_alarm() < 0) {
5887
        fprintf(stderr, "could not initialize alarm timer\n");
5888
        exit(1);
5889
    }
5890
    configure_icount(icount_option);
5891

    
5892
#ifdef _WIN32
5893
    socket_init();
5894
#endif
5895

    
5896
    if (net_init_clients() < 0) {
5897
        exit(1);
5898
    }
5899

    
5900
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5901
    net_set_boot_mask(net_boot);
5902

    
5903
    /* init the bluetooth world */
5904
    if (foreach_device_config(DEV_BT, bt_parse))
5905
        exit(1);
5906

    
5907
    /* init the memory */
5908
    if (ram_size == 0)
5909
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5910

    
5911
    /* init the dynamic translator */
5912
    cpu_exec_init_all(tb_size * 1024 * 1024);
5913

    
5914
    bdrv_init_with_whitelist();
5915

    
5916
    blk_mig_init();
5917

    
5918
    if (default_cdrom) {
5919
        /* we always create the cdrom drive, even if no disk is there */
5920
        drive_add(NULL, CDROM_ALIAS);
5921
    }
5922

    
5923
    if (default_floppy) {
5924
        /* we always create at least one floppy */
5925
        drive_add(NULL, FD_ALIAS, 0);
5926
    }
5927

    
5928
    if (default_sdcard) {
5929
        /* we always create one sd slot, even if no card is in it */
5930
        drive_add(NULL, SD_ALIAS);
5931
    }
5932

    
5933
    /* open the virtual block devices */
5934
    if (snapshot)
5935
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5936
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5937
        exit(1);
5938

    
5939
    vmstate_register(0, &vmstate_timers ,&timers_state);
5940
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5941
                         ram_load, NULL);
5942

    
5943
    if (nb_numa_nodes > 0) {
5944
        int i;
5945

    
5946
        if (nb_numa_nodes > smp_cpus) {
5947
            nb_numa_nodes = smp_cpus;
5948
        }
5949

    
5950
        /* If no memory size if given for any node, assume the default case
5951
         * and distribute the available memory equally across all nodes
5952
         */
5953
        for (i = 0; i < nb_numa_nodes; i++) {
5954
            if (node_mem[i] != 0)
5955
                break;
5956
        }
5957
        if (i == nb_numa_nodes) {
5958
            uint64_t usedmem = 0;
5959

    
5960
            /* On Linux, the each node's border has to be 8MB aligned,
5961
             * the final node gets the rest.
5962
             */
5963
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5964
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5965
                usedmem += node_mem[i];
5966
            }
5967
            node_mem[i] = ram_size - usedmem;
5968
        }
5969

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

    
5985
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5986
        exit(1);
5987
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5988
        exit(1);
5989
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5990
        exit(1);
5991
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5992
        exit(1);
5993

    
5994
    module_call_init(MODULE_INIT_DEVICE);
5995

    
5996
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5997
        exit(0);
5998

    
5999
    if (watchdog) {
6000
        i = select_watchdog(watchdog);
6001
        if (i > 0)
6002
            exit (i == 1 ? 1 : 0);
6003
    }
6004

    
6005
    if (machine->compat_props) {
6006
        qdev_prop_register_global_list(machine->compat_props);
6007
    }
6008
    qemu_add_globals();
6009

    
6010
    machine->init(ram_size, boot_devices,
6011
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6012

    
6013
    cpu_synchronize_all_post_init();
6014

    
6015
#ifndef _WIN32
6016
    /* must be after terminal init, SDL library changes signal handlers */
6017
    sighandler_setup();
6018
#endif
6019

    
6020
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
6021
        for (i = 0; i < nb_numa_nodes; i++) {
6022
            if (node_cpumask[i] & (1 << env->cpu_index)) {
6023
                env->numa_node = i;
6024
            }
6025
        }
6026
    }
6027

    
6028
    current_machine = machine;
6029

    
6030
    /* init USB devices */
6031
    if (usb_enabled) {
6032
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
6033
            exit(1);
6034
    }
6035

    
6036
    /* init generic devices */
6037
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6038
        exit(1);
6039

    
6040
    net_check_clients();
6041

    
6042
    /* just use the first displaystate for the moment */
6043
    ds = get_displaystate();
6044

    
6045
    if (display_type == DT_DEFAULT) {
6046
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6047
        display_type = DT_SDL;
6048
#else
6049
        display_type = DT_VNC;
6050
        vnc_display = "localhost:0,to=99";
6051
        show_vnc_port = 1;
6052
#endif
6053
    }
6054
        
6055

    
6056
    switch (display_type) {
6057
    case DT_NOGRAPHIC:
6058
        break;
6059
#if defined(CONFIG_CURSES)
6060
    case DT_CURSES:
6061
        curses_display_init(ds, full_screen);
6062
        break;
6063
#endif
6064
#if defined(CONFIG_SDL)
6065
    case DT_SDL:
6066
        sdl_display_init(ds, full_screen, no_frame);
6067
        break;
6068
#elif defined(CONFIG_COCOA)
6069
    case DT_SDL:
6070
        cocoa_display_init(ds, full_screen);
6071
        break;
6072
#endif
6073
    case DT_VNC:
6074
        vnc_display_init(ds);
6075
        if (vnc_display_open(ds, vnc_display) < 0)
6076
            exit(1);
6077

    
6078
        if (show_vnc_port) {
6079
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6080
        }
6081
        break;
6082
    default:
6083
        break;
6084
    }
6085
    dpy_resize(ds);
6086

    
6087
    dcl = ds->listeners;
6088
    while (dcl != NULL) {
6089
        if (dcl->dpy_refresh != NULL) {
6090
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6091
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6092
        }
6093
        dcl = dcl->next;
6094
    }
6095

    
6096
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6097
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6098
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6099
    }
6100

    
6101
    text_consoles_set_display(ds);
6102

    
6103
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6104
        exit(1);
6105

    
6106
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6107
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6108
                gdbstub_dev);
6109
        exit(1);
6110
    }
6111

    
6112
    qdev_machine_creation_done();
6113

    
6114
    if (rom_load_all() != 0) {
6115
        fprintf(stderr, "rom loading failed\n");
6116
        exit(1);
6117
    }
6118

    
6119
    qemu_system_reset();
6120
    if (loadvm) {
6121
        if (load_vmstate(loadvm) < 0) {
6122
            autostart = 0;
6123
        }
6124
    }
6125

    
6126
    if (incoming) {
6127
        qemu_start_incoming_migration(incoming);
6128
    } else if (autostart) {
6129
        vm_start();
6130
    }
6131

    
6132
#ifndef _WIN32
6133
    if (daemonize) {
6134
        uint8_t status = 0;
6135
        ssize_t len;
6136

    
6137
    again1:
6138
        len = write(fds[1], &status, 1);
6139
        if (len == -1 && (errno == EINTR))
6140
            goto again1;
6141

    
6142
        if (len != 1)
6143
            exit(1);
6144

    
6145
        if (chdir("/")) {
6146
            perror("not able to chdir to /");
6147
            exit(1);
6148
        }
6149
        TFR(fd = qemu_open("/dev/null", O_RDWR));
6150
        if (fd == -1)
6151
            exit(1);
6152
    }
6153

    
6154
    if (run_as) {
6155
        pwd = getpwnam(run_as);
6156
        if (!pwd) {
6157
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6158
            exit(1);
6159
        }
6160
    }
6161

    
6162
    if (chroot_dir) {
6163
        if (chroot(chroot_dir) < 0) {
6164
            fprintf(stderr, "chroot failed\n");
6165
            exit(1);
6166
        }
6167
        if (chdir("/")) {
6168
            perror("not able to chdir to /");
6169
            exit(1);
6170
        }
6171
    }
6172

    
6173
    if (run_as) {
6174
        if (setgid(pwd->pw_gid) < 0) {
6175
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6176
            exit(1);
6177
        }
6178
        if (setuid(pwd->pw_uid) < 0) {
6179
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6180
            exit(1);
6181
        }
6182
        if (setuid(0) != -1) {
6183
            fprintf(stderr, "Dropping privileges failed\n");
6184
            exit(1);
6185
        }
6186
    }
6187

    
6188
    if (daemonize) {
6189
        dup2(fd, 0);
6190
        dup2(fd, 1);
6191
        dup2(fd, 2);
6192

    
6193
        close(fd);
6194
    }
6195
#endif
6196

    
6197
    main_loop();
6198
    quit_timers();
6199
    net_cleanup();
6200

    
6201
    return 0;
6202
}