Statistics
| Branch: | Revision:

root / vl.c @ e2a7bb4b

History | View | Annotate | Download (157.4 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include <unistd.h>
25
#include <fcntl.h>
26
#include <signal.h>
27
#include <time.h>
28
#include <errno.h>
29
#include <sys/time.h>
30
#include <zlib.h>
31

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

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

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

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

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

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

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

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

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

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

    
161
#include "disas.h"
162

    
163
#include "exec-all.h"
164

    
165
#include "qemu_socket.h"
166

    
167
#include "slirp/libslirp.h"
168

    
169
#include "qemu-queue.h"
170

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

    
174
#define DEFAULT_RAM_SIZE 128
175

    
176
#define MAX_VIRTIO_CONSOLES 1
177

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

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

    
259
static CPUState *cur_cpu;
260
static CPUState *next_cpu;
261
/* 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 inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
605
{
606
    return !!t->rearm;
607
}
608

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

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

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

    
620
static struct qemu_alarm_timer *alarm_timer;
621

    
622
#ifdef _WIN32
623

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

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

    
633
#else
634

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

    
638
#ifdef __linux__
639

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

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

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

    
650
#endif /* __linux__ */
651

    
652
#endif /* _WIN32 */
653

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

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

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

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

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

    
704
static void configure_icount(const char *option)
705
{
706
    if (!option)
707
        return;
708

    
709
    if (strcmp(option, "auto") != 0) {
710
        icount_time_shift = strtol(option, NULL, 0);
711
        use_icount = 1;
712
        return;
713
    }
714

    
715
    use_icount = 2;
716

    
717
    /* 125MIPS seems a reasonable initial guess at the guest speed.
718
       It will be corrected fairly quickly anyway.  */
719
    icount_time_shift = 3;
720

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

    
734
static int64_t qemu_icount_round(int64_t count)
735
{
736
    return (count + (1 << icount_time_shift) - 1) >> icount_time_shift;
737
}
738

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

    
759
static void show_available_alarms(void)
760
{
761
    int i;
762

    
763
    printf("Available alarm timers, in order of precedence:\n");
764
    for (i = 0; alarm_timers[i].name; i++)
765
        printf("%s\n", alarm_timers[i].name);
766
}
767

    
768
static void configure_alarms(char const *opt)
769
{
770
    int i;
771
    int cur = 0;
772
    int count = ARRAY_SIZE(alarm_timers) - 1;
773
    char *arg;
774
    char *name;
775
    struct qemu_alarm_timer tmp;
776

    
777
    if (!strcmp(opt, "?")) {
778
        show_available_alarms();
779
        exit(0);
780
    }
781

    
782
    arg = qemu_strdup(opt);
783

    
784
    /* Reorder the array */
785
    name = strtok(arg, ",");
786
    while (name) {
787
        for (i = 0; i < count && alarm_timers[i].name; i++) {
788
            if (!strcmp(alarm_timers[i].name, name))
789
                break;
790
        }
791

    
792
        if (i == count) {
793
            fprintf(stderr, "Unknown clock %s\n", name);
794
            goto next;
795
        }
796

    
797
        if (i < cur)
798
            /* Ignore */
799
            goto next;
800

    
801
        /* Swap */
802
        tmp = alarm_timers[i];
803
        alarm_timers[i] = alarm_timers[cur];
804
        alarm_timers[cur] = tmp;
805

    
806
        cur++;
807
next:
808
        name = strtok(NULL, ",");
809
    }
810

    
811
    qemu_free(arg);
812

    
813
    if (cur) {
814
        /* Disable remaining timers */
815
        for (i = cur; i < count; i++)
816
            alarm_timers[i].name = NULL;
817
    } else {
818
        show_available_alarms();
819
        exit(1);
820
    }
821
}
822

    
823
#define QEMU_NUM_CLOCKS 3
824

    
825
QEMUClock *rt_clock;
826
QEMUClock *vm_clock;
827
QEMUClock *host_clock;
828

    
829
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
830

    
831
static QEMUClock *qemu_new_clock(int type)
832
{
833
    QEMUClock *clock;
834
    clock = qemu_mallocz(sizeof(QEMUClock));
835
    clock->type = type;
836
    clock->enabled = 1;
837
    return clock;
838
}
839

    
840
static void qemu_clock_enable(QEMUClock *clock, int enabled)
841
{
842
    clock->enabled = enabled;
843
}
844

    
845
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
846
{
847
    QEMUTimer *ts;
848

    
849
    ts = qemu_mallocz(sizeof(QEMUTimer));
850
    ts->clock = clock;
851
    ts->cb = cb;
852
    ts->opaque = opaque;
853
    return ts;
854
}
855

    
856
void qemu_free_timer(QEMUTimer *ts)
857
{
858
    qemu_free(ts);
859
}
860

    
861
/* stop a timer, but do not dealloc it */
862
void qemu_del_timer(QEMUTimer *ts)
863
{
864
    QEMUTimer **pt, *t;
865

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

    
881
/* modify the current timer so that it will be fired when current_time
882
   >= expire_time. The corresponding callback will be called. */
883
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
884
{
885
    QEMUTimer **pt, *t;
886

    
887
    qemu_del_timer(ts);
888

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

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

    
916
int qemu_timer_pending(QEMUTimer *ts)
917
{
918
    QEMUTimer *t;
919
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
920
        if (t == ts)
921
            return 1;
922
    }
923
    return 0;
924
}
925

    
926
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
927
{
928
    if (!timer_head)
929
        return 0;
930
    return (timer_head->expire_time <= current_time);
931
}
932

    
933
static void qemu_run_timers(QEMUClock *clock)
934
{
935
    QEMUTimer **ptimer_head, *ts;
936
    int64_t current_time;
937
   
938
    if (!clock->enabled)
939
        return;
940

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

    
951
        /* run the callback (the timer list can be modified) */
952
        ts->cb(ts->opaque);
953
    }
954
}
955

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

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

    
990
static void init_clocks(void)
991
{
992
    init_get_clock();
993
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
994
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
995
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
996

    
997
    rtc_clock = host_clock;
998
}
999

    
1000
/* save a timer */
1001
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1002
{
1003
    uint64_t expire_time;
1004

    
1005
    if (qemu_timer_pending(ts)) {
1006
        expire_time = ts->expire_time;
1007
    } else {
1008
        expire_time = -1;
1009
    }
1010
    qemu_put_be64(f, expire_time);
1011
}
1012

    
1013
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1014
{
1015
    uint64_t expire_time;
1016

    
1017
    expire_time = qemu_get_be64(f);
1018
    if (expire_time != -1) {
1019
        qemu_mod_timer(ts, expire_time);
1020
    } else {
1021
        qemu_del_timer(ts);
1022
    }
1023
}
1024

    
1025
static const VMStateDescription vmstate_timers = {
1026
    .name = "timer",
1027
    .version_id = 2,
1028
    .minimum_version_id = 1,
1029
    .minimum_version_id_old = 1,
1030
    .fields      = (VMStateField []) {
1031
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
1032
        VMSTATE_INT64(dummy, TimersState),
1033
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1034
        VMSTATE_END_OF_LIST()
1035
    }
1036
};
1037

    
1038
static void qemu_run_all_timers(void)
1039
{
1040
    /* rearm timer, if not periodic */
1041
    if (alarm_timer->expired) {
1042
        alarm_timer->expired = 0;
1043
        qemu_rearm_alarm_timer(alarm_timer);
1044
    }
1045

    
1046
    alarm_timer->pending = 0;
1047

    
1048
    /* vm time timers */
1049
    if (vm_running) {
1050
        qemu_run_timers(vm_clock);
1051
    }
1052

    
1053
    qemu_run_timers(rt_clock);
1054
    qemu_run_timers(host_clock);
1055
}
1056

    
1057
#ifdef _WIN32
1058
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1059
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1060
                                        DWORD_PTR dw2)
1061
#else
1062
static void host_alarm_handler(int host_signum)
1063
#endif
1064
{
1065
    struct qemu_alarm_timer *t = alarm_timer;
1066
    if (!t)
1067
        return;
1068

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

    
1107
        t->expired = alarm_has_dynticks(t);
1108
        t->pending = 1;
1109
        qemu_notify_event();
1110
    }
1111
}
1112

    
1113
static int64_t qemu_next_deadline(void)
1114
{
1115
    /* To avoid problems with overflow limit this to 2^32.  */
1116
    int64_t delta = INT32_MAX;
1117

    
1118
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1119
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1120
                     qemu_get_clock(vm_clock);
1121
    }
1122
    if (active_timers[QEMU_CLOCK_HOST]) {
1123
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1124
                 qemu_get_clock(host_clock);
1125
        if (hdelta < delta)
1126
            delta = hdelta;
1127
    }
1128

    
1129
    if (delta < 0)
1130
        delta = 0;
1131

    
1132
    return delta;
1133
}
1134

    
1135
#if defined(__linux__)
1136
static uint64_t qemu_next_deadline_dyntick(void)
1137
{
1138
    int64_t delta;
1139
    int64_t rtdelta;
1140

    
1141
    if (use_icount)
1142
        delta = INT32_MAX;
1143
    else
1144
        delta = (qemu_next_deadline() + 999) / 1000;
1145

    
1146
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1147
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1148
                 qemu_get_clock(rt_clock))*1000;
1149
        if (rtdelta < delta)
1150
            delta = rtdelta;
1151
    }
1152

    
1153
    if (delta < MIN_TIMER_REARM_US)
1154
        delta = MIN_TIMER_REARM_US;
1155

    
1156
    return delta;
1157
}
1158
#endif
1159

    
1160
#ifndef _WIN32
1161

    
1162
/* Sets a specific flag */
1163
static int fcntl_setfl(int fd, int flag)
1164
{
1165
    int flags;
1166

    
1167
    flags = fcntl(fd, F_GETFL);
1168
    if (flags == -1)
1169
        return -errno;
1170

    
1171
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1172
        return -errno;
1173

    
1174
    return 0;
1175
}
1176

    
1177
#if defined(__linux__)
1178

    
1179
#define RTC_FREQ 1024
1180

    
1181
static void enable_sigio_timer(int fd)
1182
{
1183
    struct sigaction act;
1184

    
1185
    /* timer signal */
1186
    sigfillset(&act.sa_mask);
1187
    act.sa_flags = 0;
1188
    act.sa_handler = host_alarm_handler;
1189

    
1190
    sigaction(SIGIO, &act, NULL);
1191
    fcntl_setfl(fd, O_ASYNC);
1192
    fcntl(fd, F_SETOWN, getpid());
1193
}
1194

    
1195
static int hpet_start_timer(struct qemu_alarm_timer *t)
1196
{
1197
    struct hpet_info info;
1198
    int r, fd;
1199

    
1200
    fd = qemu_open("/dev/hpet", O_RDONLY);
1201
    if (fd < 0)
1202
        return -1;
1203

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

    
1213
    /* Check capabilities */
1214
    r = ioctl(fd, HPET_INFO, &info);
1215
    if (r < 0)
1216
        goto fail;
1217

    
1218
    /* Enable periodic mode */
1219
    r = ioctl(fd, HPET_EPI, 0);
1220
    if (info.hi_flags && (r < 0))
1221
        goto fail;
1222

    
1223
    /* Enable interrupt */
1224
    r = ioctl(fd, HPET_IE_ON, 0);
1225
    if (r < 0)
1226
        goto fail;
1227

    
1228
    enable_sigio_timer(fd);
1229
    t->priv = (void *)(long)fd;
1230

    
1231
    return 0;
1232
fail:
1233
    close(fd);
1234
    return -1;
1235
}
1236

    
1237
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1238
{
1239
    int fd = (long)t->priv;
1240

    
1241
    close(fd);
1242
}
1243

    
1244
static int rtc_start_timer(struct qemu_alarm_timer *t)
1245
{
1246
    int rtc_fd;
1247
    unsigned long current_rtc_freq = 0;
1248

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

    
1266
    enable_sigio_timer(rtc_fd);
1267

    
1268
    t->priv = (void *)(long)rtc_fd;
1269

    
1270
    return 0;
1271
}
1272

    
1273
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1274
{
1275
    int rtc_fd = (long)t->priv;
1276

    
1277
    close(rtc_fd);
1278
}
1279

    
1280
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1281
{
1282
    struct sigevent ev;
1283
    timer_t host_timer;
1284
    struct sigaction act;
1285

    
1286
    sigfillset(&act.sa_mask);
1287
    act.sa_flags = 0;
1288
    act.sa_handler = host_alarm_handler;
1289

    
1290
    sigaction(SIGALRM, &act, NULL);
1291

    
1292
    /* 
1293
     * Initialize ev struct to 0 to avoid valgrind complaining
1294
     * about uninitialized data in timer_create call
1295
     */
1296
    memset(&ev, 0, sizeof(ev));
1297
    ev.sigev_value.sival_int = 0;
1298
    ev.sigev_notify = SIGEV_SIGNAL;
1299
    ev.sigev_signo = SIGALRM;
1300

    
1301
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1302
        perror("timer_create");
1303

    
1304
        /* disable dynticks */
1305
        fprintf(stderr, "Dynamic Ticks disabled\n");
1306

    
1307
        return -1;
1308
    }
1309

    
1310
    t->priv = (void *)(long)host_timer;
1311

    
1312
    return 0;
1313
}
1314

    
1315
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1316
{
1317
    timer_t host_timer = (timer_t)(long)t->priv;
1318

    
1319
    timer_delete(host_timer);
1320
}
1321

    
1322
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1323
{
1324
    timer_t host_timer = (timer_t)(long)t->priv;
1325
    struct itimerspec timeout;
1326
    int64_t nearest_delta_us = INT64_MAX;
1327
    int64_t current_us;
1328

    
1329
    assert(alarm_has_dynticks(t));
1330
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1331
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1332
        !active_timers[QEMU_CLOCK_HOST])
1333
        return;
1334

    
1335
    nearest_delta_us = qemu_next_deadline_dyntick();
1336

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

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

    
1358
#endif /* defined(__linux__) */
1359

    
1360
static int unix_start_timer(struct qemu_alarm_timer *t)
1361
{
1362
    struct sigaction act;
1363
    struct itimerval itv;
1364
    int err;
1365

    
1366
    /* timer signal */
1367
    sigfillset(&act.sa_mask);
1368
    act.sa_flags = 0;
1369
    act.sa_handler = host_alarm_handler;
1370

    
1371
    sigaction(SIGALRM, &act, NULL);
1372

    
1373
    itv.it_interval.tv_sec = 0;
1374
    /* for i386 kernel 2.6 to get 1 ms */
1375
    itv.it_interval.tv_usec = 999;
1376
    itv.it_value.tv_sec = 0;
1377
    itv.it_value.tv_usec = 10 * 1000;
1378

    
1379
    err = setitimer(ITIMER_REAL, &itv, NULL);
1380
    if (err)
1381
        return -1;
1382

    
1383
    return 0;
1384
}
1385

    
1386
static void unix_stop_timer(struct qemu_alarm_timer *t)
1387
{
1388
    struct itimerval itv;
1389

    
1390
    memset(&itv, 0, sizeof(itv));
1391
    setitimer(ITIMER_REAL, &itv, NULL);
1392
}
1393

    
1394
#endif /* !defined(_WIN32) */
1395

    
1396

    
1397
#ifdef _WIN32
1398

    
1399
static int win32_start_timer(struct qemu_alarm_timer *t)
1400
{
1401
    TIMECAPS tc;
1402
    struct qemu_alarm_win32 *data = t->priv;
1403
    UINT flags;
1404

    
1405
    memset(&tc, 0, sizeof(tc));
1406
    timeGetDevCaps(&tc, sizeof(tc));
1407

    
1408
    data->period = tc.wPeriodMin;
1409
    timeBeginPeriod(data->period);
1410

    
1411
    flags = TIME_CALLBACK_FUNCTION;
1412
    if (alarm_has_dynticks(t))
1413
        flags |= TIME_ONESHOT;
1414
    else
1415
        flags |= TIME_PERIODIC;
1416

    
1417
    data->timerId = timeSetEvent(1,         // interval (ms)
1418
                        data->period,       // resolution
1419
                        host_alarm_handler, // function
1420
                        (DWORD)t,           // parameter
1421
                        flags);
1422

    
1423
    if (!data->timerId) {
1424
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1425
                GetLastError());
1426
        timeEndPeriod(data->period);
1427
        return -1;
1428
    }
1429

    
1430
    return 0;
1431
}
1432

    
1433
static void win32_stop_timer(struct qemu_alarm_timer *t)
1434
{
1435
    struct qemu_alarm_win32 *data = t->priv;
1436

    
1437
    timeKillEvent(data->timerId);
1438
    timeEndPeriod(data->period);
1439
}
1440

    
1441
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1442
{
1443
    struct qemu_alarm_win32 *data = t->priv;
1444

    
1445
    assert(alarm_has_dynticks(t));
1446
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1447
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1448
        !active_timers[QEMU_CLOCK_HOST])
1449
        return;
1450

    
1451
    timeKillEvent(data->timerId);
1452

    
1453
    data->timerId = timeSetEvent(1,
1454
                        data->period,
1455
                        host_alarm_handler,
1456
                        (DWORD)t,
1457
                        TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
1458

    
1459
    if (!data->timerId) {
1460
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1461
                GetLastError());
1462

    
1463
        timeEndPeriod(data->period);
1464
        exit(1);
1465
    }
1466
}
1467

    
1468
#endif /* _WIN32 */
1469

    
1470
static void alarm_timer_on_change_state_rearm(void *opaque, int running, int reason)
1471
{
1472
    if (running)
1473
        qemu_rearm_alarm_timer((struct qemu_alarm_timer *) opaque);
1474
}
1475

    
1476
static int init_timer_alarm(void)
1477
{
1478
    struct qemu_alarm_timer *t = NULL;
1479
    int i, err = -1;
1480

    
1481
    for (i = 0; alarm_timers[i].name; i++) {
1482
        t = &alarm_timers[i];
1483

    
1484
        err = t->start(t);
1485
        if (!err)
1486
            break;
1487
    }
1488

    
1489
    if (err) {
1490
        err = -ENOENT;
1491
        goto fail;
1492
    }
1493

    
1494
    /* first event is at time 0 */
1495
    t->pending = 1;
1496
    alarm_timer = t;
1497
    qemu_add_vm_change_state_handler(alarm_timer_on_change_state_rearm, t);
1498

    
1499
    return 0;
1500

    
1501
fail:
1502
    return err;
1503
}
1504

    
1505
static void quit_timers(void)
1506
{
1507
    struct qemu_alarm_timer *t = alarm_timer;
1508
    alarm_timer = NULL;
1509
    t->stop(t);
1510
}
1511

    
1512
/***********************************************************/
1513
/* host time/date access */
1514
void qemu_get_timedate(struct tm *tm, int offset)
1515
{
1516
    time_t ti;
1517
    struct tm *ret;
1518

    
1519
    time(&ti);
1520
    ti += offset;
1521
    if (rtc_date_offset == -1) {
1522
        if (rtc_utc)
1523
            ret = gmtime(&ti);
1524
        else
1525
            ret = localtime(&ti);
1526
    } else {
1527
        ti -= rtc_date_offset;
1528
        ret = gmtime(&ti);
1529
    }
1530

    
1531
    memcpy(tm, ret, sizeof(struct tm));
1532
}
1533

    
1534
int qemu_timedate_diff(struct tm *tm)
1535
{
1536
    time_t seconds;
1537

    
1538
    if (rtc_date_offset == -1)
1539
        if (rtc_utc)
1540
            seconds = mktimegm(tm);
1541
        else
1542
            seconds = mktime(tm);
1543
    else
1544
        seconds = mktimegm(tm) + rtc_date_offset;
1545

    
1546
    return seconds - time(NULL);
1547
}
1548

    
1549
void rtc_change_mon_event(struct tm *tm)
1550
{
1551
    QObject *data;
1552

    
1553
    data = qobject_from_jsonf("{ 'offset': %d }", qemu_timedate_diff(tm));
1554
    monitor_protocol_event(QEVENT_RTC_CHANGE, data);
1555
    qobject_decref(data);
1556
}
1557

    
1558
static void configure_rtc_date_offset(const char *startdate, int legacy)
1559
{
1560
    time_t rtc_start_date;
1561
    struct tm tm;
1562

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

    
1597
static void configure_rtc(QemuOpts *opts)
1598
{
1599
    const char *value;
1600

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

    
1637
#ifdef _WIN32
1638
static void socket_cleanup(void)
1639
{
1640
    WSACleanup();
1641
}
1642

    
1643
static int socket_init(void)
1644
{
1645
    WSADATA Data;
1646
    int ret, err;
1647

    
1648
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1649
    if (ret != 0) {
1650
        err = WSAGetLastError();
1651
        fprintf(stderr, "WSAStartup: %d\n", err);
1652
        return -1;
1653
    }
1654
    atexit(socket_cleanup);
1655
    return 0;
1656
}
1657
#endif
1658

    
1659
/***********************************************************/
1660
/* Bluetooth support */
1661
static int nb_hcis;
1662
static int cur_hci;
1663
static struct HCIInfo *hci_table[MAX_NICS];
1664

    
1665
static struct bt_vlan_s {
1666
    struct bt_scatternet_s net;
1667
    int id;
1668
    struct bt_vlan_s *next;
1669
} *first_bt_vlan;
1670

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

    
1688
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1689
{
1690
}
1691

    
1692
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1693
{
1694
    return -ENOTSUP;
1695
}
1696

    
1697
static struct HCIInfo null_hci = {
1698
    .cmd_send = null_hci_send,
1699
    .sco_send = null_hci_send,
1700
    .acl_send = null_hci_send,
1701
    .bdaddr_set = null_hci_addr_set,
1702
};
1703

    
1704
struct HCIInfo *qemu_next_hci(void)
1705
{
1706
    if (cur_hci == nb_hcis)
1707
        return &null_hci;
1708

    
1709
    return hci_table[cur_hci++];
1710
}
1711

    
1712
static struct HCIInfo *hci_init(const char *str)
1713
{
1714
    char *endp;
1715
    struct bt_scatternet_s *vlan = 0;
1716

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

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

    
1739
    return 0;
1740
}
1741

    
1742
static int bt_hci_parse(const char *str)
1743
{
1744
    struct HCIInfo *hci;
1745
    bdaddr_t bdaddr;
1746

    
1747
    if (nb_hcis >= MAX_NICS) {
1748
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1749
        return -1;
1750
    }
1751

    
1752
    hci = hci_init(str);
1753
    if (!hci)
1754
        return -1;
1755

    
1756
    bdaddr.b[0] = 0x52;
1757
    bdaddr.b[1] = 0x54;
1758
    bdaddr.b[2] = 0x00;
1759
    bdaddr.b[3] = 0x12;
1760
    bdaddr.b[4] = 0x34;
1761
    bdaddr.b[5] = 0x56 + nb_hcis;
1762
    hci->bdaddr_set(hci, bdaddr.b);
1763

    
1764
    hci_table[nb_hcis++] = hci;
1765

    
1766
    return 0;
1767
}
1768

    
1769
static void bt_vhci_add(int vlan_id)
1770
{
1771
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1772

    
1773
    if (!vlan->slave)
1774
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1775
                        "an empty scatternet %i\n", vlan_id);
1776

    
1777
    bt_vhci_init(bt_new_hci(vlan));
1778
}
1779

    
1780
static struct bt_device_s *bt_device_add(const char *opt)
1781
{
1782
    struct bt_scatternet_s *vlan;
1783
    int vlan_id = 0;
1784
    char *endp = strstr(opt, ",vlan=");
1785
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1786
    char devname[10];
1787

    
1788
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1789

    
1790
    if (endp) {
1791
        vlan_id = strtol(endp + 6, &endp, 0);
1792
        if (*endp) {
1793
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1794
            return 0;
1795
        }
1796
    }
1797

    
1798
    vlan = qemu_find_bt_vlan(vlan_id);
1799

    
1800
    if (!vlan->slave)
1801
        fprintf(stderr, "qemu: warning: adding a slave device to "
1802
                        "an empty scatternet %i\n", vlan_id);
1803

    
1804
    if (!strcmp(devname, "keyboard"))
1805
        return bt_keyboard_init(vlan);
1806

    
1807
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1808
    return 0;
1809
}
1810

    
1811
static int bt_parse(const char *opt)
1812
{
1813
    const char *endp, *p;
1814
    int vlan;
1815

    
1816
    if (strstart(opt, "hci", &endp)) {
1817
        if (!*endp || *endp == ',') {
1818
            if (*endp)
1819
                if (!strstart(endp, ",vlan=", 0))
1820
                    opt = endp + 1;
1821

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

    
1840
            bt_vhci_add(vlan);
1841
            return 0;
1842
        }
1843
    } else if (strstart(opt, "device:", &endp))
1844
        return !bt_device_add(endp);
1845

    
1846
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1847
    return 1;
1848
}
1849

    
1850
/***********************************************************/
1851
/* QEMU Block devices */
1852

    
1853
#define HD_ALIAS "index=%d,media=disk"
1854
#define CDROM_ALIAS "index=2,media=cdrom"
1855
#define FD_ALIAS "index=%d,if=floppy"
1856
#define PFLASH_ALIAS "if=pflash"
1857
#define MTD_ALIAS "if=mtd"
1858
#define SD_ALIAS "index=0,if=sd"
1859

    
1860
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1861
{
1862
    va_list ap;
1863
    char optstr[1024];
1864
    QemuOpts *opts;
1865

    
1866
    va_start(ap, fmt);
1867
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1868
    va_end(ap);
1869

    
1870
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, 0);
1871
    if (!opts) {
1872
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1873
                __FUNCTION__, optstr);
1874
        return NULL;
1875
    }
1876
    if (file)
1877
        qemu_opt_set(opts, "file", file);
1878
    return opts;
1879
}
1880

    
1881
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1882
{
1883
    DriveInfo *dinfo;
1884

    
1885
    /* seek interface, bus and unit */
1886

    
1887
    QTAILQ_FOREACH(dinfo, &drives, next) {
1888
        if (dinfo->type == type &&
1889
            dinfo->bus == bus &&
1890
            dinfo->unit == unit)
1891
            return dinfo;
1892
    }
1893

    
1894
    return NULL;
1895
}
1896

    
1897
DriveInfo *drive_get_by_id(const char *id)
1898
{
1899
    DriveInfo *dinfo;
1900

    
1901
    QTAILQ_FOREACH(dinfo, &drives, next) {
1902
        if (strcmp(id, dinfo->id))
1903
            continue;
1904
        return dinfo;
1905
    }
1906
    return NULL;
1907
}
1908

    
1909
int drive_get_max_bus(BlockInterfaceType type)
1910
{
1911
    int max_bus;
1912
    DriveInfo *dinfo;
1913

    
1914
    max_bus = -1;
1915
    QTAILQ_FOREACH(dinfo, &drives, next) {
1916
        if(dinfo->type == type &&
1917
           dinfo->bus > max_bus)
1918
            max_bus = dinfo->bus;
1919
    }
1920
    return max_bus;
1921
}
1922

    
1923
const char *drive_get_serial(BlockDriverState *bdrv)
1924
{
1925
    DriveInfo *dinfo;
1926

    
1927
    QTAILQ_FOREACH(dinfo, &drives, next) {
1928
        if (dinfo->bdrv == bdrv)
1929
            return dinfo->serial;
1930
    }
1931

    
1932
    return "\0";
1933
}
1934

    
1935
BlockInterfaceErrorAction drive_get_on_error(
1936
    BlockDriverState *bdrv, int is_read)
1937
{
1938
    DriveInfo *dinfo;
1939

    
1940
    QTAILQ_FOREACH(dinfo, &drives, next) {
1941
        if (dinfo->bdrv == bdrv)
1942
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1943
    }
1944

    
1945
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1946
}
1947

    
1948
static void bdrv_format_print(void *opaque, const char *name)
1949
{
1950
    fprintf(stderr, " %s", name);
1951
}
1952

    
1953
void drive_uninit(DriveInfo *dinfo)
1954
{
1955
    qemu_opts_del(dinfo->opts);
1956
    bdrv_delete(dinfo->bdrv);
1957
    QTAILQ_REMOVE(&drives, dinfo, next);
1958
    qemu_free(dinfo);
1959
}
1960

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

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

    
2003
    *fatal_error = 1;
2004

    
2005
    translation = BIOS_ATA_TRANSLATION_AUTO;
2006
    cache = 1;
2007

    
2008
    if (machine && machine->use_scsi) {
2009
        type = IF_SCSI;
2010
        max_devs = MAX_SCSI_DEVS;
2011
        pstrcpy(devname, sizeof(devname), "scsi");
2012
    } else {
2013
        type = IF_IDE;
2014
        max_devs = MAX_IDE_DEVS;
2015
        pstrcpy(devname, sizeof(devname), "ide");
2016
    }
2017
    media = MEDIA_DISK;
2018

    
2019
    /* extract parameters */
2020
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
2021
    unit_id = qemu_opt_get_number(opts, "unit", -1);
2022
    index   = qemu_opt_get_number(opts, "index", -1);
2023

    
2024
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
2025
    heads = qemu_opt_get_number(opts, "heads", 0);
2026
    secs  = qemu_opt_get_number(opts, "secs", 0);
2027

    
2028
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2029
    ro = qemu_opt_get_bool(opts, "readonly", 0);
2030

    
2031
    file = qemu_opt_get(opts, "file");
2032
    serial = qemu_opt_get(opts, "serial");
2033

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

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

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

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

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

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

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

    
2159
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2160
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2161
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2162
            fprintf(stderr, "werror is no supported by this format\n");
2163
            return NULL;
2164
        }
2165

    
2166
        on_write_error = parse_block_error_action(buf, 0);
2167
        if (on_write_error < 0) {
2168
            return NULL;
2169
        }
2170
    }
2171

    
2172
    on_read_error = BLOCK_ERR_REPORT;
2173
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2174
        if (type != IF_IDE && type != IF_VIRTIO) {
2175
            fprintf(stderr, "rerror is no supported by this format\n");
2176
            return NULL;
2177
        }
2178

    
2179
        on_read_error = parse_block_error_action(buf, 1);
2180
        if (on_read_error < 0) {
2181
            return NULL;
2182
        }
2183
    }
2184

    
2185
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2186
        if (type != IF_VIRTIO) {
2187
            fprintf(stderr, "addr is not supported\n");
2188
            return NULL;
2189
        }
2190
    }
2191

    
2192
    /* compute bus and unit according index */
2193

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

    
2210
    /* if user doesn't specify a unit_id,
2211
     * try to find the first free
2212
     */
2213

    
2214
    if (unit_id == -1) {
2215
       unit_id = 0;
2216
       while (drive_get(type, bus_id, unit_id) != NULL) {
2217
           unit_id++;
2218
           if (max_devs && unit_id >= max_devs) {
2219
               unit_id -= max_devs;
2220
               bus_id++;
2221
           }
2222
       }
2223
    }
2224

    
2225
    /* check unit id */
2226

    
2227
    if (max_devs && unit_id >= max_devs) {
2228
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2229
                unit_id, max_devs - 1);
2230
        return NULL;
2231
    }
2232

    
2233
    /*
2234
     * ignore multiple definitions
2235
     */
2236

    
2237
    if (drive_get(type, bus_id, unit_id) != NULL) {
2238
        *fatal_error = 0;
2239
        return NULL;
2240
    }
2241

    
2242
    /* init */
2243

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

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

    
2322
    if (aio == 1) {
2323
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2324
    } else {
2325
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2326
    }
2327

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

    
2343
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2344
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2345
                        file, strerror(errno));
2346
        return NULL;
2347
    }
2348

    
2349
    if (bdrv_key_required(dinfo->bdrv))
2350
        autostart = 0;
2351
    *fatal_error = 0;
2352
    return dinfo;
2353
}
2354

    
2355
static int drive_init_func(QemuOpts *opts, void *opaque)
2356
{
2357
    QEMUMachine *machine = opaque;
2358
    int fatal_error = 0;
2359

    
2360
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2361
        if (fatal_error)
2362
            return 1;
2363
    }
2364
    return 0;
2365
}
2366

    
2367
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2368
{
2369
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2370
        qemu_opt_set(opts, "snapshot", "on");
2371
    }
2372
    return 0;
2373
}
2374

    
2375
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2376
{
2377
    boot_set_handler = func;
2378
    boot_set_opaque = opaque;
2379
}
2380

    
2381
int qemu_boot_set(const char *boot_devices)
2382
{
2383
    if (!boot_set_handler) {
2384
        return -EINVAL;
2385
    }
2386
    return boot_set_handler(boot_set_opaque, boot_devices);
2387
}
2388

    
2389
static int parse_bootdevices(char *devices)
2390
{
2391
    /* We just do some generic consistency checks */
2392
    const char *p;
2393
    int bitmap = 0;
2394

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

    
2418
static void restore_boot_devices(void *opaque)
2419
{
2420
    char *standard_boot_devices = opaque;
2421

    
2422
    qemu_boot_set(standard_boot_devices);
2423

    
2424
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2425
    qemu_free(standard_boot_devices);
2426
}
2427

    
2428
static void numa_add(const char *optarg)
2429
{
2430
    char option[128];
2431
    char *endptr;
2432
    unsigned long long value, endvalue;
2433
    int nodenr;
2434

    
2435
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2436
    if (!strcmp(option, "node")) {
2437
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2438
            nodenr = nb_numa_nodes;
2439
        } else {
2440
            nodenr = strtoull(option, NULL, 10);
2441
        }
2442

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

    
2484
static void smp_parse(const char *optarg)
2485
{
2486
    int smp, sockets = 0, threads = 0, cores = 0;
2487
    char *endptr;
2488
    char option[128];
2489

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

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

    
2530
/***********************************************************/
2531
/* USB devices */
2532

    
2533
static int usb_device_add(const char *devname, int is_hotplug)
2534
{
2535
    const char *p;
2536
    USBDevice *dev = NULL;
2537

    
2538
    if (!usb_enabled)
2539
        return -1;
2540

    
2541
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2542
    dev = usbdevice_create(devname);
2543
    if (dev)
2544
        goto done;
2545

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

    
2558
done:
2559
    return 0;
2560
}
2561

    
2562
static int usb_device_del(const char *devname)
2563
{
2564
    int bus_num, addr;
2565
    const char *p;
2566

    
2567
    if (strstart(devname, "host:", &p))
2568
        return usb_host_device_close(p);
2569

    
2570
    if (!usb_enabled)
2571
        return -1;
2572

    
2573
    p = strchr(devname, '.');
2574
    if (!p)
2575
        return -1;
2576
    bus_num = strtoul(devname, NULL, 0);
2577
    addr = strtoul(p + 1, NULL, 0);
2578

    
2579
    return usb_device_delete_addr(bus_num, addr);
2580
}
2581

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

    
2592
void do_usb_add(Monitor *mon, const QDict *qdict)
2593
{
2594
    const char *devname = qdict_get_str(qdict, "devname");
2595
    if (usb_device_add(devname, 1) < 0) {
2596
        error_report("could not add USB device '%s'", devname);
2597
    }
2598
}
2599

    
2600
void do_usb_del(Monitor *mon, const QDict *qdict)
2601
{
2602
    const char *devname = qdict_get_str(qdict, "devname");
2603
    if (usb_device_del(devname) < 0) {
2604
        error_report("could not delete USB device '%s'", devname);
2605
    }
2606
}
2607

    
2608
/***********************************************************/
2609
/* PCMCIA/Cardbus */
2610

    
2611
static struct pcmcia_socket_entry_s {
2612
    PCMCIASocket *socket;
2613
    struct pcmcia_socket_entry_s *next;
2614
} *pcmcia_sockets = 0;
2615

    
2616
void pcmcia_socket_register(PCMCIASocket *socket)
2617
{
2618
    struct pcmcia_socket_entry_s *entry;
2619

    
2620
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2621
    entry->socket = socket;
2622
    entry->next = pcmcia_sockets;
2623
    pcmcia_sockets = entry;
2624
}
2625

    
2626
void pcmcia_socket_unregister(PCMCIASocket *socket)
2627
{
2628
    struct pcmcia_socket_entry_s *entry, **ptr;
2629

    
2630
    ptr = &pcmcia_sockets;
2631
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2632
        if (entry->socket == socket) {
2633
            *ptr = entry->next;
2634
            qemu_free(entry);
2635
        }
2636
}
2637

    
2638
void pcmcia_info(Monitor *mon)
2639
{
2640
    struct pcmcia_socket_entry_s *iter;
2641

    
2642
    if (!pcmcia_sockets)
2643
        monitor_printf(mon, "No PCMCIA sockets\n");
2644

    
2645
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2646
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2647
                       iter->socket->attached ? iter->socket->card_string :
2648
                       "Empty");
2649
}
2650

    
2651
/***********************************************************/
2652
/* I/O handling */
2653

    
2654
typedef struct IOHandlerRecord {
2655
    int fd;
2656
    IOCanRWHandler *fd_read_poll;
2657
    IOHandler *fd_read;
2658
    IOHandler *fd_write;
2659
    int deleted;
2660
    void *opaque;
2661
    /* temporary data */
2662
    struct pollfd *ufd;
2663
    struct IOHandlerRecord *next;
2664
} IOHandlerRecord;
2665

    
2666
static IOHandlerRecord *first_io_handler;
2667

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

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

    
2709
int qemu_set_fd_handler(int fd,
2710
                        IOHandler *fd_read,
2711
                        IOHandler *fd_write,
2712
                        void *opaque)
2713
{
2714
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2715
}
2716

    
2717
#ifdef _WIN32
2718
/***********************************************************/
2719
/* Polling handling */
2720

    
2721
typedef struct PollingEntry {
2722
    PollingFunc *func;
2723
    void *opaque;
2724
    struct PollingEntry *next;
2725
} PollingEntry;
2726

    
2727
static PollingEntry *first_polling_entry;
2728

    
2729
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2730
{
2731
    PollingEntry **ppe, *pe;
2732
    pe = qemu_mallocz(sizeof(PollingEntry));
2733
    pe->func = func;
2734
    pe->opaque = opaque;
2735
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2736
    *ppe = pe;
2737
    return 0;
2738
}
2739

    
2740
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2741
{
2742
    PollingEntry **ppe, *pe;
2743
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2744
        pe = *ppe;
2745
        if (pe->func == func && pe->opaque == opaque) {
2746
            *ppe = pe->next;
2747
            qemu_free(pe);
2748
            break;
2749
        }
2750
    }
2751
}
2752

    
2753
/***********************************************************/
2754
/* Wait objects support */
2755
typedef struct WaitObjects {
2756
    int num;
2757
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2758
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2759
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2760
} WaitObjects;
2761

    
2762
static WaitObjects wait_objects = {0};
2763

    
2764
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2765
{
2766
    WaitObjects *w = &wait_objects;
2767

    
2768
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2769
        return -1;
2770
    w->events[w->num] = handle;
2771
    w->func[w->num] = func;
2772
    w->opaque[w->num] = opaque;
2773
    w->num++;
2774
    return 0;
2775
}
2776

    
2777
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2778
{
2779
    int i, found;
2780
    WaitObjects *w = &wait_objects;
2781

    
2782
    found = 0;
2783
    for (i = 0; i < w->num; i++) {
2784
        if (w->events[i] == handle)
2785
            found = 1;
2786
        if (found) {
2787
            w->events[i] = w->events[i + 1];
2788
            w->func[i] = w->func[i + 1];
2789
            w->opaque[i] = w->opaque[i + 1];
2790
        }
2791
    }
2792
    if (found)
2793
        w->num--;
2794
}
2795
#endif
2796

    
2797
/***********************************************************/
2798
/* ram save/restore */
2799

    
2800
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2801
#define RAM_SAVE_FLAG_COMPRESS        0x02
2802
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2803
#define RAM_SAVE_FLAG_PAGE        0x08
2804
#define RAM_SAVE_FLAG_EOS        0x10
2805

    
2806
static int is_dup_page(uint8_t *page, uint8_t ch)
2807
{
2808
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2809
    uint32_t *array = (uint32_t *)page;
2810
    int i;
2811

    
2812
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2813
        if (array[i] != val)
2814
            return 0;
2815
    }
2816

    
2817
    return 1;
2818
}
2819

    
2820
static int ram_save_block(QEMUFile *f)
2821
{
2822
    static ram_addr_t current_addr = 0;
2823
    ram_addr_t saved_addr = current_addr;
2824
    ram_addr_t addr = 0;
2825
    int found = 0;
2826

    
2827
    while (addr < last_ram_offset) {
2828
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2829
            uint8_t *p;
2830

    
2831
            cpu_physical_memory_reset_dirty(current_addr,
2832
                                            current_addr + TARGET_PAGE_SIZE,
2833
                                            MIGRATION_DIRTY_FLAG);
2834

    
2835
            p = qemu_get_ram_ptr(current_addr);
2836

    
2837
            if (is_dup_page(p, *p)) {
2838
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2839
                qemu_put_byte(f, *p);
2840
            } else {
2841
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2842
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2843
            }
2844

    
2845
            found = 1;
2846
            break;
2847
        }
2848
        addr += TARGET_PAGE_SIZE;
2849
        current_addr = (saved_addr + addr) % last_ram_offset;
2850
    }
2851

    
2852
    return found;
2853
}
2854

    
2855
static uint64_t bytes_transferred;
2856

    
2857
static ram_addr_t ram_save_remaining(void)
2858
{
2859
    ram_addr_t addr;
2860
    ram_addr_t count = 0;
2861

    
2862
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2863
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2864
            count++;
2865
    }
2866

    
2867
    return count;
2868
}
2869

    
2870
uint64_t ram_bytes_remaining(void)
2871
{
2872
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2873
}
2874

    
2875
uint64_t ram_bytes_transferred(void)
2876
{
2877
    return bytes_transferred;
2878
}
2879

    
2880
uint64_t ram_bytes_total(void)
2881
{
2882
    return last_ram_offset;
2883
}
2884

    
2885
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
2886
{
2887
    ram_addr_t addr;
2888
    uint64_t bytes_transferred_last;
2889
    double bwidth = 0;
2890
    uint64_t expected_time = 0;
2891

    
2892
    if (stage < 0) {
2893
        cpu_physical_memory_set_dirty_tracking(0);
2894
        return 0;
2895
    }
2896

    
2897
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2898
        qemu_file_set_error(f);
2899
        return 0;
2900
    }
2901

    
2902
    if (stage == 1) {
2903
        bytes_transferred = 0;
2904

    
2905
        /* Make sure all dirty bits are set */
2906
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2907
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2908
                cpu_physical_memory_set_dirty(addr);
2909
        }
2910

    
2911
        /* Enable dirty memory tracking */
2912
        cpu_physical_memory_set_dirty_tracking(1);
2913

    
2914
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2915
    }
2916

    
2917
    bytes_transferred_last = bytes_transferred;
2918
    bwidth = qemu_get_clock_ns(rt_clock);
2919

    
2920
    while (!qemu_file_rate_limit(f)) {
2921
        int ret;
2922

    
2923
        ret = ram_save_block(f);
2924
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2925
        if (ret == 0) /* no more blocks */
2926
            break;
2927
    }
2928

    
2929
    bwidth = qemu_get_clock_ns(rt_clock) - bwidth;
2930
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2931

    
2932
    /* if we haven't transferred anything this round, force expected_time to a
2933
     * a very high value, but without crashing */
2934
    if (bwidth == 0)
2935
        bwidth = 0.000001;
2936

    
2937
    /* try transferring iterative blocks of memory */
2938
    if (stage == 3) {
2939
        /* flush all remaining blocks regardless of rate limiting */
2940
        while (ram_save_block(f) != 0) {
2941
            bytes_transferred += TARGET_PAGE_SIZE;
2942
        }
2943
        cpu_physical_memory_set_dirty_tracking(0);
2944
    }
2945

    
2946
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2947

    
2948
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2949

    
2950
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2951
}
2952

    
2953
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2954
{
2955
    ram_addr_t addr;
2956
    int flags;
2957

    
2958
    if (version_id != 3)
2959
        return -EINVAL;
2960

    
2961
    do {
2962
        addr = qemu_get_be64(f);
2963

    
2964
        flags = addr & ~TARGET_PAGE_MASK;
2965
        addr &= TARGET_PAGE_MASK;
2966

    
2967
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2968
            if (addr != last_ram_offset)
2969
                return -EINVAL;
2970
        }
2971

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

    
2989
    return 0;
2990
}
2991

    
2992
void qemu_service_io(void)
2993
{
2994
    qemu_notify_event();
2995
}
2996

    
2997
/***********************************************************/
2998
/* machine registration */
2999

    
3000
static QEMUMachine *first_machine = NULL;
3001
QEMUMachine *current_machine = NULL;
3002

    
3003
int qemu_register_machine(QEMUMachine *m)
3004
{
3005
    QEMUMachine **pm;
3006
    pm = &first_machine;
3007
    while (*pm != NULL)
3008
        pm = &(*pm)->next;
3009
    m->next = NULL;
3010
    *pm = m;
3011
    return 0;
3012
}
3013

    
3014
static QEMUMachine *find_machine(const char *name)
3015
{
3016
    QEMUMachine *m;
3017

    
3018
    for(m = first_machine; m != NULL; m = m->next) {
3019
        if (!strcmp(m->name, name))
3020
            return m;
3021
        if (m->alias && !strcmp(m->alias, name))
3022
            return m;
3023
    }
3024
    return NULL;
3025
}
3026

    
3027
static QEMUMachine *find_default_machine(void)
3028
{
3029
    QEMUMachine *m;
3030

    
3031
    for(m = first_machine; m != NULL; m = m->next) {
3032
        if (m->is_default) {
3033
            return m;
3034
        }
3035
    }
3036
    return NULL;
3037
}
3038

    
3039
/***********************************************************/
3040
/* main execution loop */
3041

    
3042
static void gui_update(void *opaque)
3043
{
3044
    uint64_t interval = GUI_REFRESH_INTERVAL;
3045
    DisplayState *ds = opaque;
3046
    DisplayChangeListener *dcl = ds->listeners;
3047

    
3048
    qemu_flush_coalesced_mmio_buffer();
3049
    dpy_refresh(ds);
3050

    
3051
    while (dcl != NULL) {
3052
        if (dcl->gui_timer_interval &&
3053
            dcl->gui_timer_interval < interval)
3054
            interval = dcl->gui_timer_interval;
3055
        dcl = dcl->next;
3056
    }
3057
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3058
}
3059

    
3060
static void nographic_update(void *opaque)
3061
{
3062
    uint64_t interval = GUI_REFRESH_INTERVAL;
3063

    
3064
    qemu_flush_coalesced_mmio_buffer();
3065
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3066
}
3067

    
3068
void cpu_synchronize_all_states(void)
3069
{
3070
    CPUState *cpu;
3071

    
3072
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3073
        cpu_synchronize_state(cpu);
3074
    }
3075
}
3076

    
3077
void cpu_synchronize_all_post_reset(void)
3078
{
3079
    CPUState *cpu;
3080

    
3081
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3082
        cpu_synchronize_post_reset(cpu);
3083
    }
3084
}
3085

    
3086
void cpu_synchronize_all_post_init(void)
3087
{
3088
    CPUState *cpu;
3089

    
3090
    for (cpu = first_cpu; cpu; cpu = cpu->next_cpu) {
3091
        cpu_synchronize_post_init(cpu);
3092
    }
3093
}
3094

    
3095
struct vm_change_state_entry {
3096
    VMChangeStateHandler *cb;
3097
    void *opaque;
3098
    QLIST_ENTRY (vm_change_state_entry) entries;
3099
};
3100

    
3101
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3102

    
3103
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3104
                                                     void *opaque)
3105
{
3106
    VMChangeStateEntry *e;
3107

    
3108
    e = qemu_mallocz(sizeof (*e));
3109

    
3110
    e->cb = cb;
3111
    e->opaque = opaque;
3112
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3113
    return e;
3114
}
3115

    
3116
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3117
{
3118
    QLIST_REMOVE (e, entries);
3119
    qemu_free (e);
3120
}
3121

    
3122
static void vm_state_notify(int running, int reason)
3123
{
3124
    VMChangeStateEntry *e;
3125

    
3126
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3127
        e->cb(e->opaque, running, reason);
3128
    }
3129
}
3130

    
3131
static void resume_all_vcpus(void);
3132
static void pause_all_vcpus(void);
3133

    
3134
void vm_start(void)
3135
{
3136
    if (!vm_running) {
3137
        cpu_enable_ticks();
3138
        vm_running = 1;
3139
        vm_state_notify(1, 0);
3140
        resume_all_vcpus();
3141
    }
3142
}
3143

    
3144
/* reset/shutdown handler */
3145

    
3146
typedef struct QEMUResetEntry {
3147
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3148
    QEMUResetHandler *func;
3149
    void *opaque;
3150
} QEMUResetEntry;
3151

    
3152
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3153
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3154
static int reset_requested;
3155
static int shutdown_requested;
3156
static int powerdown_requested;
3157
static int debug_requested;
3158
static int vmstop_requested;
3159

    
3160
int qemu_shutdown_requested(void)
3161
{
3162
    int r = shutdown_requested;
3163
    shutdown_requested = 0;
3164
    return r;
3165
}
3166

    
3167
int qemu_reset_requested(void)
3168
{
3169
    int r = reset_requested;
3170
    reset_requested = 0;
3171
    return r;
3172
}
3173

    
3174
int qemu_powerdown_requested(void)
3175
{
3176
    int r = powerdown_requested;
3177
    powerdown_requested = 0;
3178
    return r;
3179
}
3180

    
3181
static int qemu_debug_requested(void)
3182
{
3183
    int r = debug_requested;
3184
    debug_requested = 0;
3185
    return r;
3186
}
3187

    
3188
static int qemu_vmstop_requested(void)
3189
{
3190
    int r = vmstop_requested;
3191
    vmstop_requested = 0;
3192
    return r;
3193
}
3194

    
3195
static void do_vm_stop(int reason)
3196
{
3197
    if (vm_running) {
3198
        cpu_disable_ticks();
3199
        vm_running = 0;
3200
        pause_all_vcpus();
3201
        vm_state_notify(0, reason);
3202
        monitor_protocol_event(QEVENT_STOP, NULL);
3203
    }
3204
}
3205

    
3206
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3207
{
3208
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3209

    
3210
    re->func = func;
3211
    re->opaque = opaque;
3212
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3213
}
3214

    
3215
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3216
{
3217
    QEMUResetEntry *re;
3218

    
3219
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3220
        if (re->func == func && re->opaque == opaque) {
3221
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3222
            qemu_free(re);
3223
            return;
3224
        }
3225
    }
3226
}
3227

    
3228
void qemu_system_reset(void)
3229
{
3230
    QEMUResetEntry *re, *nre;
3231

    
3232
    /* reset all devices */
3233
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3234
        re->func(re->opaque);
3235
    }
3236
    monitor_protocol_event(QEVENT_RESET, NULL);
3237
    cpu_synchronize_all_post_reset();
3238
}
3239

    
3240
void qemu_system_reset_request(void)
3241
{
3242
    if (no_reboot) {
3243
        shutdown_requested = 1;
3244
    } else {
3245
        reset_requested = 1;
3246
    }
3247
    qemu_notify_event();
3248
}
3249

    
3250
void qemu_system_shutdown_request(void)
3251
{
3252
    shutdown_requested = 1;
3253
    qemu_notify_event();
3254
}
3255

    
3256
void qemu_system_powerdown_request(void)
3257
{
3258
    powerdown_requested = 1;
3259
    qemu_notify_event();
3260
}
3261

    
3262
#ifdef CONFIG_IOTHREAD
3263
static void qemu_system_vmstop_request(int reason)
3264
{
3265
    vmstop_requested = reason;
3266
    qemu_notify_event();
3267
}
3268
#endif
3269

    
3270
#ifndef _WIN32
3271
static int io_thread_fd = -1;
3272

    
3273
static void qemu_event_increment(void)
3274
{
3275
    /* Write 8 bytes to be compatible with eventfd.  */
3276
    static uint64_t val = 1;
3277
    ssize_t ret;
3278

    
3279
    if (io_thread_fd == -1)
3280
        return;
3281

    
3282
    do {
3283
        ret = write(io_thread_fd, &val, sizeof(val));
3284
    } while (ret < 0 && errno == EINTR);
3285

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

    
3294
static void qemu_event_read(void *opaque)
3295
{
3296
    int fd = (unsigned long)opaque;
3297
    ssize_t len;
3298
    char buffer[512];
3299

    
3300
    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */
3301
    do {
3302
        len = read(fd, buffer, sizeof(buffer));
3303
    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
3304
}
3305

    
3306
static int qemu_event_init(void)
3307
{
3308
    int err;
3309
    int fds[2];
3310

    
3311
    err = qemu_eventfd(fds);
3312
    if (err == -1)
3313
        return -errno;
3314

    
3315
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3316
    if (err < 0)
3317
        goto fail;
3318

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

    
3323
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3324
                         (void *)(unsigned long)fds[0]);
3325

    
3326
    io_thread_fd = fds[1];
3327
    return 0;
3328

    
3329
fail:
3330
    close(fds[0]);
3331
    close(fds[1]);
3332
    return err;
3333
}
3334
#else
3335
HANDLE qemu_event_handle;
3336

    
3337
static void dummy_event_handler(void *opaque)
3338
{
3339
}
3340

    
3341
static int qemu_event_init(void)
3342
{
3343
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3344
    if (!qemu_event_handle) {
3345
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3346
        return -1;
3347
    }
3348
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3349
    return 0;
3350
}
3351

    
3352
static void qemu_event_increment(void)
3353
{
3354
    if (!SetEvent(qemu_event_handle)) {
3355
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3356
                GetLastError());
3357
        exit (1);
3358
    }
3359
}
3360
#endif
3361

    
3362
static int cpu_can_run(CPUState *env)
3363
{
3364
    if (env->stop)
3365
        return 0;
3366
    if (env->stopped)
3367
        return 0;
3368
    if (!vm_running)
3369
        return 0;
3370
    return 1;
3371
}
3372

    
3373
#ifndef CONFIG_IOTHREAD
3374
static int qemu_init_main_loop(void)
3375
{
3376
    return qemu_event_init();
3377
}
3378

    
3379
void qemu_init_vcpu(void *_env)
3380
{
3381
    CPUState *env = _env;
3382

    
3383
    env->nr_cores = smp_cores;
3384
    env->nr_threads = smp_threads;
3385
    if (kvm_enabled())
3386
        kvm_init_vcpu(env);
3387
    return;
3388
}
3389

    
3390
int qemu_cpu_self(void *env)
3391
{
3392
    return 1;
3393
}
3394

    
3395
static void resume_all_vcpus(void)
3396
{
3397
}
3398

    
3399
static void pause_all_vcpus(void)
3400
{
3401
}
3402

    
3403
void qemu_cpu_kick(void *env)
3404
{
3405
    return;
3406
}
3407

    
3408
void qemu_notify_event(void)
3409
{
3410
    CPUState *env = cpu_single_env;
3411

    
3412
    qemu_event_increment ();
3413
    if (env) {
3414
        cpu_exit(env);
3415
    }
3416
    if (next_cpu && env != next_cpu) {
3417
        cpu_exit(next_cpu);
3418
    }
3419
}
3420

    
3421
void qemu_mutex_lock_iothread(void) {}
3422
void qemu_mutex_unlock_iothread(void) {}
3423

    
3424
void vm_stop(int reason)
3425
{
3426
    do_vm_stop(reason);
3427
}
3428

    
3429
#else /* CONFIG_IOTHREAD */
3430

    
3431
#include "qemu-thread.h"
3432

    
3433
QemuMutex qemu_global_mutex;
3434
static QemuMutex qemu_fair_mutex;
3435

    
3436
static QemuThread io_thread;
3437

    
3438
static QemuThread *tcg_cpu_thread;
3439
static QemuCond *tcg_halt_cond;
3440

    
3441
static int qemu_system_ready;
3442
/* cpu creation */
3443
static QemuCond qemu_cpu_cond;
3444
/* system init */
3445
static QemuCond qemu_system_cond;
3446
static QemuCond qemu_pause_cond;
3447

    
3448
static void tcg_block_io_signals(void);
3449
static void kvm_block_io_signals(CPUState *env);
3450
static void unblock_io_signals(void);
3451
static int tcg_has_work(void);
3452
static int cpu_has_work(CPUState *env);
3453

    
3454
static int qemu_init_main_loop(void)
3455
{
3456
    int ret;
3457

    
3458
    ret = qemu_event_init();
3459
    if (ret)
3460
        return ret;
3461

    
3462
    qemu_cond_init(&qemu_pause_cond);
3463
    qemu_mutex_init(&qemu_fair_mutex);
3464
    qemu_mutex_init(&qemu_global_mutex);
3465
    qemu_mutex_lock(&qemu_global_mutex);
3466

    
3467
    unblock_io_signals();
3468
    qemu_thread_self(&io_thread);
3469

    
3470
    return 0;
3471
}
3472

    
3473
static void qemu_wait_io_event_common(CPUState *env)
3474
{
3475
    if (env->stop) {
3476
        env->stop = 0;
3477
        env->stopped = 1;
3478
        qemu_cond_signal(&qemu_pause_cond);
3479
    }
3480
}
3481

    
3482
static void qemu_wait_io_event(CPUState *env)
3483
{
3484
    while (!tcg_has_work())
3485
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3486

    
3487
    qemu_mutex_unlock(&qemu_global_mutex);
3488

    
3489
    /*
3490
     * Users of qemu_global_mutex can be starved, having no chance
3491
     * to acquire it since this path will get to it first.
3492
     * So use another lock to provide fairness.
3493
     */
3494
    qemu_mutex_lock(&qemu_fair_mutex);
3495
    qemu_mutex_unlock(&qemu_fair_mutex);
3496

    
3497
    qemu_mutex_lock(&qemu_global_mutex);
3498
    qemu_wait_io_event_common(env);
3499
}
3500

    
3501
static void qemu_kvm_eat_signal(CPUState *env, int timeout)
3502
{
3503
    struct timespec ts;
3504
    int r, e;
3505
    siginfo_t siginfo;
3506
    sigset_t waitset;
3507

    
3508
    ts.tv_sec = timeout / 1000;
3509
    ts.tv_nsec = (timeout % 1000) * 1000000;
3510

    
3511
    sigemptyset(&waitset);
3512
    sigaddset(&waitset, SIG_IPI);
3513

    
3514
    qemu_mutex_unlock(&qemu_global_mutex);
3515
    r = sigtimedwait(&waitset, &siginfo, &ts);
3516
    e = errno;
3517
    qemu_mutex_lock(&qemu_global_mutex);
3518

    
3519
    if (r == -1 && !(e == EAGAIN || e == EINTR)) {
3520
        fprintf(stderr, "sigtimedwait: %s\n", strerror(e));
3521
        exit(1);
3522
    }
3523
}
3524

    
3525
static void qemu_kvm_wait_io_event(CPUState *env)
3526
{
3527
    while (!cpu_has_work(env))
3528
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3529

    
3530
    qemu_kvm_eat_signal(env, 0);
3531
    qemu_wait_io_event_common(env);
3532
}
3533

    
3534
static int qemu_cpu_exec(CPUState *env);
3535

    
3536
static void *kvm_cpu_thread_fn(void *arg)
3537
{
3538
    CPUState *env = arg;
3539

    
3540
    qemu_thread_self(env->thread);
3541
    if (kvm_enabled())
3542
        kvm_init_vcpu(env);
3543

    
3544
    kvm_block_io_signals(env);
3545

    
3546
    /* signal CPU creation */
3547
    qemu_mutex_lock(&qemu_global_mutex);
3548
    env->created = 1;
3549
    qemu_cond_signal(&qemu_cpu_cond);
3550

    
3551
    /* and wait for machine initialization */
3552
    while (!qemu_system_ready)
3553
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3554

    
3555
    while (1) {
3556
        if (cpu_can_run(env))
3557
            qemu_cpu_exec(env);
3558
        qemu_kvm_wait_io_event(env);
3559
    }
3560

    
3561
    return NULL;
3562
}
3563

    
3564
static void tcg_cpu_exec(void);
3565

    
3566
static void *tcg_cpu_thread_fn(void *arg)
3567
{
3568
    CPUState *env = arg;
3569

    
3570
    tcg_block_io_signals();
3571
    qemu_thread_self(env->thread);
3572

    
3573
    /* signal CPU creation */
3574
    qemu_mutex_lock(&qemu_global_mutex);
3575
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3576
        env->created = 1;
3577
    qemu_cond_signal(&qemu_cpu_cond);
3578

    
3579
    /* and wait for machine initialization */
3580
    while (!qemu_system_ready)
3581
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3582

    
3583
    while (1) {
3584
        tcg_cpu_exec();
3585
        qemu_wait_io_event(cur_cpu);
3586
    }
3587

    
3588
    return NULL;
3589
}
3590

    
3591
void qemu_cpu_kick(void *_env)
3592
{
3593
    CPUState *env = _env;
3594
    qemu_cond_broadcast(env->halt_cond);
3595
    if (kvm_enabled())
3596
        qemu_thread_signal(env->thread, SIG_IPI);
3597
}
3598

    
3599
int qemu_cpu_self(void *_env)
3600
{
3601
    CPUState *env = _env;
3602
    QemuThread this;
3603
 
3604
    qemu_thread_self(&this);
3605
 
3606
    return qemu_thread_equal(&this, env->thread);
3607
}
3608

    
3609
static void cpu_signal(int sig)
3610
{
3611
    if (cpu_single_env)
3612
        cpu_exit(cpu_single_env);
3613
}
3614

    
3615
static void tcg_block_io_signals(void)
3616
{
3617
    sigset_t set;
3618
    struct sigaction sigact;
3619

    
3620
    sigemptyset(&set);
3621
    sigaddset(&set, SIGUSR2);
3622
    sigaddset(&set, SIGIO);
3623
    sigaddset(&set, SIGALRM);
3624
    sigaddset(&set, SIGCHLD);
3625
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3626

    
3627
    sigemptyset(&set);
3628
    sigaddset(&set, SIG_IPI);
3629
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3630

    
3631
    memset(&sigact, 0, sizeof(sigact));
3632
    sigact.sa_handler = cpu_signal;
3633
    sigaction(SIG_IPI, &sigact, NULL);
3634
}
3635

    
3636
static void dummy_signal(int sig)
3637
{
3638
}
3639

    
3640
static void kvm_block_io_signals(CPUState *env)
3641
{
3642
    int r;
3643
    sigset_t set;
3644
    struct sigaction sigact;
3645

    
3646
    sigemptyset(&set);
3647
    sigaddset(&set, SIGUSR2);
3648
    sigaddset(&set, SIGIO);
3649
    sigaddset(&set, SIGALRM);
3650
    sigaddset(&set, SIGCHLD);
3651
    sigaddset(&set, SIG_IPI);
3652
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3653

    
3654
    pthread_sigmask(SIG_BLOCK, NULL, &set);
3655
    sigdelset(&set, SIG_IPI);
3656

    
3657
    memset(&sigact, 0, sizeof(sigact));
3658
    sigact.sa_handler = dummy_signal;
3659
    sigaction(SIG_IPI, &sigact, NULL);
3660

    
3661
    r = kvm_set_signal_mask(env, &set);
3662
    if (r) {
3663
        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(r));
3664
        exit(1);
3665
    }
3666
}
3667

    
3668
static void unblock_io_signals(void)
3669
{
3670
    sigset_t set;
3671

    
3672
    sigemptyset(&set);
3673
    sigaddset(&set, SIGUSR2);
3674
    sigaddset(&set, SIGIO);
3675
    sigaddset(&set, SIGALRM);
3676
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3677

    
3678
    sigemptyset(&set);
3679
    sigaddset(&set, SIG_IPI);
3680
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3681
}
3682

    
3683
static void qemu_signal_lock(unsigned int msecs)
3684
{
3685
    qemu_mutex_lock(&qemu_fair_mutex);
3686

    
3687
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3688
        qemu_thread_signal(tcg_cpu_thread, SIG_IPI);
3689
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3690
            break;
3691
    }
3692
    qemu_mutex_unlock(&qemu_fair_mutex);
3693
}
3694

    
3695
void qemu_mutex_lock_iothread(void)
3696
{
3697
    if (kvm_enabled()) {
3698
        qemu_mutex_lock(&qemu_fair_mutex);
3699
        qemu_mutex_lock(&qemu_global_mutex);
3700
        qemu_mutex_unlock(&qemu_fair_mutex);
3701
    } else
3702
        qemu_signal_lock(100);
3703
}
3704

    
3705
void qemu_mutex_unlock_iothread(void)
3706
{
3707
    qemu_mutex_unlock(&qemu_global_mutex);
3708
}
3709

    
3710
static int all_vcpus_paused(void)
3711
{
3712
    CPUState *penv = first_cpu;
3713

    
3714
    while (penv) {
3715
        if (!penv->stopped)
3716
            return 0;
3717
        penv = (CPUState *)penv->next_cpu;
3718
    }
3719

    
3720
    return 1;
3721
}
3722

    
3723
static void pause_all_vcpus(void)
3724
{
3725
    CPUState *penv = first_cpu;
3726

    
3727
    while (penv) {
3728
        penv->stop = 1;
3729
        qemu_thread_signal(penv->thread, SIG_IPI);
3730
        qemu_cpu_kick(penv);
3731
        penv = (CPUState *)penv->next_cpu;
3732
    }
3733

    
3734
    while (!all_vcpus_paused()) {
3735
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3736
        penv = first_cpu;
3737
        while (penv) {
3738
            qemu_thread_signal(penv->thread, SIG_IPI);
3739
            penv = (CPUState *)penv->next_cpu;
3740
        }
3741
    }
3742
}
3743

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

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

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

    
3776
static void kvm_start_vcpu(CPUState *env)
3777
{
3778
    env->thread = qemu_mallocz(sizeof(QemuThread));
3779
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3780
    qemu_cond_init(env->halt_cond);
3781
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3782
    while (env->created == 0)
3783
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3784
}
3785

    
3786
void qemu_init_vcpu(void *_env)
3787
{
3788
    CPUState *env = _env;
3789

    
3790
    env->nr_cores = smp_cores;
3791
    env->nr_threads = smp_threads;
3792
    if (kvm_enabled())
3793
        kvm_start_vcpu(env);
3794
    else
3795
        tcg_init_vcpu(env);
3796
}
3797

    
3798
void qemu_notify_event(void)
3799
{
3800
    qemu_event_increment();
3801
}
3802

    
3803
void vm_stop(int reason)
3804
{
3805
    QemuThread me;
3806
    qemu_thread_self(&me);
3807

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

    
3823
#endif
3824

    
3825

    
3826
#ifdef _WIN32
3827
static void host_main_loop_wait(int *timeout)
3828
{
3829
    int ret, ret2, i;
3830
    PollingEntry *pe;
3831

    
3832

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

    
3842
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3843
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3844
            if (w->func[ret - WAIT_OBJECT_0])
3845
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3846

    
3847
            /* Check for additional signaled events */
3848
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3849

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

    
3868
    *timeout = 0;
3869
}
3870
#else
3871
static void host_main_loop_wait(int *timeout)
3872
{
3873
}
3874
#endif
3875

    
3876
void main_loop_wait(int timeout)
3877
{
3878
    IOHandlerRecord *ioh;
3879
    fd_set rfds, wfds, xfds;
3880
    int ret, nfds;
3881
    struct timeval tv;
3882

    
3883
    qemu_bh_update_timeout(&timeout);
3884

    
3885
    host_main_loop_wait(&timeout);
3886

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

    
3910
    tv.tv_sec = timeout / 1000;
3911
    tv.tv_usec = (timeout % 1000) * 1000;
3912

    
3913
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3914

    
3915
    qemu_mutex_unlock_iothread();
3916
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3917
    qemu_mutex_lock_iothread();
3918
    if (ret > 0) {
3919
        IOHandlerRecord **pioh;
3920

    
3921
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3922
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3923
                ioh->fd_read(ioh->opaque);
3924
            }
3925
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3926
                ioh->fd_write(ioh->opaque);
3927
            }
3928
        }
3929

    
3930
        /* remove deleted IO handlers */
3931
        pioh = &first_io_handler;
3932
        while (*pioh) {
3933
            ioh = *pioh;
3934
            if (ioh->deleted) {
3935
                *pioh = ioh->next;
3936
                qemu_free(ioh);
3937
            } else
3938
                pioh = &ioh->next;
3939
        }
3940
    }
3941

    
3942
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3943

    
3944
    qemu_run_all_timers();
3945

    
3946
    /* Check bottom-halves last in case any of the earlier events triggered
3947
       them.  */
3948
    qemu_bh_poll();
3949

    
3950
}
3951

    
3952
static int qemu_cpu_exec(CPUState *env)
3953
{
3954
    int ret;
3955
#ifdef CONFIG_PROFILER
3956
    int64_t ti;
3957
#endif
3958

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

    
3990
static void tcg_cpu_exec(void)
3991
{
3992
    int ret = 0;
3993

    
3994
    if (next_cpu == NULL)
3995
        next_cpu = first_cpu;
3996
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3997
        CPUState *env = cur_cpu = next_cpu;
3998

    
3999
        qemu_clock_enable(vm_clock,
4000
                          (cur_cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
4001

    
4002
        if (alarm_timer->pending)
4003
            break;
4004
        if (cpu_can_run(env))
4005
            ret = qemu_cpu_exec(env);
4006
        else if (env->stop)
4007
            break;
4008

    
4009
        if (ret == EXCP_DEBUG) {
4010
            gdb_set_stop_cpu(env);
4011
            debug_requested = 1;
4012
            break;
4013
        }
4014
    }
4015
}
4016

    
4017
static int cpu_has_work(CPUState *env)
4018
{
4019
    if (env->stop)
4020
        return 1;
4021
    if (env->stopped)
4022
        return 0;
4023
    if (!env->halted)
4024
        return 1;
4025
    if (qemu_cpu_has_work(env))
4026
        return 1;
4027
    return 0;
4028
}
4029

    
4030
static int tcg_has_work(void)
4031
{
4032
    CPUState *env;
4033

    
4034
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4035
        if (cpu_has_work(env))
4036
            return 1;
4037
    return 0;
4038
}
4039

    
4040
static int qemu_calculate_timeout(void)
4041
{
4042
#ifndef CONFIG_IOTHREAD
4043
    int timeout;
4044

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

    
4085
    return timeout;
4086
#else /* CONFIG_IOTHREAD */
4087
    return 1000;
4088
#endif
4089
}
4090

    
4091
static int vm_can_run(void)
4092
{
4093
    if (powerdown_requested)
4094
        return 0;
4095
    if (reset_requested)
4096
        return 0;
4097
    if (shutdown_requested)
4098
        return 0;
4099
    if (debug_requested)
4100
        return 0;
4101
    return 1;
4102
}
4103

    
4104
qemu_irq qemu_system_powerdown;
4105

    
4106
static void main_loop(void)
4107
{
4108
    int r;
4109

    
4110
#ifdef CONFIG_IOTHREAD
4111
    qemu_system_ready = 1;
4112
    qemu_cond_broadcast(&qemu_system_cond);
4113
#endif
4114

    
4115
    for (;;) {
4116
        do {
4117
#ifdef CONFIG_PROFILER
4118
            int64_t ti;
4119
#endif
4120
#ifndef CONFIG_IOTHREAD
4121
            tcg_cpu_exec();
4122
#endif
4123
#ifdef CONFIG_PROFILER
4124
            ti = profile_getclock();
4125
#endif
4126
            main_loop_wait(qemu_calculate_timeout());
4127
#ifdef CONFIG_PROFILER
4128
            dev_time += profile_getclock() - ti;
4129
#endif
4130
        } while (vm_can_run());
4131

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

    
4159
static void version(void)
4160
{
4161
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4162
}
4163

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

    
4192
#define HAS_ARG 0x0001
4193

    
4194
enum {
4195
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4196
    opt_enum,
4197
#define DEFHEADING(text)
4198
#include "qemu-options.h"
4199
#undef DEF
4200
#undef DEFHEADING
4201
#undef GEN_DOCS
4202
};
4203

    
4204
typedef struct QEMUOption {
4205
    const char *name;
4206
    int flags;
4207
    int index;
4208
} QEMUOption;
4209

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

    
4222
#ifdef HAS_AUDIO
4223
struct soundhw soundhw[] = {
4224
#ifdef HAS_AUDIO_CHOICE
4225
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4226
    {
4227
        "pcspk",
4228
        "PC speaker",
4229
        0,
4230
        1,
4231
        { .init_isa = pcspk_audio_init }
4232
    },
4233
#endif
4234

    
4235
#ifdef CONFIG_SB16
4236
    {
4237
        "sb16",
4238
        "Creative Sound Blaster 16",
4239
        0,
4240
        1,
4241
        { .init_isa = SB16_init }
4242
    },
4243
#endif
4244

    
4245
#ifdef CONFIG_CS4231A
4246
    {
4247
        "cs4231a",
4248
        "CS4231A",
4249
        0,
4250
        1,
4251
        { .init_isa = cs4231a_init }
4252
    },
4253
#endif
4254

    
4255
#ifdef CONFIG_ADLIB
4256
    {
4257
        "adlib",
4258
#ifdef HAS_YMF262
4259
        "Yamaha YMF262 (OPL3)",
4260
#else
4261
        "Yamaha YM3812 (OPL2)",
4262
#endif
4263
        0,
4264
        1,
4265
        { .init_isa = Adlib_init }
4266
    },
4267
#endif
4268

    
4269
#ifdef CONFIG_GUS
4270
    {
4271
        "gus",
4272
        "Gravis Ultrasound GF1",
4273
        0,
4274
        1,
4275
        { .init_isa = GUS_init }
4276
    },
4277
#endif
4278

    
4279
#ifdef CONFIG_AC97
4280
    {
4281
        "ac97",
4282
        "Intel 82801AA AC97 Audio",
4283
        0,
4284
        0,
4285
        { .init_pci = ac97_init }
4286
    },
4287
#endif
4288

    
4289
#ifdef CONFIG_ES1370
4290
    {
4291
        "es1370",
4292
        "ENSONIQ AudioPCI ES1370",
4293
        0,
4294
        0,
4295
        { .init_pci = es1370_init }
4296
    },
4297
#endif
4298

    
4299
#endif /* HAS_AUDIO_CHOICE */
4300

    
4301
    { NULL, NULL, 0, 0, { NULL } }
4302
};
4303

    
4304
static void select_soundhw (const char *optarg)
4305
{
4306
    struct soundhw *c;
4307

    
4308
    if (*optarg == '?') {
4309
    show_valid_cards:
4310

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

    
4324
        if (!strcmp (optarg, "all")) {
4325
            for (c = soundhw; c->name; ++c) {
4326
                c->enabled = 1;
4327
            }
4328
            return;
4329
        }
4330

    
4331
        p = optarg;
4332
        while (*p) {
4333
            e = strchr (p, ',');
4334
            l = !e ? strlen (p) : (size_t) (e - p);
4335

    
4336
            for (c = soundhw; c->name; ++c) {
4337
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4338
                    c->enabled = 1;
4339
                    break;
4340
                }
4341
            }
4342

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

    
4357
        if (bad_card)
4358
            goto show_valid_cards;
4359
    }
4360
}
4361
#endif
4362

    
4363
static void select_vgahw (const char *p)
4364
{
4365
    const char *opts;
4366

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

    
4385
        if (strstart(opts, ",retrace=", &nextopt)) {
4386
            opts = nextopt;
4387
            if (strstart(opts, "dumb", &nextopt))
4388
                vga_retrace_method = VGA_RETRACE_DUMB;
4389
            else if (strstart(opts, "precise", &nextopt))
4390
                vga_retrace_method = VGA_RETRACE_PRECISE;
4391
            else goto invalid_vga;
4392
        } else goto invalid_vga;
4393
        opts = nextopt;
4394
    }
4395
}
4396

    
4397
#ifdef TARGET_I386
4398
static int balloon_parse(const char *arg)
4399
{
4400
    QemuOpts *opts;
4401

    
4402
    if (strcmp(arg, "none") == 0) {
4403
        return 0;
4404
    }
4405

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

    
4420
    return -1;
4421
}
4422
#endif
4423

    
4424
#ifdef _WIN32
4425
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4426
{
4427
    exit(STATUS_CONTROL_C_EXIT);
4428
    return TRUE;
4429
}
4430
#endif
4431

    
4432
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4433
{
4434
    int ret;
4435

    
4436
    if(strlen(str) != 36)
4437
        return -1;
4438

    
4439
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4440
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4441
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4442

    
4443
    if(ret != 16)
4444
        return -1;
4445

    
4446
#ifdef TARGET_I386
4447
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4448
#endif
4449

    
4450
    return 0;
4451
}
4452

    
4453
#ifndef _WIN32
4454

    
4455
static void termsig_handler(int signal)
4456
{
4457
    qemu_system_shutdown_request();
4458
}
4459

    
4460
static void sigchld_handler(int signal)
4461
{
4462
    waitpid(-1, NULL, WNOHANG);
4463
}
4464

    
4465
static void sighandler_setup(void)
4466
{
4467
    struct sigaction act;
4468

    
4469
    memset(&act, 0, sizeof(act));
4470
    act.sa_handler = termsig_handler;
4471
    sigaction(SIGINT,  &act, NULL);
4472
    sigaction(SIGHUP,  &act, NULL);
4473
    sigaction(SIGTERM, &act, NULL);
4474

    
4475
    act.sa_handler = sigchld_handler;
4476
    act.sa_flags = SA_NOCLDSTOP;
4477
    sigaction(SIGCHLD, &act, NULL);
4478
}
4479

    
4480
#endif
4481

    
4482
#ifdef _WIN32
4483
/* Look for support files in the same directory as the executable.  */
4484
static char *find_datadir(const char *argv0)
4485
{
4486
    char *p;
4487
    char buf[MAX_PATH];
4488
    DWORD len;
4489

    
4490
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4491
    if (len == 0) {
4492
        return NULL;
4493
    }
4494

    
4495
    buf[len] = 0;
4496
    p = buf + len - 1;
4497
    while (p != buf && *p != '\\')
4498
        p--;
4499
    *p = 0;
4500
    if (access(buf, R_OK) == 0) {
4501
        return qemu_strdup(buf);
4502
    }
4503
    return NULL;
4504
}
4505
#else /* !_WIN32 */
4506

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

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

    
4550
    max_len = strlen(dir) +
4551
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4552
    res = qemu_mallocz(max_len);
4553
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4554
    if (access(res, R_OK)) {
4555
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4556
        if (access(res, R_OK)) {
4557
            qemu_free(res);
4558
            res = NULL;
4559
        }
4560
    }
4561

    
4562
    return res;
4563
}
4564
#undef SHARE_SUFFIX
4565
#undef BUILD_SUFFIX
4566
#endif
4567

    
4568
char *qemu_find_file(int type, const char *name)
4569
{
4570
    int len;
4571
    const char *subdir;
4572
    char *buf;
4573

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

    
4599
static int device_help_func(QemuOpts *opts, void *opaque)
4600
{
4601
    return qdev_device_help(opts);
4602
}
4603

    
4604
static int device_init_func(QemuOpts *opts, void *opaque)
4605
{
4606
    DeviceState *dev;
4607

    
4608
    dev = qdev_device_add(opts);
4609
    if (!dev)
4610
        return -1;
4611
    return 0;
4612
}
4613

    
4614
static int chardev_init_func(QemuOpts *opts, void *opaque)
4615
{
4616
    CharDriverState *chr;
4617

    
4618
    chr = qemu_chr_open_opts(opts, NULL);
4619
    if (!chr)
4620
        return -1;
4621
    return 0;
4622
}
4623

    
4624
static int mon_init_func(QemuOpts *opts, void *opaque)
4625
{
4626
    CharDriverState *chr;
4627
    const char *chardev;
4628
    const char *mode;
4629
    int flags;
4630

    
4631
    mode = qemu_opt_get(opts, "mode");
4632
    if (mode == NULL) {
4633
        mode = "readline";
4634
    }
4635
    if (strcmp(mode, "readline") == 0) {
4636
        flags = MONITOR_USE_READLINE;
4637
    } else if (strcmp(mode, "control") == 0) {
4638
        flags = MONITOR_USE_CONTROL;
4639
    } else {
4640
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4641
        exit(1);
4642
    }
4643

    
4644
    if (qemu_opt_get_bool(opts, "default", 0))
4645
        flags |= MONITOR_IS_DEFAULT;
4646

    
4647
    chardev = qemu_opt_get(opts, "chardev");
4648
    chr = qemu_chr_find(chardev);
4649
    if (chr == NULL) {
4650
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4651
        exit(1);
4652
    }
4653

    
4654
    monitor_init(chr, flags);
4655
    return 0;
4656
}
4657

    
4658
static void monitor_parse(const char *optarg, const char *mode)
4659
{
4660
    static int monitor_device_index = 0;
4661
    QemuOpts *opts;
4662
    const char *p;
4663
    char label[32];
4664
    int def = 0;
4665

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

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

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

    
4709
static void add_device_config(int type, const char *cmdline)
4710
{
4711
    struct device_config *conf;
4712

    
4713
    conf = qemu_mallocz(sizeof(*conf));
4714
    conf->type = type;
4715
    conf->cmdline = cmdline;
4716
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4717
}
4718

    
4719
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4720
{
4721
    struct device_config *conf;
4722
    int rc;
4723

    
4724
    QTAILQ_FOREACH(conf, &device_configs, next) {
4725
        if (conf->type != type)
4726
            continue;
4727
        rc = func(conf->cmdline);
4728
        if (0 != rc)
4729
            return rc;
4730
    }
4731
    return 0;
4732
}
4733

    
4734
static int serial_parse(const char *devname)
4735
{
4736
    static int index = 0;
4737
    char label[32];
4738

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

    
4756
static int parallel_parse(const char *devname)
4757
{
4758
    static int index = 0;
4759
    char label[32];
4760

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

    
4778
static int virtcon_parse(const char *devname)
4779
{
4780
    static int index = 0;
4781
    char label[32];
4782
    QemuOpts *bus_opts, *dev_opts;
4783

    
4784
    if (strcmp(devname, "none") == 0)
4785
        return 0;
4786
    if (index == MAX_VIRTIO_CONSOLES) {
4787
        fprintf(stderr, "qemu: too many virtio consoles\n");
4788
        exit(1);
4789
    }
4790

    
4791
    bus_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4792
    qemu_opt_set(bus_opts, "driver", "virtio-serial");
4793

    
4794
    dev_opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4795
    qemu_opt_set(dev_opts, "driver", "virtconsole");
4796

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

    
4806
    index++;
4807
    return 0;
4808
}
4809

    
4810
static int debugcon_parse(const char *devname)
4811
{   
4812
    QemuOpts *opts;
4813

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

    
4827
static const QEMUOption *lookup_opt(int argc, char **argv,
4828
                                    const char **poptarg, int *poptind)
4829
{
4830
    const QEMUOption *popt;
4831
    int optind = *poptind;
4832
    char *r = argv[optind];
4833
    const char *optarg;
4834

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

    
4861
    *poptarg = optarg;
4862
    *poptind = optind;
4863

    
4864
    return popt;
4865
}
4866

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

    
4902
    error_set_progname(argv[0]);
4903

    
4904
    init_clocks();
4905

    
4906
    qemu_cache_utils_init(envp);
4907

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

    
4939
    module_call_init(MODULE_INIT_MACHINE);
4940
    machine = find_default_machine();
4941
    cpu_model = NULL;
4942
    initrd_filename = NULL;
4943
    ram_size = 0;
4944
    snapshot = 0;
4945
    kernel_filename = NULL;
4946
    kernel_cmdline = "";
4947
    cyls = heads = secs = 0;
4948
    translation = BIOS_ATA_TRANSLATION_AUTO;
4949

    
4950
    for (i = 0; i < MAX_NODES; i++) {
4951
        node_mem[i] = 0;
4952
        node_cpumask[i] = 0;
4953
    }
4954

    
4955
    nb_numa_nodes = 0;
4956
    nb_nics = 0;
4957

    
4958
    tb_size = 0;
4959
    autostart= 1;
4960

    
4961
    /* first pass of option parsing */
4962
    optind = 1;
4963
    while (optind < argc) {
4964
        if (argv[optind][0] != '-') {
4965
            /* disk image */
4966
            optind++;
4967
            continue;
4968
        } else {
4969
            const QEMUOption *popt;
4970

    
4971
            popt = lookup_opt(argc, argv, &optarg, &optind);
4972
            switch (popt->index) {
4973
            case QEMU_OPTION_nodefconfig:
4974
                defconfig=0;
4975
                break;
4976
            }
4977
        }
4978
    }
4979

    
4980
    if (defconfig) {
4981
        const char *fname;
4982
        FILE *fp;
4983

    
4984
        fname = CONFIG_QEMU_CONFDIR "/qemu.conf";
4985
        fp = fopen(fname, "r");
4986
        if (fp) {
4987
            if (qemu_config_parse(fp, fname) != 0) {
4988
                exit(1);
4989
            }
4990
            fclose(fp);
4991
        }
4992

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

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

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

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

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

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

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

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

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

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

    
5718
    /*
5719
     * Default to max_cpus = smp_cpus, in case the user doesn't
5720
     * specify a max_cpus value.
5721
     */
5722
    if (!max_cpus)
5723
        max_cpus = smp_cpus;
5724

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

    
5733
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5734
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5735

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

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

    
5786
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5787
        exit(1);
5788

    
5789
#ifndef _WIN32
5790
    if (daemonize) {
5791
        pid_t pid;
5792

    
5793
        if (pipe(fds) == -1)
5794
            exit(1);
5795

    
5796
        pid = fork();
5797
        if (pid > 0) {
5798
            uint8_t status;
5799
            ssize_t len;
5800

    
5801
            close(fds[1]);
5802

    
5803
        again:
5804
            len = read(fds[0], &status, 1);
5805
            if (len == -1 && (errno == EINTR))
5806
                goto again;
5807

    
5808
            if (len != 1)
5809
                exit(1);
5810
            else if (status == 1) {
5811
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5812
                exit(1);
5813
            } else
5814
                exit(0);
5815
        } else if (pid < 0)
5816
            exit(1);
5817

    
5818
        close(fds[0]);
5819
        qemu_set_cloexec(fds[1]);
5820

    
5821
        setsid();
5822

    
5823
        pid = fork();
5824
        if (pid > 0)
5825
            exit(0);
5826
        else if (pid < 0)
5827
            exit(1);
5828

    
5829
        umask(027);
5830

    
5831
        signal(SIGTSTP, SIG_IGN);
5832
        signal(SIGTTOU, SIG_IGN);
5833
        signal(SIGTTIN, SIG_IGN);
5834
    }
5835
#endif
5836

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

    
5850
    if (kvm_enabled()) {
5851
        int ret;
5852

    
5853
        ret = kvm_init(smp_cpus);
5854
        if (ret < 0) {
5855
            fprintf(stderr, "failed to initialize KVM\n");
5856
            exit(1);
5857
        }
5858
    }
5859

    
5860
    if (qemu_init_main_loop()) {
5861
        fprintf(stderr, "qemu_init_main_loop failed\n");
5862
        exit(1);
5863
    }
5864
    linux_boot = (kernel_filename != NULL);
5865

    
5866
    if (!linux_boot && *kernel_cmdline != '\0') {
5867
        fprintf(stderr, "-append only allowed with -kernel option\n");
5868
        exit(1);
5869
    }
5870

    
5871
    if (!linux_boot && initrd_filename != NULL) {
5872
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5873
        exit(1);
5874
    }
5875

    
5876
#ifndef _WIN32
5877
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5878
    setvbuf(stdout, NULL, _IOLBF, 0);
5879
#endif
5880

    
5881
    if (init_timer_alarm() < 0) {
5882
        fprintf(stderr, "could not initialize alarm timer\n");
5883
        exit(1);
5884
    }
5885
    configure_icount(icount_option);
5886

    
5887
#ifdef _WIN32
5888
    socket_init();
5889
#endif
5890

    
5891
    if (net_init_clients() < 0) {
5892
        exit(1);
5893
    }
5894

    
5895
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5896
    net_set_boot_mask(net_boot);
5897

    
5898
    /* init the bluetooth world */
5899
    if (foreach_device_config(DEV_BT, bt_parse))
5900
        exit(1);
5901

    
5902
    /* init the memory */
5903
    if (ram_size == 0)
5904
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5905

    
5906
    /* init the dynamic translator */
5907
    cpu_exec_init_all(tb_size * 1024 * 1024);
5908

    
5909
    bdrv_init_with_whitelist();
5910

    
5911
    blk_mig_init();
5912

    
5913
    if (default_cdrom) {
5914
        /* we always create the cdrom drive, even if no disk is there */
5915
        drive_add(NULL, CDROM_ALIAS);
5916
    }
5917

    
5918
    if (default_floppy) {
5919
        /* we always create at least one floppy */
5920
        drive_add(NULL, FD_ALIAS, 0);
5921
    }
5922

    
5923
    if (default_sdcard) {
5924
        /* we always create one sd slot, even if no card is in it */
5925
        drive_add(NULL, SD_ALIAS);
5926
    }
5927

    
5928
    /* open the virtual block devices */
5929
    if (snapshot)
5930
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5931
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5932
        exit(1);
5933

    
5934
    vmstate_register(0, &vmstate_timers ,&timers_state);
5935
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5936
                         ram_load, NULL);
5937

    
5938
    if (nb_numa_nodes > 0) {
5939
        int i;
5940

    
5941
        if (nb_numa_nodes > smp_cpus) {
5942
            nb_numa_nodes = smp_cpus;
5943
        }
5944

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

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

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

    
5980
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5981
        exit(1);
5982
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5983
        exit(1);
5984
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5985
        exit(1);
5986
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5987
        exit(1);
5988

    
5989
    module_call_init(MODULE_INIT_DEVICE);
5990

    
5991
    if (qemu_opts_foreach(&qemu_device_opts, device_help_func, NULL, 0) != 0)
5992
        exit(0);
5993

    
5994
    if (watchdog) {
5995
        i = select_watchdog(watchdog);
5996
        if (i > 0)
5997
            exit (i == 1 ? 1 : 0);
5998
    }
5999

    
6000
    if (machine->compat_props) {
6001
        qdev_prop_register_global_list(machine->compat_props);
6002
    }
6003
    qemu_add_globals();
6004

    
6005
    machine->init(ram_size, boot_devices,
6006
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6007

    
6008
    cpu_synchronize_all_post_init();
6009

    
6010
#ifndef _WIN32
6011
    /* must be after terminal init, SDL library changes signal handlers */
6012
    sighandler_setup();
6013
#endif
6014

    
6015
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
6016
        for (i = 0; i < nb_numa_nodes; i++) {
6017
            if (node_cpumask[i] & (1 << env->cpu_index)) {
6018
                env->numa_node = i;
6019
            }
6020
        }
6021
    }
6022

    
6023
    current_machine = machine;
6024

    
6025
    /* init USB devices */
6026
    if (usb_enabled) {
6027
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
6028
            exit(1);
6029
    }
6030

    
6031
    /* init generic devices */
6032
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
6033
        exit(1);
6034

    
6035
    net_check_clients();
6036

    
6037
    /* just use the first displaystate for the moment */
6038
    ds = get_displaystate();
6039

    
6040
    if (display_type == DT_DEFAULT) {
6041
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6042
        display_type = DT_SDL;
6043
#else
6044
        display_type = DT_VNC;
6045
        vnc_display = "localhost:0,to=99";
6046
        show_vnc_port = 1;
6047
#endif
6048
    }
6049
        
6050

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

    
6073
        if (show_vnc_port) {
6074
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6075
        }
6076
        break;
6077
    default:
6078
        break;
6079
    }
6080
    dpy_resize(ds);
6081

    
6082
    dcl = ds->listeners;
6083
    while (dcl != NULL) {
6084
        if (dcl->dpy_refresh != NULL) {
6085
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6086
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6087
        }
6088
        dcl = dcl->next;
6089
    }
6090

    
6091
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6092
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6093
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6094
    }
6095

    
6096
    text_consoles_set_display(ds);
6097

    
6098
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6099
        exit(1);
6100

    
6101
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6102
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6103
                gdbstub_dev);
6104
        exit(1);
6105
    }
6106

    
6107
    qdev_machine_creation_done();
6108

    
6109
    if (rom_load_all() != 0) {
6110
        fprintf(stderr, "rom loading failed\n");
6111
        exit(1);
6112
    }
6113

    
6114
    qemu_system_reset();
6115
    if (loadvm) {
6116
        if (load_vmstate(loadvm) < 0) {
6117
            autostart = 0;
6118
        }
6119
    }
6120

    
6121
    if (incoming) {
6122
        qemu_start_incoming_migration(incoming);
6123
    } else if (autostart) {
6124
        vm_start();
6125
    }
6126

    
6127
#ifndef _WIN32
6128
    if (daemonize) {
6129
        uint8_t status = 0;
6130
        ssize_t len;
6131

    
6132
    again1:
6133
        len = write(fds[1], &status, 1);
6134
        if (len == -1 && (errno == EINTR))
6135
            goto again1;
6136

    
6137
        if (len != 1)
6138
            exit(1);
6139

    
6140
        if (chdir("/")) {
6141
            perror("not able to chdir to /");
6142
            exit(1);
6143
        }
6144
        TFR(fd = qemu_open("/dev/null", O_RDWR));
6145
        if (fd == -1)
6146
            exit(1);
6147
    }
6148

    
6149
    if (run_as) {
6150
        pwd = getpwnam(run_as);
6151
        if (!pwd) {
6152
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6153
            exit(1);
6154
        }
6155
    }
6156

    
6157
    if (chroot_dir) {
6158
        if (chroot(chroot_dir) < 0) {
6159
            fprintf(stderr, "chroot failed\n");
6160
            exit(1);
6161
        }
6162
        if (chdir("/")) {
6163
            perror("not able to chdir to /");
6164
            exit(1);
6165
        }
6166
    }
6167

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

    
6183
    if (daemonize) {
6184
        dup2(fd, 0);
6185
        dup2(fd, 1);
6186
        dup2(fd, 2);
6187

    
6188
        close(fd);
6189
    }
6190
#endif
6191

    
6192
    main_loop();
6193
    quit_timers();
6194
    net_cleanup();
6195

    
6196
    return 0;
6197
}