Statistics
| Branch: | Revision:

root / vl.c @ f5edb014

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

    
250
int nb_numa_nodes;
251
uint64_t node_mem[MAX_NODES];
252
uint64_t node_cpumask[MAX_NODES];
253

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

    
267
uint8_t qemu_uuid[16];
268

    
269
static QEMUBootSetHandler *boot_set_handler;
270
static void *boot_set_opaque;
271

    
272
static int default_serial = 1;
273
static int default_parallel = 1;
274
static int default_virtcon = 1;
275
static int default_monitor = 1;
276
static int default_vga = 1;
277
static int default_floppy = 1;
278
static int default_cdrom = 1;
279
static int default_sdcard = 1;
280

    
281
static struct {
282
    const char *driver;
283
    int *flag;
284
} default_list[] = {
285
    { .driver = "isa-serial",           .flag = &default_serial    },
286
    { .driver = "isa-parallel",         .flag = &default_parallel  },
287
    { .driver = "isa-fdc",              .flag = &default_floppy    },
288
    { .driver = "ide-drive",            .flag = &default_cdrom     },
289
    { .driver = "virtio-console-pci",   .flag = &default_virtcon   },
290
    { .driver = "virtio-console-s390",  .flag = &default_virtcon   },
291
    { .driver = "VGA",                  .flag = &default_vga       },
292
    { .driver = "cirrus-vga",           .flag = &default_vga       },
293
    { .driver = "vmware-svga",          .flag = &default_vga       },
294
};
295

    
296
static int default_driver_check(QemuOpts *opts, void *opaque)
297
{
298
    const char *driver = qemu_opt_get(opts, "driver");
299
    int i;
300

    
301
    if (!driver)
302
        return 0;
303
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
304
        if (strcmp(default_list[i].driver, driver) != 0)
305
            continue;
306
        *(default_list[i].flag) = 0;
307
    }
308
    return 0;
309
}
310

    
311
/***********************************************************/
312
/* x86 ISA bus support */
313

    
314
target_phys_addr_t isa_mem_base = 0;
315
PicState2 *isa_pic;
316

    
317
/***********************************************************/
318
void hw_error(const char *fmt, ...)
319
{
320
    va_list ap;
321
    CPUState *env;
322

    
323
    va_start(ap, fmt);
324
    fprintf(stderr, "qemu: hardware error: ");
325
    vfprintf(stderr, fmt, ap);
326
    fprintf(stderr, "\n");
327
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
328
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
329
#ifdef TARGET_I386
330
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
331
#else
332
        cpu_dump_state(env, stderr, fprintf, 0);
333
#endif
334
    }
335
    va_end(ap);
336
    abort();
337
}
338

    
339
static void set_proc_name(const char *s)
340
{
341
#if defined(__linux__) && defined(PR_SET_NAME)
342
    char name[16];
343
    if (!s)
344
        return;
345
    name[sizeof(name) - 1] = 0;
346
    strncpy(name, s, sizeof(name));
347
    /* Could rewrite argv[0] too, but that's a bit more complicated.
348
       This simple way is enough for `top'. */
349
    prctl(PR_SET_NAME, name);
350
#endif            
351
}
352
 
353
/***************/
354
/* ballooning */
355

    
356
static QEMUBalloonEvent *qemu_balloon_event;
357
void *qemu_balloon_event_opaque;
358

    
359
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
360
{
361
    qemu_balloon_event = func;
362
    qemu_balloon_event_opaque = opaque;
363
}
364

    
365
void qemu_balloon(ram_addr_t target)
366
{
367
    if (qemu_balloon_event)
368
        qemu_balloon_event(qemu_balloon_event_opaque, target);
369
}
370

    
371
ram_addr_t qemu_balloon_status(void)
372
{
373
    if (qemu_balloon_event)
374
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
375
    return 0;
376
}
377

    
378

    
379
/***********************************************************/
380
/* real time host monotonic timer */
381

    
382
/* compute with 96 bit intermediate result: (a*b)/c */
383
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
384
{
385
    union {
386
        uint64_t ll;
387
        struct {
388
#ifdef HOST_WORDS_BIGENDIAN
389
            uint32_t high, low;
390
#else
391
            uint32_t low, high;
392
#endif
393
        } l;
394
    } u, res;
395
    uint64_t rl, rh;
396

    
397
    u.ll = a;
398
    rl = (uint64_t)u.l.low * (uint64_t)b;
399
    rh = (uint64_t)u.l.high * (uint64_t)b;
400
    rh += (rl >> 32);
401
    res.l.high = rh / c;
402
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
403
    return res.ll;
404
}
405

    
406
static int64_t get_clock_realtime(void)
407
{
408
    struct timeval tv;
409

    
410
    gettimeofday(&tv, NULL);
411
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
412
}
413

    
414
#ifdef WIN32
415

    
416
static int64_t clock_freq;
417

    
418
static void init_get_clock(void)
419
{
420
    LARGE_INTEGER freq;
421
    int ret;
422
    ret = QueryPerformanceFrequency(&freq);
423
    if (ret == 0) {
424
        fprintf(stderr, "Could not calibrate ticks\n");
425
        exit(1);
426
    }
427
    clock_freq = freq.QuadPart;
428
}
429

    
430
static int64_t get_clock(void)
431
{
432
    LARGE_INTEGER ti;
433
    QueryPerformanceCounter(&ti);
434
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
435
}
436

    
437
#else
438

    
439
static int use_rt_clock;
440

    
441
static void init_get_clock(void)
442
{
443
    use_rt_clock = 0;
444
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
445
    || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
446
    {
447
        struct timespec ts;
448
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
449
            use_rt_clock = 1;
450
        }
451
    }
452
#endif
453
}
454

    
455
static int64_t get_clock(void)
456
{
457
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
458
        || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
459
    if (use_rt_clock) {
460
        struct timespec ts;
461
        clock_gettime(CLOCK_MONOTONIC, &ts);
462
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
463
    } else
464
#endif
465
    {
466
        /* XXX: using gettimeofday leads to problems if the date
467
           changes, so it should be avoided. */
468
        return get_clock_realtime();
469
    }
470
}
471
#endif
472

    
473
/* Return the virtual CPU time, based on the instruction counter.  */
474
static int64_t cpu_get_icount(void)
475
{
476
    int64_t icount;
477
    CPUState *env = cpu_single_env;;
478
    icount = qemu_icount;
479
    if (env) {
480
        if (!can_do_io(env))
481
            fprintf(stderr, "Bad clock read\n");
482
        icount -= (env->icount_decr.u16.low + env->icount_extra);
483
    }
484
    return qemu_icount_bias + (icount << icount_time_shift);
485
}
486

    
487
/***********************************************************/
488
/* guest cycle counter */
489

    
490
typedef struct TimersState {
491
    int64_t cpu_ticks_prev;
492
    int64_t cpu_ticks_offset;
493
    int64_t cpu_clock_offset;
494
    int32_t cpu_ticks_enabled;
495
    int64_t dummy;
496
} TimersState;
497

    
498
TimersState timers_state;
499

    
500
/* return the host CPU cycle counter and handle stop/restart */
501
int64_t cpu_get_ticks(void)
502
{
503
    if (use_icount) {
504
        return cpu_get_icount();
505
    }
506
    if (!timers_state.cpu_ticks_enabled) {
507
        return timers_state.cpu_ticks_offset;
508
    } else {
509
        int64_t ticks;
510
        ticks = cpu_get_real_ticks();
511
        if (timers_state.cpu_ticks_prev > ticks) {
512
            /* Note: non increasing ticks may happen if the host uses
513
               software suspend */
514
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
515
        }
516
        timers_state.cpu_ticks_prev = ticks;
517
        return ticks + timers_state.cpu_ticks_offset;
518
    }
519
}
520

    
521
/* return the host CPU monotonic timer and handle stop/restart */
522
static int64_t cpu_get_clock(void)
523
{
524
    int64_t ti;
525
    if (!timers_state.cpu_ticks_enabled) {
526
        return timers_state.cpu_clock_offset;
527
    } else {
528
        ti = get_clock();
529
        return ti + timers_state.cpu_clock_offset;
530
    }
531
}
532

    
533
/* enable cpu_get_ticks() */
534
void cpu_enable_ticks(void)
535
{
536
    if (!timers_state.cpu_ticks_enabled) {
537
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
538
        timers_state.cpu_clock_offset -= get_clock();
539
        timers_state.cpu_ticks_enabled = 1;
540
    }
541
}
542

    
543
/* disable cpu_get_ticks() : the clock is stopped. You must not call
544
   cpu_get_ticks() after that.  */
545
void cpu_disable_ticks(void)
546
{
547
    if (timers_state.cpu_ticks_enabled) {
548
        timers_state.cpu_ticks_offset = cpu_get_ticks();
549
        timers_state.cpu_clock_offset = cpu_get_clock();
550
        timers_state.cpu_ticks_enabled = 0;
551
    }
552
}
553

    
554
/***********************************************************/
555
/* timers */
556

    
557
#define QEMU_CLOCK_REALTIME 0
558
#define QEMU_CLOCK_VIRTUAL  1
559
#define QEMU_CLOCK_HOST     2
560

    
561
struct QEMUClock {
562
    int type;
563
    /* XXX: add frequency */
564
};
565

    
566
struct QEMUTimer {
567
    QEMUClock *clock;
568
    int64_t expire_time;
569
    QEMUTimerCB *cb;
570
    void *opaque;
571
    struct QEMUTimer *next;
572
};
573

    
574
struct qemu_alarm_timer {
575
    char const *name;
576
    unsigned int flags;
577

    
578
    int (*start)(struct qemu_alarm_timer *t);
579
    void (*stop)(struct qemu_alarm_timer *t);
580
    void (*rearm)(struct qemu_alarm_timer *t);
581
    void *priv;
582
};
583

    
584
#define ALARM_FLAG_DYNTICKS  0x1
585
#define ALARM_FLAG_EXPIRED   0x2
586

    
587
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
588
{
589
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
590
}
591

    
592
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
593
{
594
    if (!alarm_has_dynticks(t))
595
        return;
596

    
597
    t->rearm(t);
598
}
599

    
600
/* TODO: MIN_TIMER_REARM_US should be optimized */
601
#define MIN_TIMER_REARM_US 250
602

    
603
static struct qemu_alarm_timer *alarm_timer;
604

    
605
#ifdef _WIN32
606

    
607
struct qemu_alarm_win32 {
608
    MMRESULT timerId;
609
    unsigned int period;
610
} alarm_win32_data = {0, -1};
611

    
612
static int win32_start_timer(struct qemu_alarm_timer *t);
613
static void win32_stop_timer(struct qemu_alarm_timer *t);
614
static void win32_rearm_timer(struct qemu_alarm_timer *t);
615

    
616
#else
617

    
618
static int unix_start_timer(struct qemu_alarm_timer *t);
619
static void unix_stop_timer(struct qemu_alarm_timer *t);
620

    
621
#ifdef __linux__
622

    
623
static int dynticks_start_timer(struct qemu_alarm_timer *t);
624
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
625
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
626

    
627
static int hpet_start_timer(struct qemu_alarm_timer *t);
628
static void hpet_stop_timer(struct qemu_alarm_timer *t);
629

    
630
static int rtc_start_timer(struct qemu_alarm_timer *t);
631
static void rtc_stop_timer(struct qemu_alarm_timer *t);
632

    
633
#endif /* __linux__ */
634

    
635
#endif /* _WIN32 */
636

    
637
/* Correlation between real and virtual time is always going to be
638
   fairly approximate, so ignore small variation.
639
   When the guest is idle real and virtual time will be aligned in
640
   the IO wait loop.  */
641
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
642

    
643
static void icount_adjust(void)
644
{
645
    int64_t cur_time;
646
    int64_t cur_icount;
647
    int64_t delta;
648
    static int64_t last_delta;
649
    /* If the VM is not running, then do nothing.  */
650
    if (!vm_running)
651
        return;
652

    
653
    cur_time = cpu_get_clock();
654
    cur_icount = qemu_get_clock(vm_clock);
655
    delta = cur_icount - cur_time;
656
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
657
    if (delta > 0
658
        && last_delta + ICOUNT_WOBBLE < delta * 2
659
        && icount_time_shift > 0) {
660
        /* The guest is getting too far ahead.  Slow time down.  */
661
        icount_time_shift--;
662
    }
663
    if (delta < 0
664
        && last_delta - ICOUNT_WOBBLE > delta * 2
665
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
666
        /* The guest is getting too far behind.  Speed time up.  */
667
        icount_time_shift++;
668
    }
669
    last_delta = delta;
670
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
671
}
672

    
673
static void icount_adjust_rt(void * opaque)
674
{
675
    qemu_mod_timer(icount_rt_timer,
676
                   qemu_get_clock(rt_clock) + 1000);
677
    icount_adjust();
678
}
679

    
680
static void icount_adjust_vm(void * opaque)
681
{
682
    qemu_mod_timer(icount_vm_timer,
683
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
684
    icount_adjust();
685
}
686

    
687
static void init_icount_adjust(void)
688
{
689
    /* Have both realtime and virtual time triggers for speed adjustment.
690
       The realtime trigger catches emulated time passing too slowly,
691
       the virtual time trigger catches emulated time passing too fast.
692
       Realtime triggers occur even when idle, so use them less frequently
693
       than VM triggers.  */
694
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
695
    qemu_mod_timer(icount_rt_timer,
696
                   qemu_get_clock(rt_clock) + 1000);
697
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
698
    qemu_mod_timer(icount_vm_timer,
699
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
700
}
701

    
702
static struct qemu_alarm_timer alarm_timers[] = {
703
#ifndef _WIN32
704
#ifdef __linux__
705
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
706
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
707
    /* HPET - if available - is preferred */
708
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
709
    /* ...otherwise try RTC */
710
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
711
#endif
712
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
713
#else
714
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
715
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
716
    {"win32", 0, win32_start_timer,
717
     win32_stop_timer, NULL, &alarm_win32_data},
718
#endif
719
    {NULL, }
720
};
721

    
722
static void show_available_alarms(void)
723
{
724
    int i;
725

    
726
    printf("Available alarm timers, in order of precedence:\n");
727
    for (i = 0; alarm_timers[i].name; i++)
728
        printf("%s\n", alarm_timers[i].name);
729
}
730

    
731
static void configure_alarms(char const *opt)
732
{
733
    int i;
734
    int cur = 0;
735
    int count = ARRAY_SIZE(alarm_timers) - 1;
736
    char *arg;
737
    char *name;
738
    struct qemu_alarm_timer tmp;
739

    
740
    if (!strcmp(opt, "?")) {
741
        show_available_alarms();
742
        exit(0);
743
    }
744

    
745
    arg = qemu_strdup(opt);
746

    
747
    /* Reorder the array */
748
    name = strtok(arg, ",");
749
    while (name) {
750
        for (i = 0; i < count && alarm_timers[i].name; i++) {
751
            if (!strcmp(alarm_timers[i].name, name))
752
                break;
753
        }
754

    
755
        if (i == count) {
756
            fprintf(stderr, "Unknown clock %s\n", name);
757
            goto next;
758
        }
759

    
760
        if (i < cur)
761
            /* Ignore */
762
            goto next;
763

    
764
        /* Swap */
765
        tmp = alarm_timers[i];
766
        alarm_timers[i] = alarm_timers[cur];
767
        alarm_timers[cur] = tmp;
768

    
769
        cur++;
770
next:
771
        name = strtok(NULL, ",");
772
    }
773

    
774
    qemu_free(arg);
775

    
776
    if (cur) {
777
        /* Disable remaining timers */
778
        for (i = cur; i < count; i++)
779
            alarm_timers[i].name = NULL;
780
    } else {
781
        show_available_alarms();
782
        exit(1);
783
    }
784
}
785

    
786
#define QEMU_NUM_CLOCKS 3
787

    
788
QEMUClock *rt_clock;
789
QEMUClock *vm_clock;
790
QEMUClock *host_clock;
791

    
792
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
793

    
794
static QEMUClock *qemu_new_clock(int type)
795
{
796
    QEMUClock *clock;
797
    clock = qemu_mallocz(sizeof(QEMUClock));
798
    clock->type = type;
799
    return clock;
800
}
801

    
802
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
803
{
804
    QEMUTimer *ts;
805

    
806
    ts = qemu_mallocz(sizeof(QEMUTimer));
807
    ts->clock = clock;
808
    ts->cb = cb;
809
    ts->opaque = opaque;
810
    return ts;
811
}
812

    
813
void qemu_free_timer(QEMUTimer *ts)
814
{
815
    qemu_free(ts);
816
}
817

    
818
/* stop a timer, but do not dealloc it */
819
void qemu_del_timer(QEMUTimer *ts)
820
{
821
    QEMUTimer **pt, *t;
822

    
823
    /* NOTE: this code must be signal safe because
824
       qemu_timer_expired() can be called from a signal. */
825
    pt = &active_timers[ts->clock->type];
826
    for(;;) {
827
        t = *pt;
828
        if (!t)
829
            break;
830
        if (t == ts) {
831
            *pt = t->next;
832
            break;
833
        }
834
        pt = &t->next;
835
    }
836
}
837

    
838
/* modify the current timer so that it will be fired when current_time
839
   >= expire_time. The corresponding callback will be called. */
840
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
841
{
842
    QEMUTimer **pt, *t;
843

    
844
    qemu_del_timer(ts);
845

    
846
    /* add the timer in the sorted list */
847
    /* NOTE: this code must be signal safe because
848
       qemu_timer_expired() can be called from a signal. */
849
    pt = &active_timers[ts->clock->type];
850
    for(;;) {
851
        t = *pt;
852
        if (!t)
853
            break;
854
        if (t->expire_time > expire_time)
855
            break;
856
        pt = &t->next;
857
    }
858
    ts->expire_time = expire_time;
859
    ts->next = *pt;
860
    *pt = ts;
861

    
862
    /* Rearm if necessary  */
863
    if (pt == &active_timers[ts->clock->type]) {
864
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
865
            qemu_rearm_alarm_timer(alarm_timer);
866
        }
867
        /* Interrupt execution to force deadline recalculation.  */
868
        if (use_icount)
869
            qemu_notify_event();
870
    }
871
}
872

    
873
int qemu_timer_pending(QEMUTimer *ts)
874
{
875
    QEMUTimer *t;
876
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
877
        if (t == ts)
878
            return 1;
879
    }
880
    return 0;
881
}
882

    
883
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
884
{
885
    if (!timer_head)
886
        return 0;
887
    return (timer_head->expire_time <= current_time);
888
}
889

    
890
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
891
{
892
    QEMUTimer *ts;
893

    
894
    for(;;) {
895
        ts = *ptimer_head;
896
        if (!ts || ts->expire_time > current_time)
897
            break;
898
        /* remove timer from the list before calling the callback */
899
        *ptimer_head = ts->next;
900
        ts->next = NULL;
901

    
902
        /* run the callback (the timer list can be modified) */
903
        ts->cb(ts->opaque);
904
    }
905
}
906

    
907
int64_t qemu_get_clock(QEMUClock *clock)
908
{
909
    switch(clock->type) {
910
    case QEMU_CLOCK_REALTIME:
911
        return get_clock() / 1000000;
912
    default:
913
    case QEMU_CLOCK_VIRTUAL:
914
        if (use_icount) {
915
            return cpu_get_icount();
916
        } else {
917
            return cpu_get_clock();
918
        }
919
    case QEMU_CLOCK_HOST:
920
        return get_clock_realtime();
921
    }
922
}
923

    
924
static void init_clocks(void)
925
{
926
    init_get_clock();
927
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
928
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
929
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
930

    
931
    rtc_clock = host_clock;
932
}
933

    
934
/* save a timer */
935
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
936
{
937
    uint64_t expire_time;
938

    
939
    if (qemu_timer_pending(ts)) {
940
        expire_time = ts->expire_time;
941
    } else {
942
        expire_time = -1;
943
    }
944
    qemu_put_be64(f, expire_time);
945
}
946

    
947
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
948
{
949
    uint64_t expire_time;
950

    
951
    expire_time = qemu_get_be64(f);
952
    if (expire_time != -1) {
953
        qemu_mod_timer(ts, expire_time);
954
    } else {
955
        qemu_del_timer(ts);
956
    }
957
}
958

    
959
static const VMStateDescription vmstate_timers = {
960
    .name = "timer",
961
    .version_id = 2,
962
    .minimum_version_id = 1,
963
    .minimum_version_id_old = 1,
964
    .fields      = (VMStateField []) {
965
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
966
        VMSTATE_INT64(dummy, TimersState),
967
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
968
        VMSTATE_END_OF_LIST()
969
    }
970
};
971

    
972
static void qemu_event_increment(void);
973

    
974
#ifdef _WIN32
975
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
976
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
977
                                        DWORD_PTR dw2)
978
#else
979
static void host_alarm_handler(int host_signum)
980
#endif
981
{
982
#if 0
983
#define DISP_FREQ 1000
984
    {
985
        static int64_t delta_min = INT64_MAX;
986
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
987
        static int count;
988
        ti = qemu_get_clock(vm_clock);
989
        if (last_clock != 0) {
990
            delta = ti - last_clock;
991
            if (delta < delta_min)
992
                delta_min = delta;
993
            if (delta > delta_max)
994
                delta_max = delta;
995
            delta_cum += delta;
996
            if (++count == DISP_FREQ) {
997
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
998
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
999
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1000
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1001
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1002
                count = 0;
1003
                delta_min = INT64_MAX;
1004
                delta_max = 0;
1005
                delta_cum = 0;
1006
            }
1007
        }
1008
        last_clock = ti;
1009
    }
1010
#endif
1011
    if (alarm_has_dynticks(alarm_timer) ||
1012
        (!use_icount &&
1013
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1014
                               qemu_get_clock(vm_clock))) ||
1015
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1016
                           qemu_get_clock(rt_clock)) ||
1017
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1018
                           qemu_get_clock(host_clock))) {
1019
        qemu_event_increment();
1020
        if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1021

    
1022
#ifndef CONFIG_IOTHREAD
1023
        if (next_cpu) {
1024
            /* stop the currently executing cpu because a timer occured */
1025
            cpu_exit(next_cpu);
1026
        }
1027
#endif
1028
        timer_alarm_pending = 1;
1029
        qemu_notify_event();
1030
    }
1031
}
1032

    
1033
static int64_t qemu_next_deadline(void)
1034
{
1035
    /* To avoid problems with overflow limit this to 2^32.  */
1036
    int64_t delta = INT32_MAX;
1037

    
1038
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1039
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1040
                     qemu_get_clock(vm_clock);
1041
    }
1042
    if (active_timers[QEMU_CLOCK_HOST]) {
1043
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1044
                 qemu_get_clock(host_clock);
1045
        if (hdelta < delta)
1046
            delta = hdelta;
1047
    }
1048

    
1049
    if (delta < 0)
1050
        delta = 0;
1051

    
1052
    return delta;
1053
}
1054

    
1055
#if defined(__linux__)
1056
static uint64_t qemu_next_deadline_dyntick(void)
1057
{
1058
    int64_t delta;
1059
    int64_t rtdelta;
1060

    
1061
    if (use_icount)
1062
        delta = INT32_MAX;
1063
    else
1064
        delta = (qemu_next_deadline() + 999) / 1000;
1065

    
1066
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1067
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1068
                 qemu_get_clock(rt_clock))*1000;
1069
        if (rtdelta < delta)
1070
            delta = rtdelta;
1071
    }
1072

    
1073
    if (delta < MIN_TIMER_REARM_US)
1074
        delta = MIN_TIMER_REARM_US;
1075

    
1076
    return delta;
1077
}
1078
#endif
1079

    
1080
#ifndef _WIN32
1081

    
1082
/* Sets a specific flag */
1083
static int fcntl_setfl(int fd, int flag)
1084
{
1085
    int flags;
1086

    
1087
    flags = fcntl(fd, F_GETFL);
1088
    if (flags == -1)
1089
        return -errno;
1090

    
1091
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1092
        return -errno;
1093

    
1094
    return 0;
1095
}
1096

    
1097
#if defined(__linux__)
1098

    
1099
#define RTC_FREQ 1024
1100

    
1101
static void enable_sigio_timer(int fd)
1102
{
1103
    struct sigaction act;
1104

    
1105
    /* timer signal */
1106
    sigfillset(&act.sa_mask);
1107
    act.sa_flags = 0;
1108
    act.sa_handler = host_alarm_handler;
1109

    
1110
    sigaction(SIGIO, &act, NULL);
1111
    fcntl_setfl(fd, O_ASYNC);
1112
    fcntl(fd, F_SETOWN, getpid());
1113
}
1114

    
1115
static int hpet_start_timer(struct qemu_alarm_timer *t)
1116
{
1117
    struct hpet_info info;
1118
    int r, fd;
1119

    
1120
    fd = qemu_open("/dev/hpet", O_RDONLY);
1121
    if (fd < 0)
1122
        return -1;
1123

    
1124
    /* Set frequency */
1125
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1126
    if (r < 0) {
1127
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1128
                "error, but for better emulation accuracy type:\n"
1129
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1130
        goto fail;
1131
    }
1132

    
1133
    /* Check capabilities */
1134
    r = ioctl(fd, HPET_INFO, &info);
1135
    if (r < 0)
1136
        goto fail;
1137

    
1138
    /* Enable periodic mode */
1139
    r = ioctl(fd, HPET_EPI, 0);
1140
    if (info.hi_flags && (r < 0))
1141
        goto fail;
1142

    
1143
    /* Enable interrupt */
1144
    r = ioctl(fd, HPET_IE_ON, 0);
1145
    if (r < 0)
1146
        goto fail;
1147

    
1148
    enable_sigio_timer(fd);
1149
    t->priv = (void *)(long)fd;
1150

    
1151
    return 0;
1152
fail:
1153
    close(fd);
1154
    return -1;
1155
}
1156

    
1157
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1158
{
1159
    int fd = (long)t->priv;
1160

    
1161
    close(fd);
1162
}
1163

    
1164
static int rtc_start_timer(struct qemu_alarm_timer *t)
1165
{
1166
    int rtc_fd;
1167
    unsigned long current_rtc_freq = 0;
1168

    
1169
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1170
    if (rtc_fd < 0)
1171
        return -1;
1172
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1173
    if (current_rtc_freq != RTC_FREQ &&
1174
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1175
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1176
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1177
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1178
        goto fail;
1179
    }
1180
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1181
    fail:
1182
        close(rtc_fd);
1183
        return -1;
1184
    }
1185

    
1186
    enable_sigio_timer(rtc_fd);
1187

    
1188
    t->priv = (void *)(long)rtc_fd;
1189

    
1190
    return 0;
1191
}
1192

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

    
1197
    close(rtc_fd);
1198
}
1199

    
1200
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1201
{
1202
    struct sigevent ev;
1203
    timer_t host_timer;
1204
    struct sigaction act;
1205

    
1206
    sigfillset(&act.sa_mask);
1207
    act.sa_flags = 0;
1208
    act.sa_handler = host_alarm_handler;
1209

    
1210
    sigaction(SIGALRM, &act, NULL);
1211

    
1212
    /* 
1213
     * Initialize ev struct to 0 to avoid valgrind complaining
1214
     * about uninitialized data in timer_create call
1215
     */
1216
    memset(&ev, 0, sizeof(ev));
1217
    ev.sigev_value.sival_int = 0;
1218
    ev.sigev_notify = SIGEV_SIGNAL;
1219
    ev.sigev_signo = SIGALRM;
1220

    
1221
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1222
        perror("timer_create");
1223

    
1224
        /* disable dynticks */
1225
        fprintf(stderr, "Dynamic Ticks disabled\n");
1226

    
1227
        return -1;
1228
    }
1229

    
1230
    t->priv = (void *)(long)host_timer;
1231

    
1232
    return 0;
1233
}
1234

    
1235
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1236
{
1237
    timer_t host_timer = (timer_t)(long)t->priv;
1238

    
1239
    timer_delete(host_timer);
1240
}
1241

    
1242
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1243
{
1244
    timer_t host_timer = (timer_t)(long)t->priv;
1245
    struct itimerspec timeout;
1246
    int64_t nearest_delta_us = INT64_MAX;
1247
    int64_t current_us;
1248

    
1249
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1250
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1251
        !active_timers[QEMU_CLOCK_HOST])
1252
        return;
1253

    
1254
    nearest_delta_us = qemu_next_deadline_dyntick();
1255

    
1256
    /* check whether a timer is already running */
1257
    if (timer_gettime(host_timer, &timeout)) {
1258
        perror("gettime");
1259
        fprintf(stderr, "Internal timer error: aborting\n");
1260
        exit(1);
1261
    }
1262
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1263
    if (current_us && current_us <= nearest_delta_us)
1264
        return;
1265

    
1266
    timeout.it_interval.tv_sec = 0;
1267
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1268
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1269
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1270
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1271
        perror("settime");
1272
        fprintf(stderr, "Internal timer error: aborting\n");
1273
        exit(1);
1274
    }
1275
}
1276

    
1277
#endif /* defined(__linux__) */
1278

    
1279
static int unix_start_timer(struct qemu_alarm_timer *t)
1280
{
1281
    struct sigaction act;
1282
    struct itimerval itv;
1283
    int err;
1284

    
1285
    /* timer signal */
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
    itv.it_interval.tv_sec = 0;
1293
    /* for i386 kernel 2.6 to get 1 ms */
1294
    itv.it_interval.tv_usec = 999;
1295
    itv.it_value.tv_sec = 0;
1296
    itv.it_value.tv_usec = 10 * 1000;
1297

    
1298
    err = setitimer(ITIMER_REAL, &itv, NULL);
1299
    if (err)
1300
        return -1;
1301

    
1302
    return 0;
1303
}
1304

    
1305
static void unix_stop_timer(struct qemu_alarm_timer *t)
1306
{
1307
    struct itimerval itv;
1308

    
1309
    memset(&itv, 0, sizeof(itv));
1310
    setitimer(ITIMER_REAL, &itv, NULL);
1311
}
1312

    
1313
#endif /* !defined(_WIN32) */
1314

    
1315

    
1316
#ifdef _WIN32
1317

    
1318
static int win32_start_timer(struct qemu_alarm_timer *t)
1319
{
1320
    TIMECAPS tc;
1321
    struct qemu_alarm_win32 *data = t->priv;
1322
    UINT flags;
1323

    
1324
    memset(&tc, 0, sizeof(tc));
1325
    timeGetDevCaps(&tc, sizeof(tc));
1326

    
1327
    if (data->period < tc.wPeriodMin)
1328
        data->period = tc.wPeriodMin;
1329

    
1330
    timeBeginPeriod(data->period);
1331

    
1332
    flags = TIME_CALLBACK_FUNCTION;
1333
    if (alarm_has_dynticks(t))
1334
        flags |= TIME_ONESHOT;
1335
    else
1336
        flags |= TIME_PERIODIC;
1337

    
1338
    data->timerId = timeSetEvent(1,         // interval (ms)
1339
                        data->period,       // resolution
1340
                        host_alarm_handler, // function
1341
                        (DWORD)t,           // parameter
1342
                        flags);
1343

    
1344
    if (!data->timerId) {
1345
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1346
                GetLastError());
1347
        timeEndPeriod(data->period);
1348
        return -1;
1349
    }
1350

    
1351
    return 0;
1352
}
1353

    
1354
static void win32_stop_timer(struct qemu_alarm_timer *t)
1355
{
1356
    struct qemu_alarm_win32 *data = t->priv;
1357

    
1358
    timeKillEvent(data->timerId);
1359
    timeEndPeriod(data->period);
1360
}
1361

    
1362
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1363
{
1364
    struct qemu_alarm_win32 *data = t->priv;
1365

    
1366
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1367
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1368
        !active_timers[QEMU_CLOCK_HOST])
1369
        return;
1370

    
1371
    timeKillEvent(data->timerId);
1372

    
1373
    data->timerId = timeSetEvent(1,
1374
                        data->period,
1375
                        host_alarm_handler,
1376
                        (DWORD)t,
1377
                        TIME_ONESHOT | TIME_PERIODIC);
1378

    
1379
    if (!data->timerId) {
1380
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1381
                GetLastError());
1382

    
1383
        timeEndPeriod(data->period);
1384
        exit(1);
1385
    }
1386
}
1387

    
1388
#endif /* _WIN32 */
1389

    
1390
static int init_timer_alarm(void)
1391
{
1392
    struct qemu_alarm_timer *t = NULL;
1393
    int i, err = -1;
1394

    
1395
    for (i = 0; alarm_timers[i].name; i++) {
1396
        t = &alarm_timers[i];
1397

    
1398
        err = t->start(t);
1399
        if (!err)
1400
            break;
1401
    }
1402

    
1403
    if (err) {
1404
        err = -ENOENT;
1405
        goto fail;
1406
    }
1407

    
1408
    alarm_timer = t;
1409

    
1410
    return 0;
1411

    
1412
fail:
1413
    return err;
1414
}
1415

    
1416
static void quit_timers(void)
1417
{
1418
    alarm_timer->stop(alarm_timer);
1419
    alarm_timer = NULL;
1420
}
1421

    
1422
/***********************************************************/
1423
/* host time/date access */
1424
void qemu_get_timedate(struct tm *tm, int offset)
1425
{
1426
    time_t ti;
1427
    struct tm *ret;
1428

    
1429
    time(&ti);
1430
    ti += offset;
1431
    if (rtc_date_offset == -1) {
1432
        if (rtc_utc)
1433
            ret = gmtime(&ti);
1434
        else
1435
            ret = localtime(&ti);
1436
    } else {
1437
        ti -= rtc_date_offset;
1438
        ret = gmtime(&ti);
1439
    }
1440

    
1441
    memcpy(tm, ret, sizeof(struct tm));
1442
}
1443

    
1444
int qemu_timedate_diff(struct tm *tm)
1445
{
1446
    time_t seconds;
1447

    
1448
    if (rtc_date_offset == -1)
1449
        if (rtc_utc)
1450
            seconds = mktimegm(tm);
1451
        else
1452
            seconds = mktime(tm);
1453
    else
1454
        seconds = mktimegm(tm) + rtc_date_offset;
1455

    
1456
    return seconds - time(NULL);
1457
}
1458

    
1459
static void configure_rtc_date_offset(const char *startdate, int legacy)
1460
{
1461
    time_t rtc_start_date;
1462
    struct tm tm;
1463

    
1464
    if (!strcmp(startdate, "now") && legacy) {
1465
        rtc_date_offset = -1;
1466
    } else {
1467
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1468
                   &tm.tm_year,
1469
                   &tm.tm_mon,
1470
                   &tm.tm_mday,
1471
                   &tm.tm_hour,
1472
                   &tm.tm_min,
1473
                   &tm.tm_sec) == 6) {
1474
            /* OK */
1475
        } else if (sscanf(startdate, "%d-%d-%d",
1476
                          &tm.tm_year,
1477
                          &tm.tm_mon,
1478
                          &tm.tm_mday) == 3) {
1479
            tm.tm_hour = 0;
1480
            tm.tm_min = 0;
1481
            tm.tm_sec = 0;
1482
        } else {
1483
            goto date_fail;
1484
        }
1485
        tm.tm_year -= 1900;
1486
        tm.tm_mon--;
1487
        rtc_start_date = mktimegm(&tm);
1488
        if (rtc_start_date == -1) {
1489
        date_fail:
1490
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1491
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1492
            exit(1);
1493
        }
1494
        rtc_date_offset = time(NULL) - rtc_start_date;
1495
    }
1496
}
1497

    
1498
static void configure_rtc(QemuOpts *opts)
1499
{
1500
    const char *value;
1501

    
1502
    value = qemu_opt_get(opts, "base");
1503
    if (value) {
1504
        if (!strcmp(value, "utc")) {
1505
            rtc_utc = 1;
1506
        } else if (!strcmp(value, "localtime")) {
1507
            rtc_utc = 0;
1508
        } else {
1509
            configure_rtc_date_offset(value, 0);
1510
        }
1511
    }
1512
    value = qemu_opt_get(opts, "clock");
1513
    if (value) {
1514
        if (!strcmp(value, "host")) {
1515
            rtc_clock = host_clock;
1516
        } else if (!strcmp(value, "vm")) {
1517
            rtc_clock = vm_clock;
1518
        } else {
1519
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1520
            exit(1);
1521
        }
1522
    }
1523
#ifdef CONFIG_TARGET_I386
1524
    value = qemu_opt_get(opts, "driftfix");
1525
    if (value) {
1526
        if (!strcmp(buf, "slew")) {
1527
            rtc_td_hack = 1;
1528
        } else if (!strcmp(buf, "none")) {
1529
            rtc_td_hack = 0;
1530
        } else {
1531
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1532
            exit(1);
1533
        }
1534
    }
1535
#endif
1536
}
1537

    
1538
#ifdef _WIN32
1539
static void socket_cleanup(void)
1540
{
1541
    WSACleanup();
1542
}
1543

    
1544
static int socket_init(void)
1545
{
1546
    WSADATA Data;
1547
    int ret, err;
1548

    
1549
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1550
    if (ret != 0) {
1551
        err = WSAGetLastError();
1552
        fprintf(stderr, "WSAStartup: %d\n", err);
1553
        return -1;
1554
    }
1555
    atexit(socket_cleanup);
1556
    return 0;
1557
}
1558
#endif
1559

    
1560
/***********************************************************/
1561
/* Bluetooth support */
1562
static int nb_hcis;
1563
static int cur_hci;
1564
static struct HCIInfo *hci_table[MAX_NICS];
1565

    
1566
static struct bt_vlan_s {
1567
    struct bt_scatternet_s net;
1568
    int id;
1569
    struct bt_vlan_s *next;
1570
} *first_bt_vlan;
1571

    
1572
/* find or alloc a new bluetooth "VLAN" */
1573
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1574
{
1575
    struct bt_vlan_s **pvlan, *vlan;
1576
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1577
        if (vlan->id == id)
1578
            return &vlan->net;
1579
    }
1580
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1581
    vlan->id = id;
1582
    pvlan = &first_bt_vlan;
1583
    while (*pvlan != NULL)
1584
        pvlan = &(*pvlan)->next;
1585
    *pvlan = vlan;
1586
    return &vlan->net;
1587
}
1588

    
1589
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1590
{
1591
}
1592

    
1593
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1594
{
1595
    return -ENOTSUP;
1596
}
1597

    
1598
static struct HCIInfo null_hci = {
1599
    .cmd_send = null_hci_send,
1600
    .sco_send = null_hci_send,
1601
    .acl_send = null_hci_send,
1602
    .bdaddr_set = null_hci_addr_set,
1603
};
1604

    
1605
struct HCIInfo *qemu_next_hci(void)
1606
{
1607
    if (cur_hci == nb_hcis)
1608
        return &null_hci;
1609

    
1610
    return hci_table[cur_hci++];
1611
}
1612

    
1613
static struct HCIInfo *hci_init(const char *str)
1614
{
1615
    char *endp;
1616
    struct bt_scatternet_s *vlan = 0;
1617

    
1618
    if (!strcmp(str, "null"))
1619
        /* null */
1620
        return &null_hci;
1621
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1622
        /* host[:hciN] */
1623
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1624
    else if (!strncmp(str, "hci", 3)) {
1625
        /* hci[,vlan=n] */
1626
        if (str[3]) {
1627
            if (!strncmp(str + 3, ",vlan=", 6)) {
1628
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1629
                if (*endp)
1630
                    vlan = 0;
1631
            }
1632
        } else
1633
            vlan = qemu_find_bt_vlan(0);
1634
        if (vlan)
1635
           return bt_new_hci(vlan);
1636
    }
1637

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

    
1640
    return 0;
1641
}
1642

    
1643
static int bt_hci_parse(const char *str)
1644
{
1645
    struct HCIInfo *hci;
1646
    bdaddr_t bdaddr;
1647

    
1648
    if (nb_hcis >= MAX_NICS) {
1649
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1650
        return -1;
1651
    }
1652

    
1653
    hci = hci_init(str);
1654
    if (!hci)
1655
        return -1;
1656

    
1657
    bdaddr.b[0] = 0x52;
1658
    bdaddr.b[1] = 0x54;
1659
    bdaddr.b[2] = 0x00;
1660
    bdaddr.b[3] = 0x12;
1661
    bdaddr.b[4] = 0x34;
1662
    bdaddr.b[5] = 0x56 + nb_hcis;
1663
    hci->bdaddr_set(hci, bdaddr.b);
1664

    
1665
    hci_table[nb_hcis++] = hci;
1666

    
1667
    return 0;
1668
}
1669

    
1670
static void bt_vhci_add(int vlan_id)
1671
{
1672
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1673

    
1674
    if (!vlan->slave)
1675
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1676
                        "an empty scatternet %i\n", vlan_id);
1677

    
1678
    bt_vhci_init(bt_new_hci(vlan));
1679
}
1680

    
1681
static struct bt_device_s *bt_device_add(const char *opt)
1682
{
1683
    struct bt_scatternet_s *vlan;
1684
    int vlan_id = 0;
1685
    char *endp = strstr(opt, ",vlan=");
1686
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1687
    char devname[10];
1688

    
1689
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1690

    
1691
    if (endp) {
1692
        vlan_id = strtol(endp + 6, &endp, 0);
1693
        if (*endp) {
1694
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1695
            return 0;
1696
        }
1697
    }
1698

    
1699
    vlan = qemu_find_bt_vlan(vlan_id);
1700

    
1701
    if (!vlan->slave)
1702
        fprintf(stderr, "qemu: warning: adding a slave device to "
1703
                        "an empty scatternet %i\n", vlan_id);
1704

    
1705
    if (!strcmp(devname, "keyboard"))
1706
        return bt_keyboard_init(vlan);
1707

    
1708
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1709
    return 0;
1710
}
1711

    
1712
static int bt_parse(const char *opt)
1713
{
1714
    const char *endp, *p;
1715
    int vlan;
1716

    
1717
    if (strstart(opt, "hci", &endp)) {
1718
        if (!*endp || *endp == ',') {
1719
            if (*endp)
1720
                if (!strstart(endp, ",vlan=", 0))
1721
                    opt = endp + 1;
1722

    
1723
            return bt_hci_parse(opt);
1724
       }
1725
    } else if (strstart(opt, "vhci", &endp)) {
1726
        if (!*endp || *endp == ',') {
1727
            if (*endp) {
1728
                if (strstart(endp, ",vlan=", &p)) {
1729
                    vlan = strtol(p, (char **) &endp, 0);
1730
                    if (*endp) {
1731
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1732
                        return 1;
1733
                    }
1734
                } else {
1735
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1736
                    return 1;
1737
                }
1738
            } else
1739
                vlan = 0;
1740

    
1741
            bt_vhci_add(vlan);
1742
            return 0;
1743
        }
1744
    } else if (strstart(opt, "device:", &endp))
1745
        return !bt_device_add(endp);
1746

    
1747
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1748
    return 1;
1749
}
1750

    
1751
/***********************************************************/
1752
/* QEMU Block devices */
1753

    
1754
#define HD_ALIAS "index=%d,media=disk"
1755
#define CDROM_ALIAS "index=2,media=cdrom"
1756
#define FD_ALIAS "index=%d,if=floppy"
1757
#define PFLASH_ALIAS "if=pflash"
1758
#define MTD_ALIAS "if=mtd"
1759
#define SD_ALIAS "index=0,if=sd"
1760

    
1761
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1762
{
1763
    va_list ap;
1764
    char optstr[1024];
1765
    QemuOpts *opts;
1766

    
1767
    va_start(ap, fmt);
1768
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1769
    va_end(ap);
1770

    
1771
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1772
    if (!opts) {
1773
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1774
                __FUNCTION__, optstr);
1775
        return NULL;
1776
    }
1777
    if (file)
1778
        qemu_opt_set(opts, "file", file);
1779
    return opts;
1780
}
1781

    
1782
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1783
{
1784
    DriveInfo *dinfo;
1785

    
1786
    /* seek interface, bus and unit */
1787

    
1788
    QTAILQ_FOREACH(dinfo, &drives, next) {
1789
        if (dinfo->type == type &&
1790
            dinfo->bus == bus &&
1791
            dinfo->unit == unit)
1792
            return dinfo;
1793
    }
1794

    
1795
    return NULL;
1796
}
1797

    
1798
DriveInfo *drive_get_by_id(const char *id)
1799
{
1800
    DriveInfo *dinfo;
1801

    
1802
    QTAILQ_FOREACH(dinfo, &drives, next) {
1803
        if (strcmp(id, dinfo->id))
1804
            continue;
1805
        return dinfo;
1806
    }
1807
    return NULL;
1808
}
1809

    
1810
int drive_get_max_bus(BlockInterfaceType type)
1811
{
1812
    int max_bus;
1813
    DriveInfo *dinfo;
1814

    
1815
    max_bus = -1;
1816
    QTAILQ_FOREACH(dinfo, &drives, next) {
1817
        if(dinfo->type == type &&
1818
           dinfo->bus > max_bus)
1819
            max_bus = dinfo->bus;
1820
    }
1821
    return max_bus;
1822
}
1823

    
1824
const char *drive_get_serial(BlockDriverState *bdrv)
1825
{
1826
    DriveInfo *dinfo;
1827

    
1828
    QTAILQ_FOREACH(dinfo, &drives, next) {
1829
        if (dinfo->bdrv == bdrv)
1830
            return dinfo->serial;
1831
    }
1832

    
1833
    return "\0";
1834
}
1835

    
1836
BlockInterfaceErrorAction drive_get_on_error(
1837
    BlockDriverState *bdrv, int is_read)
1838
{
1839
    DriveInfo *dinfo;
1840

    
1841
    QTAILQ_FOREACH(dinfo, &drives, next) {
1842
        if (dinfo->bdrv == bdrv)
1843
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
1844
    }
1845

    
1846
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
1847
}
1848

    
1849
static void bdrv_format_print(void *opaque, const char *name)
1850
{
1851
    fprintf(stderr, " %s", name);
1852
}
1853

    
1854
void drive_uninit(DriveInfo *dinfo)
1855
{
1856
    qemu_opts_del(dinfo->opts);
1857
    bdrv_delete(dinfo->bdrv);
1858
    QTAILQ_REMOVE(&drives, dinfo, next);
1859
    qemu_free(dinfo);
1860
}
1861

    
1862
static int parse_block_error_action(const char *buf, int is_read)
1863
{
1864
    if (!strcmp(buf, "ignore")) {
1865
        return BLOCK_ERR_IGNORE;
1866
    } else if (!is_read && !strcmp(buf, "enospc")) {
1867
        return BLOCK_ERR_STOP_ENOSPC;
1868
    } else if (!strcmp(buf, "stop")) {
1869
        return BLOCK_ERR_STOP_ANY;
1870
    } else if (!strcmp(buf, "report")) {
1871
        return BLOCK_ERR_REPORT;
1872
    } else {
1873
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
1874
            buf, is_read ? "read" : "write");
1875
        return -1;
1876
    }
1877
}
1878

    
1879
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1880
                      int *fatal_error)
1881
{
1882
    const char *buf;
1883
    const char *file = NULL;
1884
    char devname[128];
1885
    const char *serial;
1886
    const char *mediastr = "";
1887
    BlockInterfaceType type;
1888
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1889
    int bus_id, unit_id;
1890
    int cyls, heads, secs, translation;
1891
    BlockDriver *drv = NULL;
1892
    QEMUMachine *machine = opaque;
1893
    int max_devs;
1894
    int index;
1895
    int cache;
1896
    int aio = 0;
1897
    int ro = 0;
1898
    int bdrv_flags;
1899
    int on_read_error, on_write_error;
1900
    const char *devaddr;
1901
    DriveInfo *dinfo;
1902
    int snapshot = 0;
1903

    
1904
    *fatal_error = 1;
1905

    
1906
    translation = BIOS_ATA_TRANSLATION_AUTO;
1907
    cache = 1;
1908

    
1909
    if (machine && machine->use_scsi) {
1910
        type = IF_SCSI;
1911
        max_devs = MAX_SCSI_DEVS;
1912
        pstrcpy(devname, sizeof(devname), "scsi");
1913
    } else {
1914
        type = IF_IDE;
1915
        max_devs = MAX_IDE_DEVS;
1916
        pstrcpy(devname, sizeof(devname), "ide");
1917
    }
1918
    media = MEDIA_DISK;
1919

    
1920
    /* extract parameters */
1921
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1922
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1923
    index   = qemu_opt_get_number(opts, "index", -1);
1924

    
1925
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1926
    heads = qemu_opt_get_number(opts, "heads", 0);
1927
    secs  = qemu_opt_get_number(opts, "secs", 0);
1928

    
1929
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1930
    ro = qemu_opt_get_bool(opts, "readonly", 0);
1931

    
1932
    file = qemu_opt_get(opts, "file");
1933
    serial = qemu_opt_get(opts, "serial");
1934

    
1935
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1936
        pstrcpy(devname, sizeof(devname), buf);
1937
        if (!strcmp(buf, "ide")) {
1938
            type = IF_IDE;
1939
            max_devs = MAX_IDE_DEVS;
1940
        } else if (!strcmp(buf, "scsi")) {
1941
            type = IF_SCSI;
1942
            max_devs = MAX_SCSI_DEVS;
1943
        } else if (!strcmp(buf, "floppy")) {
1944
            type = IF_FLOPPY;
1945
            max_devs = 0;
1946
        } else if (!strcmp(buf, "pflash")) {
1947
            type = IF_PFLASH;
1948
            max_devs = 0;
1949
        } else if (!strcmp(buf, "mtd")) {
1950
            type = IF_MTD;
1951
            max_devs = 0;
1952
        } else if (!strcmp(buf, "sd")) {
1953
            type = IF_SD;
1954
            max_devs = 0;
1955
        } else if (!strcmp(buf, "virtio")) {
1956
            type = IF_VIRTIO;
1957
            max_devs = 0;
1958
        } else if (!strcmp(buf, "xen")) {
1959
            type = IF_XEN;
1960
            max_devs = 0;
1961
        } else if (!strcmp(buf, "none")) {
1962
            type = IF_NONE;
1963
            max_devs = 0;
1964
        } else {
1965
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1966
            return NULL;
1967
        }
1968
    }
1969

    
1970
    if (cyls || heads || secs) {
1971
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
1972
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1973
            return NULL;
1974
        }
1975
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
1976
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1977
            return NULL;
1978
        }
1979
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
1980
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1981
            return NULL;
1982
        }
1983
    }
1984

    
1985
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1986
        if (!cyls) {
1987
            fprintf(stderr,
1988
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
1989
                    buf);
1990
            return NULL;
1991
        }
1992
        if (!strcmp(buf, "none"))
1993
            translation = BIOS_ATA_TRANSLATION_NONE;
1994
        else if (!strcmp(buf, "lba"))
1995
            translation = BIOS_ATA_TRANSLATION_LBA;
1996
        else if (!strcmp(buf, "auto"))
1997
            translation = BIOS_ATA_TRANSLATION_AUTO;
1998
        else {
1999
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2000
            return NULL;
2001
        }
2002
    }
2003

    
2004
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2005
        if (!strcmp(buf, "disk")) {
2006
            media = MEDIA_DISK;
2007
        } else if (!strcmp(buf, "cdrom")) {
2008
            if (cyls || secs || heads) {
2009
                fprintf(stderr,
2010
                        "qemu: '%s' invalid physical CHS format\n", buf);
2011
                return NULL;
2012
            }
2013
            media = MEDIA_CDROM;
2014
        } else {
2015
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2016
            return NULL;
2017
        }
2018
    }
2019

    
2020
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2021
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2022
            cache = 0;
2023
        else if (!strcmp(buf, "writethrough"))
2024
            cache = 1;
2025
        else if (!strcmp(buf, "writeback"))
2026
            cache = 2;
2027
        else {
2028
           fprintf(stderr, "qemu: invalid cache option\n");
2029
           return NULL;
2030
        }
2031
    }
2032

    
2033
#ifdef CONFIG_LINUX_AIO
2034
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2035
        if (!strcmp(buf, "threads"))
2036
            aio = 0;
2037
        else if (!strcmp(buf, "native"))
2038
            aio = 1;
2039
        else {
2040
           fprintf(stderr, "qemu: invalid aio option\n");
2041
           return NULL;
2042
        }
2043
    }
2044
#endif
2045

    
2046
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2047
       if (strcmp(buf, "?") == 0) {
2048
            fprintf(stderr, "qemu: Supported formats:");
2049
            bdrv_iterate_format(bdrv_format_print, NULL);
2050
            fprintf(stderr, "\n");
2051
            return NULL;
2052
        }
2053
        drv = bdrv_find_whitelisted_format(buf);
2054
        if (!drv) {
2055
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2056
            return NULL;
2057
        }
2058
    }
2059

    
2060
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2061
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2062
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2063
            fprintf(stderr, "werror is no supported by this format\n");
2064
            return NULL;
2065
        }
2066

    
2067
        on_write_error = parse_block_error_action(buf, 0);
2068
        if (on_write_error < 0) {
2069
            return NULL;
2070
        }
2071
    }
2072

    
2073
    on_read_error = BLOCK_ERR_REPORT;
2074
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2075
        if (type != IF_IDE && type != IF_VIRTIO) {
2076
            fprintf(stderr, "rerror is no supported by this format\n");
2077
            return NULL;
2078
        }
2079

    
2080
        on_read_error = parse_block_error_action(buf, 1);
2081
        if (on_read_error < 0) {
2082
            return NULL;
2083
        }
2084
    }
2085

    
2086
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2087
        if (type != IF_VIRTIO) {
2088
            fprintf(stderr, "addr is not supported\n");
2089
            return NULL;
2090
        }
2091
    }
2092

    
2093
    /* compute bus and unit according index */
2094

    
2095
    if (index != -1) {
2096
        if (bus_id != 0 || unit_id != -1) {
2097
            fprintf(stderr,
2098
                    "qemu: index cannot be used with bus and unit\n");
2099
            return NULL;
2100
        }
2101
        if (max_devs == 0)
2102
        {
2103
            unit_id = index;
2104
            bus_id = 0;
2105
        } else {
2106
            unit_id = index % max_devs;
2107
            bus_id = index / max_devs;
2108
        }
2109
    }
2110

    
2111
    /* if user doesn't specify a unit_id,
2112
     * try to find the first free
2113
     */
2114

    
2115
    if (unit_id == -1) {
2116
       unit_id = 0;
2117
       while (drive_get(type, bus_id, unit_id) != NULL) {
2118
           unit_id++;
2119
           if (max_devs && unit_id >= max_devs) {
2120
               unit_id -= max_devs;
2121
               bus_id++;
2122
           }
2123
       }
2124
    }
2125

    
2126
    /* check unit id */
2127

    
2128
    if (max_devs && unit_id >= max_devs) {
2129
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2130
                unit_id, max_devs - 1);
2131
        return NULL;
2132
    }
2133

    
2134
    /*
2135
     * ignore multiple definitions
2136
     */
2137

    
2138
    if (drive_get(type, bus_id, unit_id) != NULL) {
2139
        *fatal_error = 0;
2140
        return NULL;
2141
    }
2142

    
2143
    /* init */
2144

    
2145
    dinfo = qemu_mallocz(sizeof(*dinfo));
2146
    if ((buf = qemu_opts_id(opts)) != NULL) {
2147
        dinfo->id = qemu_strdup(buf);
2148
    } else {
2149
        /* no id supplied -> create one */
2150
        dinfo->id = qemu_mallocz(32);
2151
        if (type == IF_IDE || type == IF_SCSI)
2152
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2153
        if (max_devs)
2154
            snprintf(dinfo->id, 32, "%s%i%s%i",
2155
                     devname, bus_id, mediastr, unit_id);
2156
        else
2157
            snprintf(dinfo->id, 32, "%s%s%i",
2158
                     devname, mediastr, unit_id);
2159
    }
2160
    dinfo->bdrv = bdrv_new(dinfo->id);
2161
    dinfo->devaddr = devaddr;
2162
    dinfo->type = type;
2163
    dinfo->bus = bus_id;
2164
    dinfo->unit = unit_id;
2165
    dinfo->on_read_error = on_read_error;
2166
    dinfo->on_write_error = on_write_error;
2167
    dinfo->opts = opts;
2168
    if (serial)
2169
        strncpy(dinfo->serial, serial, sizeof(serial));
2170
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2171

    
2172
    switch(type) {
2173
    case IF_IDE:
2174
    case IF_SCSI:
2175
    case IF_XEN:
2176
    case IF_NONE:
2177
        switch(media) {
2178
        case MEDIA_DISK:
2179
            if (cyls != 0) {
2180
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2181
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2182
            }
2183
            break;
2184
        case MEDIA_CDROM:
2185
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2186
            break;
2187
        }
2188
        break;
2189
    case IF_SD:
2190
        /* FIXME: This isn't really a floppy, but it's a reasonable
2191
           approximation.  */
2192
    case IF_FLOPPY:
2193
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2194
        break;
2195
    case IF_PFLASH:
2196
    case IF_MTD:
2197
        break;
2198
    case IF_VIRTIO:
2199
        /* add virtio block device */
2200
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2201
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
2202
        qemu_opt_set(opts, "drive", dinfo->id);
2203
        if (devaddr)
2204
            qemu_opt_set(opts, "addr", devaddr);
2205
        break;
2206
    case IF_COUNT:
2207
        abort();
2208
    }
2209
    if (!file) {
2210
        *fatal_error = 0;
2211
        return NULL;
2212
    }
2213
    bdrv_flags = 0;
2214
    if (snapshot) {
2215
        bdrv_flags |= BDRV_O_SNAPSHOT;
2216
        cache = 2; /* always use write-back with snapshot */
2217
    }
2218
    if (cache == 0) /* no caching */
2219
        bdrv_flags |= BDRV_O_NOCACHE;
2220
    else if (cache == 2) /* write-back */
2221
        bdrv_flags |= BDRV_O_CACHE_WB;
2222

    
2223
    if (aio == 1) {
2224
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2225
    } else {
2226
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2227
    }
2228

    
2229
    if (ro == 1) {
2230
        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY) {
2231
            fprintf(stderr, "qemu: readonly flag not supported for drive with this interface\n");
2232
            return NULL;
2233
        }
2234
    }
2235
    /* 
2236
     * cdrom is read-only. Set it now, after above interface checking
2237
     * since readonly attribute not explicitly required, so no error.
2238
     */
2239
    if (media == MEDIA_CDROM) {
2240
        ro = 1;
2241
    }
2242
    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
2243

    
2244
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2245
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2246
                        file, strerror(errno));
2247
        return NULL;
2248
    }
2249

    
2250
    if (bdrv_key_required(dinfo->bdrv))
2251
        autostart = 0;
2252
    *fatal_error = 0;
2253
    return dinfo;
2254
}
2255

    
2256
static int drive_init_func(QemuOpts *opts, void *opaque)
2257
{
2258
    QEMUMachine *machine = opaque;
2259
    int fatal_error = 0;
2260

    
2261
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2262
        if (fatal_error)
2263
            return 1;
2264
    }
2265
    return 0;
2266
}
2267

    
2268
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2269
{
2270
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2271
        qemu_opt_set(opts, "snapshot", "on");
2272
    }
2273
    return 0;
2274
}
2275

    
2276
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2277
{
2278
    boot_set_handler = func;
2279
    boot_set_opaque = opaque;
2280
}
2281

    
2282
int qemu_boot_set(const char *boot_devices)
2283
{
2284
    if (!boot_set_handler) {
2285
        return -EINVAL;
2286
    }
2287
    return boot_set_handler(boot_set_opaque, boot_devices);
2288
}
2289

    
2290
static int parse_bootdevices(char *devices)
2291
{
2292
    /* We just do some generic consistency checks */
2293
    const char *p;
2294
    int bitmap = 0;
2295

    
2296
    for (p = devices; *p != '\0'; p++) {
2297
        /* Allowed boot devices are:
2298
         * a-b: floppy disk drives
2299
         * c-f: IDE disk drives
2300
         * g-m: machine implementation dependant drives
2301
         * n-p: network devices
2302
         * It's up to each machine implementation to check if the given boot
2303
         * devices match the actual hardware implementation and firmware
2304
         * features.
2305
         */
2306
        if (*p < 'a' || *p > 'p') {
2307
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2308
            exit(1);
2309
        }
2310
        if (bitmap & (1 << (*p - 'a'))) {
2311
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2312
            exit(1);
2313
        }
2314
        bitmap |= 1 << (*p - 'a');
2315
    }
2316
    return bitmap;
2317
}
2318

    
2319
static void restore_boot_devices(void *opaque)
2320
{
2321
    char *standard_boot_devices = opaque;
2322

    
2323
    qemu_boot_set(standard_boot_devices);
2324

    
2325
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2326
    qemu_free(standard_boot_devices);
2327
}
2328

    
2329
static void numa_add(const char *optarg)
2330
{
2331
    char option[128];
2332
    char *endptr;
2333
    unsigned long long value, endvalue;
2334
    int nodenr;
2335

    
2336
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2337
    if (!strcmp(option, "node")) {
2338
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2339
            nodenr = nb_numa_nodes;
2340
        } else {
2341
            nodenr = strtoull(option, NULL, 10);
2342
        }
2343

    
2344
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2345
            node_mem[nodenr] = 0;
2346
        } else {
2347
            value = strtoull(option, &endptr, 0);
2348
            switch (*endptr) {
2349
            case 0: case 'M': case 'm':
2350
                value <<= 20;
2351
                break;
2352
            case 'G': case 'g':
2353
                value <<= 30;
2354
                break;
2355
            }
2356
            node_mem[nodenr] = value;
2357
        }
2358
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2359
            node_cpumask[nodenr] = 0;
2360
        } else {
2361
            value = strtoull(option, &endptr, 10);
2362
            if (value >= 64) {
2363
                value = 63;
2364
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2365
            } else {
2366
                if (*endptr == '-') {
2367
                    endvalue = strtoull(endptr+1, &endptr, 10);
2368
                    if (endvalue >= 63) {
2369
                        endvalue = 62;
2370
                        fprintf(stderr,
2371
                            "only 63 CPUs in NUMA mode supported.\n");
2372
                    }
2373
                    value = (1 << (endvalue + 1)) - (1 << value);
2374
                } else {
2375
                    value = 1 << value;
2376
                }
2377
            }
2378
            node_cpumask[nodenr] = value;
2379
        }
2380
        nb_numa_nodes++;
2381
    }
2382
    return;
2383
}
2384

    
2385
static void smp_parse(const char *optarg)
2386
{
2387
    int smp, sockets = 0, threads = 0, cores = 0;
2388
    char *endptr;
2389
    char option[128];
2390

    
2391
    smp = strtoul(optarg, &endptr, 10);
2392
    if (endptr != optarg) {
2393
        if (*endptr == ',') {
2394
            endptr++;
2395
        }
2396
    }
2397
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2398
        sockets = strtoull(option, NULL, 10);
2399
    if (get_param_value(option, 128, "cores", endptr) != 0)
2400
        cores = strtoull(option, NULL, 10);
2401
    if (get_param_value(option, 128, "threads", endptr) != 0)
2402
        threads = strtoull(option, NULL, 10);
2403
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2404
        max_cpus = strtoull(option, NULL, 10);
2405

    
2406
    /* compute missing values, prefer sockets over cores over threads */
2407
    if (smp == 0 || sockets == 0) {
2408
        sockets = sockets > 0 ? sockets : 1;
2409
        cores = cores > 0 ? cores : 1;
2410
        threads = threads > 0 ? threads : 1;
2411
        if (smp == 0) {
2412
            smp = cores * threads * sockets;
2413
        }
2414
    } else {
2415
        if (cores == 0) {
2416
            threads = threads > 0 ? threads : 1;
2417
            cores = smp / (sockets * threads);
2418
        } else {
2419
            if (sockets) {
2420
                threads = smp / (cores * sockets);
2421
            }
2422
        }
2423
    }
2424
    smp_cpus = smp;
2425
    smp_cores = cores > 0 ? cores : 1;
2426
    smp_threads = threads > 0 ? threads : 1;
2427
    if (max_cpus == 0)
2428
        max_cpus = smp_cpus;
2429
}
2430

    
2431
/***********************************************************/
2432
/* USB devices */
2433

    
2434
static int usb_device_add(const char *devname, int is_hotplug)
2435
{
2436
    const char *p;
2437
    USBDevice *dev = NULL;
2438

    
2439
    if (!usb_enabled)
2440
        return -1;
2441

    
2442
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2443
    dev = usbdevice_create(devname);
2444
    if (dev)
2445
        goto done;
2446

    
2447
    /* the other ones */
2448
    if (strstart(devname, "host:", &p)) {
2449
        dev = usb_host_device_open(p);
2450
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2451
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2452
                        bt_new_hci(qemu_find_bt_vlan(0)));
2453
    } else {
2454
        return -1;
2455
    }
2456
    if (!dev)
2457
        return -1;
2458

    
2459
done:
2460
    return 0;
2461
}
2462

    
2463
static int usb_device_del(const char *devname)
2464
{
2465
    int bus_num, addr;
2466
    const char *p;
2467

    
2468
    if (strstart(devname, "host:", &p))
2469
        return usb_host_device_close(p);
2470

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

    
2474
    p = strchr(devname, '.');
2475
    if (!p)
2476
        return -1;
2477
    bus_num = strtoul(devname, NULL, 0);
2478
    addr = strtoul(p + 1, NULL, 0);
2479

    
2480
    return usb_device_delete_addr(bus_num, addr);
2481
}
2482

    
2483
static int usb_parse(const char *cmdline)
2484
{
2485
    int r;
2486
    r = usb_device_add(cmdline, 0);
2487
    if (r < 0) {
2488
        fprintf(stderr, "qemu: could not add USB device '%s'\n", cmdline);
2489
    }
2490
    return r;
2491
}
2492

    
2493
void do_usb_add(Monitor *mon, const QDict *qdict)
2494
{
2495
    const char *devname = qdict_get_str(qdict, "devname");
2496
    if (usb_device_add(devname, 1) < 0) {
2497
        qemu_error("could not add USB device '%s'\n", devname);
2498
    }
2499
}
2500

    
2501
void do_usb_del(Monitor *mon, const QDict *qdict)
2502
{
2503
    const char *devname = qdict_get_str(qdict, "devname");
2504
    if (usb_device_del(devname) < 0) {
2505
        qemu_error("could not delete USB device '%s'\n", devname);
2506
    }
2507
}
2508

    
2509
/***********************************************************/
2510
/* PCMCIA/Cardbus */
2511

    
2512
static struct pcmcia_socket_entry_s {
2513
    PCMCIASocket *socket;
2514
    struct pcmcia_socket_entry_s *next;
2515
} *pcmcia_sockets = 0;
2516

    
2517
void pcmcia_socket_register(PCMCIASocket *socket)
2518
{
2519
    struct pcmcia_socket_entry_s *entry;
2520

    
2521
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2522
    entry->socket = socket;
2523
    entry->next = pcmcia_sockets;
2524
    pcmcia_sockets = entry;
2525
}
2526

    
2527
void pcmcia_socket_unregister(PCMCIASocket *socket)
2528
{
2529
    struct pcmcia_socket_entry_s *entry, **ptr;
2530

    
2531
    ptr = &pcmcia_sockets;
2532
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2533
        if (entry->socket == socket) {
2534
            *ptr = entry->next;
2535
            qemu_free(entry);
2536
        }
2537
}
2538

    
2539
void pcmcia_info(Monitor *mon)
2540
{
2541
    struct pcmcia_socket_entry_s *iter;
2542

    
2543
    if (!pcmcia_sockets)
2544
        monitor_printf(mon, "No PCMCIA sockets\n");
2545

    
2546
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2547
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2548
                       iter->socket->attached ? iter->socket->card_string :
2549
                       "Empty");
2550
}
2551

    
2552
/***********************************************************/
2553
/* register display */
2554

    
2555
struct DisplayAllocator default_allocator = {
2556
    defaultallocator_create_displaysurface,
2557
    defaultallocator_resize_displaysurface,
2558
    defaultallocator_free_displaysurface
2559
};
2560

    
2561
void register_displaystate(DisplayState *ds)
2562
{
2563
    DisplayState **s;
2564
    s = &display_state;
2565
    while (*s != NULL)
2566
        s = &(*s)->next;
2567
    ds->next = NULL;
2568
    *s = ds;
2569
}
2570

    
2571
DisplayState *get_displaystate(void)
2572
{
2573
    return display_state;
2574
}
2575

    
2576
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2577
{
2578
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2579
    return ds->allocator;
2580
}
2581

    
2582
/* dumb display */
2583

    
2584
static void dumb_display_init(void)
2585
{
2586
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2587
    ds->allocator = &default_allocator;
2588
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2589
    register_displaystate(ds);
2590
}
2591

    
2592
/***********************************************************/
2593
/* I/O handling */
2594

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

    
2607
static IOHandlerRecord *first_io_handler;
2608

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

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

    
2650
int qemu_set_fd_handler(int fd,
2651
                        IOHandler *fd_read,
2652
                        IOHandler *fd_write,
2653
                        void *opaque)
2654
{
2655
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2656
}
2657

    
2658
#ifdef _WIN32
2659
/***********************************************************/
2660
/* Polling handling */
2661

    
2662
typedef struct PollingEntry {
2663
    PollingFunc *func;
2664
    void *opaque;
2665
    struct PollingEntry *next;
2666
} PollingEntry;
2667

    
2668
static PollingEntry *first_polling_entry;
2669

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

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

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

    
2703
static WaitObjects wait_objects = {0};
2704

    
2705
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2706
{
2707
    WaitObjects *w = &wait_objects;
2708

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

    
2718
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2719
{
2720
    int i, found;
2721
    WaitObjects *w = &wait_objects;
2722

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

    
2738
/***********************************************************/
2739
/* ram save/restore */
2740

    
2741
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2742
#define RAM_SAVE_FLAG_COMPRESS        0x02
2743
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2744
#define RAM_SAVE_FLAG_PAGE        0x08
2745
#define RAM_SAVE_FLAG_EOS        0x10
2746

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

    
2753
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2754
        if (array[i] != val)
2755
            return 0;
2756
    }
2757

    
2758
    return 1;
2759
}
2760

    
2761
static int ram_save_block(QEMUFile *f)
2762
{
2763
    static ram_addr_t current_addr = 0;
2764
    ram_addr_t saved_addr = current_addr;
2765
    ram_addr_t addr = 0;
2766
    int found = 0;
2767

    
2768
    while (addr < last_ram_offset) {
2769
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2770
            uint8_t *p;
2771

    
2772
            cpu_physical_memory_reset_dirty(current_addr,
2773
                                            current_addr + TARGET_PAGE_SIZE,
2774
                                            MIGRATION_DIRTY_FLAG);
2775

    
2776
            p = qemu_get_ram_ptr(current_addr);
2777

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

    
2786
            found = 1;
2787
            break;
2788
        }
2789
        addr += TARGET_PAGE_SIZE;
2790
        current_addr = (saved_addr + addr) % last_ram_offset;
2791
    }
2792

    
2793
    return found;
2794
}
2795

    
2796
static uint64_t bytes_transferred;
2797

    
2798
static ram_addr_t ram_save_remaining(void)
2799
{
2800
    ram_addr_t addr;
2801
    ram_addr_t count = 0;
2802

    
2803
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2804
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2805
            count++;
2806
    }
2807

    
2808
    return count;
2809
}
2810

    
2811
uint64_t ram_bytes_remaining(void)
2812
{
2813
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2814
}
2815

    
2816
uint64_t ram_bytes_transferred(void)
2817
{
2818
    return bytes_transferred;
2819
}
2820

    
2821
uint64_t ram_bytes_total(void)
2822
{
2823
    return last_ram_offset;
2824
}
2825

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

    
2833
    if (stage < 0) {
2834
        cpu_physical_memory_set_dirty_tracking(0);
2835
        return 0;
2836
    }
2837

    
2838
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2839
        qemu_file_set_error(f);
2840
        return 0;
2841
    }
2842

    
2843
    if (stage == 1) {
2844
        bytes_transferred = 0;
2845

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

    
2852
        /* Enable dirty memory tracking */
2853
        cpu_physical_memory_set_dirty_tracking(1);
2854

    
2855
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2856
    }
2857

    
2858
    bytes_transferred_last = bytes_transferred;
2859
    bwidth = get_clock();
2860

    
2861
    while (!qemu_file_rate_limit(f)) {
2862
        int ret;
2863

    
2864
        ret = ram_save_block(f);
2865
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2866
        if (ret == 0) /* no more blocks */
2867
            break;
2868
    }
2869

    
2870
    bwidth = get_clock() - bwidth;
2871
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2872

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

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

    
2887
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2888

    
2889
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2890

    
2891
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2892
}
2893

    
2894
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2895
{
2896
    ram_addr_t addr;
2897
    int flags;
2898

    
2899
    if (version_id != 3)
2900
        return -EINVAL;
2901

    
2902
    do {
2903
        addr = qemu_get_be64(f);
2904

    
2905
        flags = addr & ~TARGET_PAGE_MASK;
2906
        addr &= TARGET_PAGE_MASK;
2907

    
2908
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2909
            if (addr != last_ram_offset)
2910
                return -EINVAL;
2911
        }
2912

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

    
2930
    return 0;
2931
}
2932

    
2933
void qemu_service_io(void)
2934
{
2935
    qemu_notify_event();
2936
}
2937

    
2938
/***********************************************************/
2939
/* machine registration */
2940

    
2941
static QEMUMachine *first_machine = NULL;
2942
QEMUMachine *current_machine = NULL;
2943

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

    
2955
static QEMUMachine *find_machine(const char *name)
2956
{
2957
    QEMUMachine *m;
2958

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

    
2968
static QEMUMachine *find_default_machine(void)
2969
{
2970
    QEMUMachine *m;
2971

    
2972
    for(m = first_machine; m != NULL; m = m->next) {
2973
        if (m->is_default) {
2974
            return m;
2975
        }
2976
    }
2977
    return NULL;
2978
}
2979

    
2980
/***********************************************************/
2981
/* main execution loop */
2982

    
2983
static void gui_update(void *opaque)
2984
{
2985
    uint64_t interval = GUI_REFRESH_INTERVAL;
2986
    DisplayState *ds = opaque;
2987
    DisplayChangeListener *dcl = ds->listeners;
2988

    
2989
    dpy_refresh(ds);
2990

    
2991
    while (dcl != NULL) {
2992
        if (dcl->gui_timer_interval &&
2993
            dcl->gui_timer_interval < interval)
2994
            interval = dcl->gui_timer_interval;
2995
        dcl = dcl->next;
2996
    }
2997
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
2998
}
2999

    
3000
static void nographic_update(void *opaque)
3001
{
3002
    uint64_t interval = GUI_REFRESH_INTERVAL;
3003

    
3004
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3005
}
3006

    
3007
struct vm_change_state_entry {
3008
    VMChangeStateHandler *cb;
3009
    void *opaque;
3010
    QLIST_ENTRY (vm_change_state_entry) entries;
3011
};
3012

    
3013
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3014

    
3015
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3016
                                                     void *opaque)
3017
{
3018
    VMChangeStateEntry *e;
3019

    
3020
    e = qemu_mallocz(sizeof (*e));
3021

    
3022
    e->cb = cb;
3023
    e->opaque = opaque;
3024
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3025
    return e;
3026
}
3027

    
3028
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3029
{
3030
    QLIST_REMOVE (e, entries);
3031
    qemu_free (e);
3032
}
3033

    
3034
static void vm_state_notify(int running, int reason)
3035
{
3036
    VMChangeStateEntry *e;
3037

    
3038
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3039
        e->cb(e->opaque, running, reason);
3040
    }
3041
}
3042

    
3043
static void resume_all_vcpus(void);
3044
static void pause_all_vcpus(void);
3045

    
3046
void vm_start(void)
3047
{
3048
    if (!vm_running) {
3049
        cpu_enable_ticks();
3050
        vm_running = 1;
3051
        vm_state_notify(1, 0);
3052
        qemu_rearm_alarm_timer(alarm_timer);
3053
        resume_all_vcpus();
3054
    }
3055
}
3056

    
3057
/* reset/shutdown handler */
3058

    
3059
typedef struct QEMUResetEntry {
3060
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3061
    QEMUResetHandler *func;
3062
    void *opaque;
3063
} QEMUResetEntry;
3064

    
3065
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3066
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3067
static int reset_requested;
3068
static int shutdown_requested;
3069
static int powerdown_requested;
3070
static int debug_requested;
3071
static int vmstop_requested;
3072

    
3073
int qemu_shutdown_requested(void)
3074
{
3075
    int r = shutdown_requested;
3076
    shutdown_requested = 0;
3077
    return r;
3078
}
3079

    
3080
int qemu_reset_requested(void)
3081
{
3082
    int r = reset_requested;
3083
    reset_requested = 0;
3084
    return r;
3085
}
3086

    
3087
int qemu_powerdown_requested(void)
3088
{
3089
    int r = powerdown_requested;
3090
    powerdown_requested = 0;
3091
    return r;
3092
}
3093

    
3094
static int qemu_debug_requested(void)
3095
{
3096
    int r = debug_requested;
3097
    debug_requested = 0;
3098
    return r;
3099
}
3100

    
3101
static int qemu_vmstop_requested(void)
3102
{
3103
    int r = vmstop_requested;
3104
    vmstop_requested = 0;
3105
    return r;
3106
}
3107

    
3108
static void do_vm_stop(int reason)
3109
{
3110
    if (vm_running) {
3111
        cpu_disable_ticks();
3112
        vm_running = 0;
3113
        pause_all_vcpus();
3114
        vm_state_notify(0, reason);
3115
    }
3116
}
3117

    
3118
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3119
{
3120
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3121

    
3122
    re->func = func;
3123
    re->opaque = opaque;
3124
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3125
}
3126

    
3127
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3128
{
3129
    QEMUResetEntry *re;
3130

    
3131
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3132
        if (re->func == func && re->opaque == opaque) {
3133
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3134
            qemu_free(re);
3135
            return;
3136
        }
3137
    }
3138
}
3139

    
3140
void qemu_system_reset(void)
3141
{
3142
    QEMUResetEntry *re, *nre;
3143

    
3144
    /* reset all devices */
3145
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3146
        re->func(re->opaque);
3147
    }
3148
}
3149

    
3150
void qemu_system_reset_request(void)
3151
{
3152
    if (no_reboot) {
3153
        shutdown_requested = 1;
3154
    } else {
3155
        reset_requested = 1;
3156
    }
3157
    qemu_notify_event();
3158
}
3159

    
3160
void qemu_system_shutdown_request(void)
3161
{
3162
    shutdown_requested = 1;
3163
    qemu_notify_event();
3164
}
3165

    
3166
void qemu_system_powerdown_request(void)
3167
{
3168
    powerdown_requested = 1;
3169
    qemu_notify_event();
3170
}
3171

    
3172
#ifdef CONFIG_IOTHREAD
3173
static void qemu_system_vmstop_request(int reason)
3174
{
3175
    vmstop_requested = reason;
3176
    qemu_notify_event();
3177
}
3178
#endif
3179

    
3180
#ifndef _WIN32
3181
static int io_thread_fd = -1;
3182

    
3183
static void qemu_event_increment(void)
3184
{
3185
    static const char byte = 0;
3186

    
3187
    if (io_thread_fd == -1)
3188
        return;
3189

    
3190
    write(io_thread_fd, &byte, sizeof(byte));
3191
}
3192

    
3193
static void qemu_event_read(void *opaque)
3194
{
3195
    int fd = (unsigned long)opaque;
3196
    ssize_t len;
3197

    
3198
    /* Drain the notify pipe */
3199
    do {
3200
        char buffer[512];
3201
        len = read(fd, buffer, sizeof(buffer));
3202
    } while ((len == -1 && errno == EINTR) || len > 0);
3203
}
3204

    
3205
static int qemu_event_init(void)
3206
{
3207
    int err;
3208
    int fds[2];
3209

    
3210
    err = qemu_pipe(fds);
3211
    if (err == -1)
3212
        return -errno;
3213

    
3214
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3215
    if (err < 0)
3216
        goto fail;
3217

    
3218
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3219
    if (err < 0)
3220
        goto fail;
3221

    
3222
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3223
                         (void *)(unsigned long)fds[0]);
3224

    
3225
    io_thread_fd = fds[1];
3226
    return 0;
3227

    
3228
fail:
3229
    close(fds[0]);
3230
    close(fds[1]);
3231
    return err;
3232
}
3233
#else
3234
HANDLE qemu_event_handle;
3235

    
3236
static void dummy_event_handler(void *opaque)
3237
{
3238
}
3239

    
3240
static int qemu_event_init(void)
3241
{
3242
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3243
    if (!qemu_event_handle) {
3244
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3245
        return -1;
3246
    }
3247
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3248
    return 0;
3249
}
3250

    
3251
static void qemu_event_increment(void)
3252
{
3253
    if (!SetEvent(qemu_event_handle)) {
3254
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3255
                GetLastError());
3256
        exit (1);
3257
    }
3258
}
3259
#endif
3260

    
3261
static int cpu_can_run(CPUState *env)
3262
{
3263
    if (env->stop)
3264
        return 0;
3265
    if (env->stopped)
3266
        return 0;
3267
    return 1;
3268
}
3269

    
3270
#ifndef CONFIG_IOTHREAD
3271
static int qemu_init_main_loop(void)
3272
{
3273
    return qemu_event_init();
3274
}
3275

    
3276
void qemu_init_vcpu(void *_env)
3277
{
3278
    CPUState *env = _env;
3279

    
3280
    env->nr_cores = smp_cores;
3281
    env->nr_threads = smp_threads;
3282
    if (kvm_enabled())
3283
        kvm_init_vcpu(env);
3284
    return;
3285
}
3286

    
3287
int qemu_cpu_self(void *env)
3288
{
3289
    return 1;
3290
}
3291

    
3292
static void resume_all_vcpus(void)
3293
{
3294
}
3295

    
3296
static void pause_all_vcpus(void)
3297
{
3298
}
3299

    
3300
void qemu_cpu_kick(void *env)
3301
{
3302
    return;
3303
}
3304

    
3305
void qemu_notify_event(void)
3306
{
3307
    CPUState *env = cpu_single_env;
3308

    
3309
    if (env) {
3310
        cpu_exit(env);
3311
    }
3312
}
3313

    
3314
void qemu_mutex_lock_iothread(void) {}
3315
void qemu_mutex_unlock_iothread(void) {}
3316

    
3317
void vm_stop(int reason)
3318
{
3319
    do_vm_stop(reason);
3320
}
3321

    
3322
#else /* CONFIG_IOTHREAD */
3323

    
3324
#include "qemu-thread.h"
3325

    
3326
QemuMutex qemu_global_mutex;
3327
static QemuMutex qemu_fair_mutex;
3328

    
3329
static QemuThread io_thread;
3330

    
3331
static QemuThread *tcg_cpu_thread;
3332
static QemuCond *tcg_halt_cond;
3333

    
3334
static int qemu_system_ready;
3335
/* cpu creation */
3336
static QemuCond qemu_cpu_cond;
3337
/* system init */
3338
static QemuCond qemu_system_cond;
3339
static QemuCond qemu_pause_cond;
3340

    
3341
static void block_io_signals(void);
3342
static void unblock_io_signals(void);
3343
static int tcg_has_work(void);
3344

    
3345
static int qemu_init_main_loop(void)
3346
{
3347
    int ret;
3348

    
3349
    ret = qemu_event_init();
3350
    if (ret)
3351
        return ret;
3352

    
3353
    qemu_cond_init(&qemu_pause_cond);
3354
    qemu_mutex_init(&qemu_fair_mutex);
3355
    qemu_mutex_init(&qemu_global_mutex);
3356
    qemu_mutex_lock(&qemu_global_mutex);
3357

    
3358
    unblock_io_signals();
3359
    qemu_thread_self(&io_thread);
3360

    
3361
    return 0;
3362
}
3363

    
3364
static void qemu_wait_io_event(CPUState *env)
3365
{
3366
    while (!tcg_has_work())
3367
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3368

    
3369
    qemu_mutex_unlock(&qemu_global_mutex);
3370

    
3371
    /*
3372
     * Users of qemu_global_mutex can be starved, having no chance
3373
     * to acquire it since this path will get to it first.
3374
     * So use another lock to provide fairness.
3375
     */
3376
    qemu_mutex_lock(&qemu_fair_mutex);
3377
    qemu_mutex_unlock(&qemu_fair_mutex);
3378

    
3379
    qemu_mutex_lock(&qemu_global_mutex);
3380
    if (env->stop) {
3381
        env->stop = 0;
3382
        env->stopped = 1;
3383
        qemu_cond_signal(&qemu_pause_cond);
3384
    }
3385
}
3386

    
3387
static int qemu_cpu_exec(CPUState *env);
3388

    
3389
static void *kvm_cpu_thread_fn(void *arg)
3390
{
3391
    CPUState *env = arg;
3392

    
3393
    block_io_signals();
3394
    qemu_thread_self(env->thread);
3395
    if (kvm_enabled())
3396
        kvm_init_vcpu(env);
3397

    
3398
    /* signal CPU creation */
3399
    qemu_mutex_lock(&qemu_global_mutex);
3400
    env->created = 1;
3401
    qemu_cond_signal(&qemu_cpu_cond);
3402

    
3403
    /* and wait for machine initialization */
3404
    while (!qemu_system_ready)
3405
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3406

    
3407
    while (1) {
3408
        if (cpu_can_run(env))
3409
            qemu_cpu_exec(env);
3410
        qemu_wait_io_event(env);
3411
    }
3412

    
3413
    return NULL;
3414
}
3415

    
3416
static void tcg_cpu_exec(void);
3417

    
3418
static void *tcg_cpu_thread_fn(void *arg)
3419
{
3420
    CPUState *env = arg;
3421

    
3422
    block_io_signals();
3423
    qemu_thread_self(env->thread);
3424

    
3425
    /* signal CPU creation */
3426
    qemu_mutex_lock(&qemu_global_mutex);
3427
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3428
        env->created = 1;
3429
    qemu_cond_signal(&qemu_cpu_cond);
3430

    
3431
    /* and wait for machine initialization */
3432
    while (!qemu_system_ready)
3433
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3434

    
3435
    while (1) {
3436
        tcg_cpu_exec();
3437
        qemu_wait_io_event(cur_cpu);
3438
    }
3439

    
3440
    return NULL;
3441
}
3442

    
3443
void qemu_cpu_kick(void *_env)
3444
{
3445
    CPUState *env = _env;
3446
    qemu_cond_broadcast(env->halt_cond);
3447
    if (kvm_enabled())
3448
        qemu_thread_signal(env->thread, SIGUSR1);
3449
}
3450

    
3451
int qemu_cpu_self(void *_env)
3452
{
3453
    CPUState *env = _env;
3454
    QemuThread this;
3455
 
3456
    qemu_thread_self(&this);
3457
 
3458
    return qemu_thread_equal(&this, env->thread);
3459
}
3460

    
3461
static void cpu_signal(int sig)
3462
{
3463
    if (cpu_single_env)
3464
        cpu_exit(cpu_single_env);
3465
}
3466

    
3467
static void block_io_signals(void)
3468
{
3469
    sigset_t set;
3470
    struct sigaction sigact;
3471

    
3472
    sigemptyset(&set);
3473
    sigaddset(&set, SIGUSR2);
3474
    sigaddset(&set, SIGIO);
3475
    sigaddset(&set, SIGALRM);
3476
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3477

    
3478
    sigemptyset(&set);
3479
    sigaddset(&set, SIGUSR1);
3480
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3481

    
3482
    memset(&sigact, 0, sizeof(sigact));
3483
    sigact.sa_handler = cpu_signal;
3484
    sigaction(SIGUSR1, &sigact, NULL);
3485
}
3486

    
3487
static void unblock_io_signals(void)
3488
{
3489
    sigset_t set;
3490

    
3491
    sigemptyset(&set);
3492
    sigaddset(&set, SIGUSR2);
3493
    sigaddset(&set, SIGIO);
3494
    sigaddset(&set, SIGALRM);
3495
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3496

    
3497
    sigemptyset(&set);
3498
    sigaddset(&set, SIGUSR1);
3499
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3500
}
3501

    
3502
static void qemu_signal_lock(unsigned int msecs)
3503
{
3504
    qemu_mutex_lock(&qemu_fair_mutex);
3505

    
3506
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3507
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3508
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3509
            break;
3510
    }
3511
    qemu_mutex_unlock(&qemu_fair_mutex);
3512
}
3513

    
3514
void qemu_mutex_lock_iothread(void)
3515
{
3516
    if (kvm_enabled()) {
3517
        qemu_mutex_lock(&qemu_fair_mutex);
3518
        qemu_mutex_lock(&qemu_global_mutex);
3519
        qemu_mutex_unlock(&qemu_fair_mutex);
3520
    } else
3521
        qemu_signal_lock(100);
3522
}
3523

    
3524
void qemu_mutex_unlock_iothread(void)
3525
{
3526
    qemu_mutex_unlock(&qemu_global_mutex);
3527
}
3528

    
3529
static int all_vcpus_paused(void)
3530
{
3531
    CPUState *penv = first_cpu;
3532

    
3533
    while (penv) {
3534
        if (!penv->stopped)
3535
            return 0;
3536
        penv = (CPUState *)penv->next_cpu;
3537
    }
3538

    
3539
    return 1;
3540
}
3541

    
3542
static void pause_all_vcpus(void)
3543
{
3544
    CPUState *penv = first_cpu;
3545

    
3546
    while (penv) {
3547
        penv->stop = 1;
3548
        qemu_thread_signal(penv->thread, SIGUSR1);
3549
        qemu_cpu_kick(penv);
3550
        penv = (CPUState *)penv->next_cpu;
3551
    }
3552

    
3553
    while (!all_vcpus_paused()) {
3554
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3555
        penv = first_cpu;
3556
        while (penv) {
3557
            qemu_thread_signal(penv->thread, SIGUSR1);
3558
            penv = (CPUState *)penv->next_cpu;
3559
        }
3560
    }
3561
}
3562

    
3563
static void resume_all_vcpus(void)
3564
{
3565
    CPUState *penv = first_cpu;
3566

    
3567
    while (penv) {
3568
        penv->stop = 0;
3569
        penv->stopped = 0;
3570
        qemu_thread_signal(penv->thread, SIGUSR1);
3571
        qemu_cpu_kick(penv);
3572
        penv = (CPUState *)penv->next_cpu;
3573
    }
3574
}
3575

    
3576
static void tcg_init_vcpu(void *_env)
3577
{
3578
    CPUState *env = _env;
3579
    /* share a single thread for all cpus with TCG */
3580
    if (!tcg_cpu_thread) {
3581
        env->thread = qemu_mallocz(sizeof(QemuThread));
3582
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3583
        qemu_cond_init(env->halt_cond);
3584
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3585
        while (env->created == 0)
3586
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3587
        tcg_cpu_thread = env->thread;
3588
        tcg_halt_cond = env->halt_cond;
3589
    } else {
3590
        env->thread = tcg_cpu_thread;
3591
        env->halt_cond = tcg_halt_cond;
3592
    }
3593
}
3594

    
3595
static void kvm_start_vcpu(CPUState *env)
3596
{
3597
    env->thread = qemu_mallocz(sizeof(QemuThread));
3598
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3599
    qemu_cond_init(env->halt_cond);
3600
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3601
    while (env->created == 0)
3602
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3603
}
3604

    
3605
void qemu_init_vcpu(void *_env)
3606
{
3607
    CPUState *env = _env;
3608

    
3609
    env->nr_cores = smp_cores;
3610
    env->nr_threads = smp_threads;
3611
    if (kvm_enabled())
3612
        kvm_start_vcpu(env);
3613
    else
3614
        tcg_init_vcpu(env);
3615
}
3616

    
3617
void qemu_notify_event(void)
3618
{
3619
    qemu_event_increment();
3620
}
3621

    
3622
void vm_stop(int reason)
3623
{
3624
    QemuThread me;
3625
    qemu_thread_self(&me);
3626

    
3627
    if (!qemu_thread_equal(&me, &io_thread)) {
3628
        qemu_system_vmstop_request(reason);
3629
        /*
3630
         * FIXME: should not return to device code in case
3631
         * vm_stop() has been requested.
3632
         */
3633
        if (cpu_single_env) {
3634
            cpu_exit(cpu_single_env);
3635
            cpu_single_env->stop = 1;
3636
        }
3637
        return;
3638
    }
3639
    do_vm_stop(reason);
3640
}
3641

    
3642
#endif
3643

    
3644

    
3645
#ifdef _WIN32
3646
static void host_main_loop_wait(int *timeout)
3647
{
3648
    int ret, ret2, i;
3649
    PollingEntry *pe;
3650

    
3651

    
3652
    /* XXX: need to suppress polling by better using win32 events */
3653
    ret = 0;
3654
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3655
        ret |= pe->func(pe->opaque);
3656
    }
3657
    if (ret == 0) {
3658
        int err;
3659
        WaitObjects *w = &wait_objects;
3660

    
3661
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3662
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3663
            if (w->func[ret - WAIT_OBJECT_0])
3664
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3665

    
3666
            /* Check for additional signaled events */
3667
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3668

    
3669
                /* Check if event is signaled */
3670
                ret2 = WaitForSingleObject(w->events[i], 0);
3671
                if(ret2 == WAIT_OBJECT_0) {
3672
                    if (w->func[i])
3673
                        w->func[i](w->opaque[i]);
3674
                } else if (ret2 == WAIT_TIMEOUT) {
3675
                } else {
3676
                    err = GetLastError();
3677
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3678
                }
3679
            }
3680
        } else if (ret == WAIT_TIMEOUT) {
3681
        } else {
3682
            err = GetLastError();
3683
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3684
        }
3685
    }
3686

    
3687
    *timeout = 0;
3688
}
3689
#else
3690
static void host_main_loop_wait(int *timeout)
3691
{
3692
}
3693
#endif
3694

    
3695
void main_loop_wait(int timeout)
3696
{
3697
    IOHandlerRecord *ioh;
3698
    fd_set rfds, wfds, xfds;
3699
    int ret, nfds;
3700
    struct timeval tv;
3701

    
3702
    qemu_bh_update_timeout(&timeout);
3703

    
3704
    host_main_loop_wait(&timeout);
3705

    
3706
    /* poll any events */
3707
    /* XXX: separate device handlers from system ones */
3708
    nfds = -1;
3709
    FD_ZERO(&rfds);
3710
    FD_ZERO(&wfds);
3711
    FD_ZERO(&xfds);
3712
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3713
        if (ioh->deleted)
3714
            continue;
3715
        if (ioh->fd_read &&
3716
            (!ioh->fd_read_poll ||
3717
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3718
            FD_SET(ioh->fd, &rfds);
3719
            if (ioh->fd > nfds)
3720
                nfds = ioh->fd;
3721
        }
3722
        if (ioh->fd_write) {
3723
            FD_SET(ioh->fd, &wfds);
3724
            if (ioh->fd > nfds)
3725
                nfds = ioh->fd;
3726
        }
3727
    }
3728

    
3729
    tv.tv_sec = timeout / 1000;
3730
    tv.tv_usec = (timeout % 1000) * 1000;
3731

    
3732
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3733

    
3734
    qemu_mutex_unlock_iothread();
3735
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3736
    qemu_mutex_lock_iothread();
3737
    if (ret > 0) {
3738
        IOHandlerRecord **pioh;
3739

    
3740
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3741
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3742
                ioh->fd_read(ioh->opaque);
3743
            }
3744
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3745
                ioh->fd_write(ioh->opaque);
3746
            }
3747
        }
3748

    
3749
        /* remove deleted IO handlers */
3750
        pioh = &first_io_handler;
3751
        while (*pioh) {
3752
            ioh = *pioh;
3753
            if (ioh->deleted) {
3754
                *pioh = ioh->next;
3755
                qemu_free(ioh);
3756
            } else
3757
                pioh = &ioh->next;
3758
        }
3759
    }
3760

    
3761
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3762

    
3763
    /* rearm timer, if not periodic */
3764
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3765
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3766
        qemu_rearm_alarm_timer(alarm_timer);
3767
    }
3768

    
3769
    /* vm time timers */
3770
    if (vm_running) {
3771
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3772
            qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3773
                            qemu_get_clock(vm_clock));
3774
    }
3775

    
3776
    /* real time timers */
3777
    qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3778
                    qemu_get_clock(rt_clock));
3779

    
3780
    qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3781
                    qemu_get_clock(host_clock));
3782

    
3783
    /* Check bottom-halves last in case any of the earlier events triggered
3784
       them.  */
3785
    qemu_bh_poll();
3786

    
3787
}
3788

    
3789
static int qemu_cpu_exec(CPUState *env)
3790
{
3791
    int ret;
3792
#ifdef CONFIG_PROFILER
3793
    int64_t ti;
3794
#endif
3795

    
3796
#ifdef CONFIG_PROFILER
3797
    ti = profile_getclock();
3798
#endif
3799
    if (use_icount) {
3800
        int64_t count;
3801
        int decr;
3802
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3803
        env->icount_decr.u16.low = 0;
3804
        env->icount_extra = 0;
3805
        count = qemu_next_deadline();
3806
        count = (count + (1 << icount_time_shift) - 1)
3807
                >> icount_time_shift;
3808
        qemu_icount += count;
3809
        decr = (count > 0xffff) ? 0xffff : count;
3810
        count -= decr;
3811
        env->icount_decr.u16.low = decr;
3812
        env->icount_extra = count;
3813
    }
3814
    ret = cpu_exec(env);
3815
#ifdef CONFIG_PROFILER
3816
    qemu_time += profile_getclock() - ti;
3817
#endif
3818
    if (use_icount) {
3819
        /* Fold pending instructions back into the
3820
           instruction counter, and clear the interrupt flag.  */
3821
        qemu_icount -= (env->icount_decr.u16.low
3822
                        + env->icount_extra);
3823
        env->icount_decr.u32 = 0;
3824
        env->icount_extra = 0;
3825
    }
3826
    return ret;
3827
}
3828

    
3829
static void tcg_cpu_exec(void)
3830
{
3831
    int ret = 0;
3832

    
3833
    if (next_cpu == NULL)
3834
        next_cpu = first_cpu;
3835
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3836
        CPUState *env = cur_cpu = next_cpu;
3837

    
3838
        if (!vm_running)
3839
            break;
3840
        if (timer_alarm_pending) {
3841
            timer_alarm_pending = 0;
3842
            break;
3843
        }
3844
        if (cpu_can_run(env))
3845
            ret = qemu_cpu_exec(env);
3846
        if (ret == EXCP_DEBUG) {
3847
            gdb_set_stop_cpu(env);
3848
            debug_requested = 1;
3849
            break;
3850
        }
3851
    }
3852
}
3853

    
3854
static int cpu_has_work(CPUState *env)
3855
{
3856
    if (env->stop)
3857
        return 1;
3858
    if (env->stopped)
3859
        return 0;
3860
    if (!env->halted)
3861
        return 1;
3862
    if (qemu_cpu_has_work(env))
3863
        return 1;
3864
    return 0;
3865
}
3866

    
3867
static int tcg_has_work(void)
3868
{
3869
    CPUState *env;
3870

    
3871
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3872
        if (cpu_has_work(env))
3873
            return 1;
3874
    return 0;
3875
}
3876

    
3877
static int qemu_calculate_timeout(void)
3878
{
3879
#ifndef CONFIG_IOTHREAD
3880
    int timeout;
3881

    
3882
    if (!vm_running)
3883
        timeout = 5000;
3884
    else if (tcg_has_work())
3885
        timeout = 0;
3886
    else if (!use_icount)
3887
        timeout = 5000;
3888
    else {
3889
     /* XXX: use timeout computed from timers */
3890
        int64_t add;
3891
        int64_t delta;
3892
        /* Advance virtual time to the next event.  */
3893
        if (use_icount == 1) {
3894
            /* When not using an adaptive execution frequency
3895
               we tend to get badly out of sync with real time,
3896
               so just delay for a reasonable amount of time.  */
3897
            delta = 0;
3898
        } else {
3899
            delta = cpu_get_icount() - cpu_get_clock();
3900
        }
3901
        if (delta > 0) {
3902
            /* If virtual time is ahead of real time then just
3903
               wait for IO.  */
3904
            timeout = (delta / 1000000) + 1;
3905
        } else {
3906
            /* Wait for either IO to occur or the next
3907
               timer event.  */
3908
            add = qemu_next_deadline();
3909
            /* We advance the timer before checking for IO.
3910
               Limit the amount we advance so that early IO
3911
               activity won't get the guest too far ahead.  */
3912
            if (add > 10000000)
3913
                add = 10000000;
3914
            delta += add;
3915
            add = (add + (1 << icount_time_shift) - 1)
3916
                  >> icount_time_shift;
3917
            qemu_icount += add;
3918
            timeout = delta / 1000000;
3919
            if (timeout < 0)
3920
                timeout = 0;
3921
        }
3922
    }
3923

    
3924
    return timeout;
3925
#else /* CONFIG_IOTHREAD */
3926
    return 1000;
3927
#endif
3928
}
3929

    
3930
static int vm_can_run(void)
3931
{
3932
    if (powerdown_requested)
3933
        return 0;
3934
    if (reset_requested)
3935
        return 0;
3936
    if (shutdown_requested)
3937
        return 0;
3938
    if (debug_requested)
3939
        return 0;
3940
    return 1;
3941
}
3942

    
3943
qemu_irq qemu_system_powerdown;
3944

    
3945
static void main_loop(void)
3946
{
3947
    int r;
3948

    
3949
#ifdef CONFIG_IOTHREAD
3950
    qemu_system_ready = 1;
3951
    qemu_cond_broadcast(&qemu_system_cond);
3952
#endif
3953

    
3954
    for (;;) {
3955
        do {
3956
#ifdef CONFIG_PROFILER
3957
            int64_t ti;
3958
#endif
3959
#ifndef CONFIG_IOTHREAD
3960
            tcg_cpu_exec();
3961
#endif
3962
#ifdef CONFIG_PROFILER
3963
            ti = profile_getclock();
3964
#endif
3965
            main_loop_wait(qemu_calculate_timeout());
3966
#ifdef CONFIG_PROFILER
3967
            dev_time += profile_getclock() - ti;
3968
#endif
3969
        } while (vm_can_run());
3970

    
3971
        if (qemu_debug_requested()) {
3972
            monitor_protocol_event(QEVENT_DEBUG, NULL);
3973
            vm_stop(EXCP_DEBUG);
3974
        }
3975
        if (qemu_shutdown_requested()) {
3976
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
3977
            if (no_shutdown) {
3978
                vm_stop(0);
3979
                no_shutdown = 0;
3980
            } else
3981
                break;
3982
        }
3983
        if (qemu_reset_requested()) {
3984
            monitor_protocol_event(QEVENT_RESET, NULL);
3985
            pause_all_vcpus();
3986
            qemu_system_reset();
3987
            resume_all_vcpus();
3988
        }
3989
        if (qemu_powerdown_requested()) {
3990
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
3991
            qemu_irq_raise(qemu_system_powerdown);
3992
        }
3993
        if ((r = qemu_vmstop_requested())) {
3994
            monitor_protocol_event(QEVENT_STOP, NULL);
3995
            vm_stop(r);
3996
        }
3997
    }
3998
    pause_all_vcpus();
3999
}
4000

    
4001
static void version(void)
4002
{
4003
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4004
}
4005

    
4006
static void help(int exitcode)
4007
{
4008
    version();
4009
    printf("usage: %s [options] [disk_image]\n"
4010
           "\n"
4011
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4012
           "\n"
4013
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4014
           opt_help
4015
#define DEFHEADING(text) stringify(text) "\n"
4016
#include "qemu-options.h"
4017
#undef DEF
4018
#undef DEFHEADING
4019
#undef GEN_DOCS
4020
           "\n"
4021
           "During emulation, the following keys are useful:\n"
4022
           "ctrl-alt-f      toggle full screen\n"
4023
           "ctrl-alt-n      switch to virtual console 'n'\n"
4024
           "ctrl-alt        toggle mouse and keyboard grab\n"
4025
           "\n"
4026
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4027
           ,
4028
           "qemu",
4029
           DEFAULT_RAM_SIZE,
4030
#ifndef _WIN32
4031
           DEFAULT_NETWORK_SCRIPT,
4032
           DEFAULT_NETWORK_DOWN_SCRIPT,
4033
#endif
4034
           DEFAULT_GDBSTUB_PORT,
4035
           "/tmp/qemu.log");
4036
    exit(exitcode);
4037
}
4038

    
4039
#define HAS_ARG 0x0001
4040

    
4041
enum {
4042
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4043
    opt_enum,
4044
#define DEFHEADING(text)
4045
#include "qemu-options.h"
4046
#undef DEF
4047
#undef DEFHEADING
4048
#undef GEN_DOCS
4049
};
4050

    
4051
typedef struct QEMUOption {
4052
    const char *name;
4053
    int flags;
4054
    int index;
4055
} QEMUOption;
4056

    
4057
static const QEMUOption qemu_options[] = {
4058
    { "h", 0, QEMU_OPTION_h },
4059
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4060
    { option, opt_arg, opt_enum },
4061
#define DEFHEADING(text)
4062
#include "qemu-options.h"
4063
#undef DEF
4064
#undef DEFHEADING
4065
#undef GEN_DOCS
4066
    { NULL },
4067
};
4068

    
4069
#ifdef HAS_AUDIO
4070
struct soundhw soundhw[] = {
4071
#ifdef HAS_AUDIO_CHOICE
4072
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4073
    {
4074
        "pcspk",
4075
        "PC speaker",
4076
        0,
4077
        1,
4078
        { .init_isa = pcspk_audio_init }
4079
    },
4080
#endif
4081

    
4082
#ifdef CONFIG_SB16
4083
    {
4084
        "sb16",
4085
        "Creative Sound Blaster 16",
4086
        0,
4087
        1,
4088
        { .init_isa = SB16_init }
4089
    },
4090
#endif
4091

    
4092
#ifdef CONFIG_CS4231A
4093
    {
4094
        "cs4231a",
4095
        "CS4231A",
4096
        0,
4097
        1,
4098
        { .init_isa = cs4231a_init }
4099
    },
4100
#endif
4101

    
4102
#ifdef CONFIG_ADLIB
4103
    {
4104
        "adlib",
4105
#ifdef HAS_YMF262
4106
        "Yamaha YMF262 (OPL3)",
4107
#else
4108
        "Yamaha YM3812 (OPL2)",
4109
#endif
4110
        0,
4111
        1,
4112
        { .init_isa = Adlib_init }
4113
    },
4114
#endif
4115

    
4116
#ifdef CONFIG_GUS
4117
    {
4118
        "gus",
4119
        "Gravis Ultrasound GF1",
4120
        0,
4121
        1,
4122
        { .init_isa = GUS_init }
4123
    },
4124
#endif
4125

    
4126
#ifdef CONFIG_AC97
4127
    {
4128
        "ac97",
4129
        "Intel 82801AA AC97 Audio",
4130
        0,
4131
        0,
4132
        { .init_pci = ac97_init }
4133
    },
4134
#endif
4135

    
4136
#ifdef CONFIG_ES1370
4137
    {
4138
        "es1370",
4139
        "ENSONIQ AudioPCI ES1370",
4140
        0,
4141
        0,
4142
        { .init_pci = es1370_init }
4143
    },
4144
#endif
4145

    
4146
#endif /* HAS_AUDIO_CHOICE */
4147

    
4148
    { NULL, NULL, 0, 0, { NULL } }
4149
};
4150

    
4151
static void select_soundhw (const char *optarg)
4152
{
4153
    struct soundhw *c;
4154

    
4155
    if (*optarg == '?') {
4156
    show_valid_cards:
4157

    
4158
        printf ("Valid sound card names (comma separated):\n");
4159
        for (c = soundhw; c->name; ++c) {
4160
            printf ("%-11s %s\n", c->name, c->descr);
4161
        }
4162
        printf ("\n-soundhw all will enable all of the above\n");
4163
        exit (*optarg != '?');
4164
    }
4165
    else {
4166
        size_t l;
4167
        const char *p;
4168
        char *e;
4169
        int bad_card = 0;
4170

    
4171
        if (!strcmp (optarg, "all")) {
4172
            for (c = soundhw; c->name; ++c) {
4173
                c->enabled = 1;
4174
            }
4175
            return;
4176
        }
4177

    
4178
        p = optarg;
4179
        while (*p) {
4180
            e = strchr (p, ',');
4181
            l = !e ? strlen (p) : (size_t) (e - p);
4182

    
4183
            for (c = soundhw; c->name; ++c) {
4184
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4185
                    c->enabled = 1;
4186
                    break;
4187
                }
4188
            }
4189

    
4190
            if (!c->name) {
4191
                if (l > 80) {
4192
                    fprintf (stderr,
4193
                             "Unknown sound card name (too big to show)\n");
4194
                }
4195
                else {
4196
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4197
                             (int) l, p);
4198
                }
4199
                bad_card = 1;
4200
            }
4201
            p += l + (e != NULL);
4202
        }
4203

    
4204
        if (bad_card)
4205
            goto show_valid_cards;
4206
    }
4207
}
4208
#endif
4209

    
4210
static void select_vgahw (const char *p)
4211
{
4212
    const char *opts;
4213

    
4214
    default_vga = 0;
4215
    vga_interface_type = VGA_NONE;
4216
    if (strstart(p, "std", &opts)) {
4217
        vga_interface_type = VGA_STD;
4218
    } else if (strstart(p, "cirrus", &opts)) {
4219
        vga_interface_type = VGA_CIRRUS;
4220
    } else if (strstart(p, "vmware", &opts)) {
4221
        vga_interface_type = VGA_VMWARE;
4222
    } else if (strstart(p, "xenfb", &opts)) {
4223
        vga_interface_type = VGA_XENFB;
4224
    } else if (!strstart(p, "none", &opts)) {
4225
    invalid_vga:
4226
        fprintf(stderr, "Unknown vga type: %s\n", p);
4227
        exit(1);
4228
    }
4229
    while (*opts) {
4230
        const char *nextopt;
4231

    
4232
        if (strstart(opts, ",retrace=", &nextopt)) {
4233
            opts = nextopt;
4234
            if (strstart(opts, "dumb", &nextopt))
4235
                vga_retrace_method = VGA_RETRACE_DUMB;
4236
            else if (strstart(opts, "precise", &nextopt))
4237
                vga_retrace_method = VGA_RETRACE_PRECISE;
4238
            else goto invalid_vga;
4239
        } else goto invalid_vga;
4240
        opts = nextopt;
4241
    }
4242
}
4243

    
4244
#ifdef TARGET_I386
4245
static int balloon_parse(const char *arg)
4246
{
4247
    QemuOpts *opts;
4248

    
4249
    if (strcmp(arg, "none") == 0) {
4250
        return 0;
4251
    }
4252

    
4253
    if (!strncmp(arg, "virtio", 6)) {
4254
        if (arg[6] == ',') {
4255
            /* have params -> parse them */
4256
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4257
            if (!opts)
4258
                return  -1;
4259
        } else {
4260
            /* create empty opts */
4261
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4262
        }
4263
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4264
        return 0;
4265
    }
4266

    
4267
    return -1;
4268
}
4269
#endif
4270

    
4271
#ifdef _WIN32
4272
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4273
{
4274
    exit(STATUS_CONTROL_C_EXIT);
4275
    return TRUE;
4276
}
4277
#endif
4278

    
4279
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4280
{
4281
    int ret;
4282

    
4283
    if(strlen(str) != 36)
4284
        return -1;
4285

    
4286
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4287
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4288
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4289

    
4290
    if(ret != 16)
4291
        return -1;
4292

    
4293
#ifdef TARGET_I386
4294
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4295
#endif
4296

    
4297
    return 0;
4298
}
4299

    
4300
#ifndef _WIN32
4301

    
4302
static void termsig_handler(int signal)
4303
{
4304
    qemu_system_shutdown_request();
4305
}
4306

    
4307
static void sigchld_handler(int signal)
4308
{
4309
    waitpid(-1, NULL, WNOHANG);
4310
}
4311

    
4312
static void sighandler_setup(void)
4313
{
4314
    struct sigaction act;
4315

    
4316
    memset(&act, 0, sizeof(act));
4317
    act.sa_handler = termsig_handler;
4318
    sigaction(SIGINT,  &act, NULL);
4319
    sigaction(SIGHUP,  &act, NULL);
4320
    sigaction(SIGTERM, &act, NULL);
4321

    
4322
    act.sa_handler = sigchld_handler;
4323
    act.sa_flags = SA_NOCLDSTOP;
4324
    sigaction(SIGCHLD, &act, NULL);
4325
}
4326

    
4327
#endif
4328

    
4329
#ifdef _WIN32
4330
/* Look for support files in the same directory as the executable.  */
4331
static char *find_datadir(const char *argv0)
4332
{
4333
    char *p;
4334
    char buf[MAX_PATH];
4335
    DWORD len;
4336

    
4337
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4338
    if (len == 0) {
4339
        return NULL;
4340
    }
4341

    
4342
    buf[len] = 0;
4343
    p = buf + len - 1;
4344
    while (p != buf && *p != '\\')
4345
        p--;
4346
    *p = 0;
4347
    if (access(buf, R_OK) == 0) {
4348
        return qemu_strdup(buf);
4349
    }
4350
    return NULL;
4351
}
4352
#else /* !_WIN32 */
4353

    
4354
/* Find a likely location for support files using the location of the binary.
4355
   For installed binaries this will be "$bindir/../share/qemu".  When
4356
   running from the build tree this will be "$bindir/../pc-bios".  */
4357
#define SHARE_SUFFIX "/share/qemu"
4358
#define BUILD_SUFFIX "/pc-bios"
4359
static char *find_datadir(const char *argv0)
4360
{
4361
    char *dir;
4362
    char *p = NULL;
4363
    char *res;
4364
    char buf[PATH_MAX];
4365
    size_t max_len;
4366

    
4367
#if defined(__linux__)
4368
    {
4369
        int len;
4370
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4371
        if (len > 0) {
4372
            buf[len] = 0;
4373
            p = buf;
4374
        }
4375
    }
4376
#elif defined(__FreeBSD__)
4377
    {
4378
        int len;
4379
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4380
        if (len > 0) {
4381
            buf[len] = 0;
4382
            p = buf;
4383
        }
4384
    }
4385
#endif
4386
    /* If we don't have any way of figuring out the actual executable
4387
       location then try argv[0].  */
4388
    if (!p) {
4389
        p = realpath(argv0, buf);
4390
        if (!p) {
4391
            return NULL;
4392
        }
4393
    }
4394
    dir = dirname(p);
4395
    dir = dirname(dir);
4396

    
4397
    max_len = strlen(dir) +
4398
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4399
    res = qemu_mallocz(max_len);
4400
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4401
    if (access(res, R_OK)) {
4402
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4403
        if (access(res, R_OK)) {
4404
            qemu_free(res);
4405
            res = NULL;
4406
        }
4407
    }
4408

    
4409
    return res;
4410
}
4411
#undef SHARE_SUFFIX
4412
#undef BUILD_SUFFIX
4413
#endif
4414

    
4415
char *qemu_find_file(int type, const char *name)
4416
{
4417
    int len;
4418
    const char *subdir;
4419
    char *buf;
4420

    
4421
    /* If name contains path separators then try it as a straight path.  */
4422
    if ((strchr(name, '/') || strchr(name, '\\'))
4423
        && access(name, R_OK) == 0) {
4424
        return qemu_strdup(name);
4425
    }
4426
    switch (type) {
4427
    case QEMU_FILE_TYPE_BIOS:
4428
        subdir = "";
4429
        break;
4430
    case QEMU_FILE_TYPE_KEYMAP:
4431
        subdir = "keymaps/";
4432
        break;
4433
    default:
4434
        abort();
4435
    }
4436
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4437
    buf = qemu_mallocz(len);
4438
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4439
    if (access(buf, R_OK)) {
4440
        qemu_free(buf);
4441
        return NULL;
4442
    }
4443
    return buf;
4444
}
4445

    
4446
static int device_init_func(QemuOpts *opts, void *opaque)
4447
{
4448
    DeviceState *dev;
4449

    
4450
    dev = qdev_device_add(opts);
4451
    if (!dev)
4452
        return -1;
4453
    return 0;
4454
}
4455

    
4456
static int chardev_init_func(QemuOpts *opts, void *opaque)
4457
{
4458
    CharDriverState *chr;
4459

    
4460
    chr = qemu_chr_open_opts(opts, NULL);
4461
    if (!chr)
4462
        return -1;
4463
    return 0;
4464
}
4465

    
4466
static int mon_init_func(QemuOpts *opts, void *opaque)
4467
{
4468
    CharDriverState *chr;
4469
    const char *chardev;
4470
    const char *mode;
4471
    int flags;
4472

    
4473
    mode = qemu_opt_get(opts, "mode");
4474
    if (mode == NULL) {
4475
        mode = "readline";
4476
    }
4477
    if (strcmp(mode, "readline") == 0) {
4478
        flags = MONITOR_USE_READLINE;
4479
    } else if (strcmp(mode, "control") == 0) {
4480
        flags = MONITOR_USE_CONTROL;
4481
    } else {
4482
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4483
        exit(1);
4484
    }
4485

    
4486
    if (qemu_opt_get_bool(opts, "default", 0))
4487
        flags |= MONITOR_IS_DEFAULT;
4488

    
4489
    chardev = qemu_opt_get(opts, "chardev");
4490
    chr = qemu_chr_find(chardev);
4491
    if (chr == NULL) {
4492
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4493
        exit(1);
4494
    }
4495

    
4496
    monitor_init(chr, flags);
4497
    return 0;
4498
}
4499

    
4500
static void monitor_parse(const char *optarg, const char *mode)
4501
{
4502
    static int monitor_device_index = 0;
4503
    QemuOpts *opts;
4504
    const char *p;
4505
    char label[32];
4506
    int def = 0;
4507

    
4508
    if (strstart(optarg, "chardev:", &p)) {
4509
        snprintf(label, sizeof(label), "%s", p);
4510
    } else {
4511
        if (monitor_device_index) {
4512
            snprintf(label, sizeof(label), "monitor%d",
4513
                     monitor_device_index);
4514
        } else {
4515
            snprintf(label, sizeof(label), "monitor");
4516
            def = 1;
4517
        }
4518
        opts = qemu_chr_parse_compat(label, optarg);
4519
        if (!opts) {
4520
            fprintf(stderr, "parse error: %s\n", optarg);
4521
            exit(1);
4522
        }
4523
    }
4524

    
4525
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4526
    if (!opts) {
4527
        fprintf(stderr, "duplicate chardev: %s\n", label);
4528
        exit(1);
4529
    }
4530
    qemu_opt_set(opts, "mode", mode);
4531
    qemu_opt_set(opts, "chardev", label);
4532
    if (def)
4533
        qemu_opt_set(opts, "default", "on");
4534
    monitor_device_index++;
4535
}
4536

    
4537
struct device_config {
4538
    enum {
4539
        DEV_USB,       /* -usbdevice     */
4540
        DEV_BT,        /* -bt            */
4541
        DEV_SERIAL,    /* -serial        */
4542
        DEV_PARALLEL,  /* -parallel      */
4543
        DEV_VIRTCON,   /* -virtioconsole */
4544
        DEV_DEBUGCON,  /* -debugcon */
4545
    } type;
4546
    const char *cmdline;
4547
    QTAILQ_ENTRY(device_config) next;
4548
};
4549
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4550

    
4551
static void add_device_config(int type, const char *cmdline)
4552
{
4553
    struct device_config *conf;
4554

    
4555
    conf = qemu_mallocz(sizeof(*conf));
4556
    conf->type = type;
4557
    conf->cmdline = cmdline;
4558
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4559
}
4560

    
4561
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4562
{
4563
    struct device_config *conf;
4564
    int rc;
4565

    
4566
    QTAILQ_FOREACH(conf, &device_configs, next) {
4567
        if (conf->type != type)
4568
            continue;
4569
        rc = func(conf->cmdline);
4570
        if (0 != rc)
4571
            return rc;
4572
    }
4573
    return 0;
4574
}
4575

    
4576
static int serial_parse(const char *devname)
4577
{
4578
    static int index = 0;
4579
    char label[32];
4580

    
4581
    if (strcmp(devname, "none") == 0)
4582
        return 0;
4583
    if (index == MAX_SERIAL_PORTS) {
4584
        fprintf(stderr, "qemu: too many serial ports\n");
4585
        exit(1);
4586
    }
4587
    snprintf(label, sizeof(label), "serial%d", index);
4588
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
4589
    if (!serial_hds[index]) {
4590
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4591
                devname, strerror(errno));
4592
        return -1;
4593
    }
4594
    index++;
4595
    return 0;
4596
}
4597

    
4598
static int parallel_parse(const char *devname)
4599
{
4600
    static int index = 0;
4601
    char label[32];
4602

    
4603
    if (strcmp(devname, "none") == 0)
4604
        return 0;
4605
    if (index == MAX_PARALLEL_PORTS) {
4606
        fprintf(stderr, "qemu: too many parallel ports\n");
4607
        exit(1);
4608
    }
4609
    snprintf(label, sizeof(label), "parallel%d", index);
4610
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4611
    if (!parallel_hds[index]) {
4612
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4613
                devname, strerror(errno));
4614
        return -1;
4615
    }
4616
    index++;
4617
    return 0;
4618
}
4619

    
4620
static int virtcon_parse(const char *devname)
4621
{
4622
    static int index = 0;
4623
    char label[32];
4624

    
4625
    if (strcmp(devname, "none") == 0)
4626
        return 0;
4627
    if (index == MAX_VIRTIO_CONSOLES) {
4628
        fprintf(stderr, "qemu: too many virtio consoles\n");
4629
        exit(1);
4630
    }
4631
    snprintf(label, sizeof(label), "virtcon%d", index);
4632
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4633
    if (!virtcon_hds[index]) {
4634
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4635
                devname, strerror(errno));
4636
        return -1;
4637
    }
4638
    index++;
4639
    return 0;
4640
}
4641

    
4642
static int debugcon_parse(const char *devname)
4643
{   
4644
    QemuOpts *opts;
4645

    
4646
    if (!qemu_chr_open("debugcon", devname, NULL)) {
4647
        exit(1);
4648
    }
4649
    opts = qemu_opts_create(&qemu_device_opts, "debugcon", 1);
4650
    if (!opts) {
4651
        fprintf(stderr, "qemu: already have a debugcon device\n");
4652
        exit(1);
4653
    }
4654
    qemu_opt_set(opts, "driver", "isa-debugcon");
4655
    qemu_opt_set(opts, "chardev", "debugcon");
4656
    return 0;
4657
}
4658

    
4659
int main(int argc, char **argv, char **envp)
4660
{
4661
    const char *gdbstub_dev = NULL;
4662
    uint32_t boot_devices_bitmap = 0;
4663
    int i;
4664
    int snapshot, linux_boot, net_boot;
4665
    const char *initrd_filename;
4666
    const char *kernel_filename, *kernel_cmdline;
4667
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4668
    DisplayState *ds;
4669
    DisplayChangeListener *dcl;
4670
    int cyls, heads, secs, translation;
4671
    QemuOpts *hda_opts = NULL, *opts;
4672
    int optind;
4673
    const char *r, *optarg;
4674
    const char *loadvm = NULL;
4675
    QEMUMachine *machine;
4676
    const char *cpu_model;
4677
#ifndef _WIN32
4678
    int fds[2];
4679
#endif
4680
    int tb_size;
4681
    const char *pid_file = NULL;
4682
    const char *incoming = NULL;
4683
#ifndef _WIN32
4684
    int fd = 0;
4685
    struct passwd *pwd = NULL;
4686
    const char *chroot_dir = NULL;
4687
    const char *run_as = NULL;
4688
#endif
4689
    CPUState *env;
4690
    int show_vnc_port = 0;
4691

    
4692
    init_clocks();
4693

    
4694
    qemu_errors_to_file(stderr);
4695
    qemu_cache_utils_init(envp);
4696

    
4697
    QLIST_INIT (&vm_change_state_head);
4698
#ifndef _WIN32
4699
    {
4700
        struct sigaction act;
4701
        sigfillset(&act.sa_mask);
4702
        act.sa_flags = 0;
4703
        act.sa_handler = SIG_IGN;
4704
        sigaction(SIGPIPE, &act, NULL);
4705
    }
4706
#else
4707
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4708
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4709
       QEMU to run on a single CPU */
4710
    {
4711
        HANDLE h;
4712
        DWORD mask, smask;
4713
        int i;
4714
        h = GetCurrentProcess();
4715
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4716
            for(i = 0; i < 32; i++) {
4717
                if (mask & (1 << i))
4718
                    break;
4719
            }
4720
            if (i != 32) {
4721
                mask = 1 << i;
4722
                SetProcessAffinityMask(h, mask);
4723
            }
4724
        }
4725
    }
4726
#endif
4727

    
4728
    module_call_init(MODULE_INIT_MACHINE);
4729
    machine = find_default_machine();
4730
    cpu_model = NULL;
4731
    initrd_filename = NULL;
4732
    ram_size = 0;
4733
    snapshot = 0;
4734
    kernel_filename = NULL;
4735
    kernel_cmdline = "";
4736
    cyls = heads = secs = 0;
4737
    translation = BIOS_ATA_TRANSLATION_AUTO;
4738

    
4739
    for (i = 0; i < MAX_NODES; i++) {
4740
        node_mem[i] = 0;
4741
        node_cpumask[i] = 0;
4742
    }
4743

    
4744
    nb_numa_nodes = 0;
4745
    nb_nics = 0;
4746

    
4747
    tb_size = 0;
4748
    autostart= 1;
4749

    
4750
    optind = 1;
4751
    for(;;) {
4752
        if (optind >= argc)
4753
            break;
4754
        r = argv[optind];
4755
        if (r[0] != '-') {
4756
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4757
        } else {
4758
            const QEMUOption *popt;
4759

    
4760
            optind++;
4761
            /* Treat --foo the same as -foo.  */
4762
            if (r[1] == '-')
4763
                r++;
4764
            popt = qemu_options;
4765
            for(;;) {
4766
                if (!popt->name) {
4767
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4768
                            argv[0], r);
4769
                    exit(1);
4770
                }
4771
                if (!strcmp(popt->name, r + 1))
4772
                    break;
4773
                popt++;
4774
            }
4775
            if (popt->flags & HAS_ARG) {
4776
                if (optind >= argc) {
4777
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4778
                            argv[0], r);
4779
                    exit(1);
4780
                }
4781
                optarg = argv[optind++];
4782
            } else {
4783
                optarg = NULL;
4784
            }
4785

    
4786
            switch(popt->index) {
4787
            case QEMU_OPTION_M:
4788
                machine = find_machine(optarg);
4789
                if (!machine) {
4790
                    QEMUMachine *m;
4791
                    printf("Supported machines are:\n");
4792
                    for(m = first_machine; m != NULL; m = m->next) {
4793
                        if (m->alias)
4794
                            printf("%-10s %s (alias of %s)\n",
4795
                                   m->alias, m->desc, m->name);
4796
                        printf("%-10s %s%s\n",
4797
                               m->name, m->desc,
4798
                               m->is_default ? " (default)" : "");
4799
                    }
4800
                    exit(*optarg != '?');
4801
                }
4802
                break;
4803
            case QEMU_OPTION_cpu:
4804
                /* hw initialization will check this */
4805
                if (*optarg == '?') {
4806
/* XXX: implement xxx_cpu_list for targets that still miss it */
4807
#if defined(cpu_list)
4808
                    cpu_list(stdout, &fprintf);
4809
#endif
4810
                    exit(0);
4811
                } else {
4812
                    cpu_model = optarg;
4813
                }
4814
                break;
4815
            case QEMU_OPTION_initrd:
4816
                initrd_filename = optarg;
4817
                break;
4818
            case QEMU_OPTION_hda:
4819
                if (cyls == 0)
4820
                    hda_opts = drive_add(optarg, HD_ALIAS, 0);
4821
                else
4822
                    hda_opts = drive_add(optarg, HD_ALIAS
4823
                             ",cyls=%d,heads=%d,secs=%d%s",
4824
                             0, cyls, heads, secs,
4825
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4826
                                 ",trans=lba" :
4827
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4828
                                 ",trans=none" : "");
4829
                 break;
4830
            case QEMU_OPTION_hdb:
4831
            case QEMU_OPTION_hdc:
4832
            case QEMU_OPTION_hdd:
4833
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4834
                break;
4835
            case QEMU_OPTION_drive:
4836
                drive_add(NULL, "%s", optarg);
4837
                break;
4838
            case QEMU_OPTION_set:
4839
                if (qemu_set_option(optarg) != 0)
4840
                    exit(1);
4841
                break;
4842
            case QEMU_OPTION_global:
4843
                if (qemu_global_option(optarg) != 0)
4844
                    exit(1);
4845
                break;
4846
            case QEMU_OPTION_mtdblock:
4847
                drive_add(optarg, MTD_ALIAS);
4848
                break;
4849
            case QEMU_OPTION_sd:
4850
                drive_add(optarg, SD_ALIAS);
4851
                break;
4852
            case QEMU_OPTION_pflash:
4853
                drive_add(optarg, PFLASH_ALIAS);
4854
                break;
4855
            case QEMU_OPTION_snapshot:
4856
                snapshot = 1;
4857
                break;
4858
            case QEMU_OPTION_hdachs:
4859
                {
4860
                    const char *p;
4861
                    p = optarg;
4862
                    cyls = strtol(p, (char **)&p, 0);
4863
                    if (cyls < 1 || cyls > 16383)
4864
                        goto chs_fail;
4865
                    if (*p != ',')
4866
                        goto chs_fail;
4867
                    p++;
4868
                    heads = strtol(p, (char **)&p, 0);
4869
                    if (heads < 1 || heads > 16)
4870
                        goto chs_fail;
4871
                    if (*p != ',')
4872
                        goto chs_fail;
4873
                    p++;
4874
                    secs = strtol(p, (char **)&p, 0);
4875
                    if (secs < 1 || secs > 63)
4876
                        goto chs_fail;
4877
                    if (*p == ',') {
4878
                        p++;
4879
                        if (!strcmp(p, "none"))
4880
                            translation = BIOS_ATA_TRANSLATION_NONE;
4881
                        else if (!strcmp(p, "lba"))
4882
                            translation = BIOS_ATA_TRANSLATION_LBA;
4883
                        else if (!strcmp(p, "auto"))
4884
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4885
                        else
4886
                            goto chs_fail;
4887
                    } else if (*p != '\0') {
4888
                    chs_fail:
4889
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4890
                        exit(1);
4891
                    }
4892
                    if (hda_opts != NULL) {
4893
                        char num[16];
4894
                        snprintf(num, sizeof(num), "%d", cyls);
4895
                        qemu_opt_set(hda_opts, "cyls", num);
4896
                        snprintf(num, sizeof(num), "%d", heads);
4897
                        qemu_opt_set(hda_opts, "heads", num);
4898
                        snprintf(num, sizeof(num), "%d", secs);
4899
                        qemu_opt_set(hda_opts, "secs", num);
4900
                        if (translation == BIOS_ATA_TRANSLATION_LBA)
4901
                            qemu_opt_set(hda_opts, "trans", "lba");
4902
                        if (translation == BIOS_ATA_TRANSLATION_NONE)
4903
                            qemu_opt_set(hda_opts, "trans", "none");
4904
                    }
4905
                }
4906
                break;
4907
            case QEMU_OPTION_numa:
4908
                if (nb_numa_nodes >= MAX_NODES) {
4909
                    fprintf(stderr, "qemu: too many NUMA nodes\n");
4910
                    exit(1);
4911
                }
4912
                numa_add(optarg);
4913
                break;
4914
            case QEMU_OPTION_nographic:
4915
                display_type = DT_NOGRAPHIC;
4916
                break;
4917
#ifdef CONFIG_CURSES
4918
            case QEMU_OPTION_curses:
4919
                display_type = DT_CURSES;
4920
                break;
4921
#endif
4922
            case QEMU_OPTION_portrait:
4923
                graphic_rotate = 1;
4924
                break;
4925
            case QEMU_OPTION_kernel:
4926
                kernel_filename = optarg;
4927
                break;
4928
            case QEMU_OPTION_append:
4929
                kernel_cmdline = optarg;
4930
                break;
4931
            case QEMU_OPTION_cdrom:
4932
                drive_add(optarg, CDROM_ALIAS);
4933
                break;
4934
            case QEMU_OPTION_boot:
4935
                {
4936
                    static const char * const params[] = {
4937
                        "order", "once", "menu", NULL
4938
                    };
4939
                    char buf[sizeof(boot_devices)];
4940
                    char *standard_boot_devices;
4941
                    int legacy = 0;
4942

    
4943
                    if (!strchr(optarg, '=')) {
4944
                        legacy = 1;
4945
                        pstrcpy(buf, sizeof(buf), optarg);
4946
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4947
                        fprintf(stderr,
4948
                                "qemu: unknown boot parameter '%s' in '%s'\n",
4949
                                buf, optarg);
4950
                        exit(1);
4951
                    }
4952

    
4953
                    if (legacy ||
4954
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
4955
                        boot_devices_bitmap = parse_bootdevices(buf);
4956
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
4957
                    }
4958
                    if (!legacy) {
4959
                        if (get_param_value(buf, sizeof(buf),
4960
                                            "once", optarg)) {
4961
                            boot_devices_bitmap |= parse_bootdevices(buf);
4962
                            standard_boot_devices = qemu_strdup(boot_devices);
4963
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
4964
                            qemu_register_reset(restore_boot_devices,
4965
                                                standard_boot_devices);
4966
                        }
4967
                        if (get_param_value(buf, sizeof(buf),
4968
                                            "menu", optarg)) {
4969
                            if (!strcmp(buf, "on")) {
4970
                                boot_menu = 1;
4971
                            } else if (!strcmp(buf, "off")) {
4972
                                boot_menu = 0;
4973
                            } else {
4974
                                fprintf(stderr,
4975
                                        "qemu: invalid option value '%s'\n",
4976
                                        buf);
4977
                                exit(1);
4978
                            }
4979
                        }
4980
                    }
4981
                }
4982
                break;
4983
            case QEMU_OPTION_fda:
4984
            case QEMU_OPTION_fdb:
4985
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4986
                break;
4987
#ifdef TARGET_I386
4988
            case QEMU_OPTION_no_fd_bootchk:
4989
                fd_bootchk = 0;
4990
                break;
4991
#endif
4992
            case QEMU_OPTION_netdev:
4993
                if (net_client_parse(&qemu_netdev_opts, optarg) == -1) {
4994
                    exit(1);
4995
                }
4996
                break;
4997
            case QEMU_OPTION_net:
4998
                if (net_client_parse(&qemu_net_opts, optarg) == -1) {
4999
                    exit(1);
5000
                }
5001
                break;
5002
#ifdef CONFIG_SLIRP
5003
            case QEMU_OPTION_tftp:
5004
                legacy_tftp_prefix = optarg;
5005
                break;
5006
            case QEMU_OPTION_bootp:
5007
                legacy_bootp_filename = optarg;
5008
                break;
5009
#ifndef _WIN32
5010
            case QEMU_OPTION_smb:
5011
                if (net_slirp_smb(optarg) < 0)
5012
                    exit(1);
5013
                break;
5014
#endif
5015
            case QEMU_OPTION_redir:
5016
                if (net_slirp_redir(optarg) < 0)
5017
                    exit(1);
5018
                break;
5019
#endif
5020
            case QEMU_OPTION_bt:
5021
                add_device_config(DEV_BT, optarg);
5022
                break;
5023
#ifdef HAS_AUDIO
5024
            case QEMU_OPTION_audio_help:
5025
                AUD_help ();
5026
                exit (0);
5027
                break;
5028
            case QEMU_OPTION_soundhw:
5029
                select_soundhw (optarg);
5030
                break;
5031
#endif
5032
            case QEMU_OPTION_h:
5033
                help(0);
5034
                break;
5035
            case QEMU_OPTION_version:
5036
                version();
5037
                exit(0);
5038
                break;
5039
            case QEMU_OPTION_m: {
5040
                uint64_t value;
5041
                char *ptr;
5042

    
5043
                value = strtoul(optarg, &ptr, 10);
5044
                switch (*ptr) {
5045
                case 0: case 'M': case 'm':
5046
                    value <<= 20;
5047
                    break;
5048
                case 'G': case 'g':
5049
                    value <<= 30;
5050
                    break;
5051
                default:
5052
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5053
                    exit(1);
5054
                }
5055

    
5056
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5057
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5058
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5059
                    exit(1);
5060
                }
5061
                if (value != (uint64_t)(ram_addr_t)value) {
5062
                    fprintf(stderr, "qemu: ram size too large\n");
5063
                    exit(1);
5064
                }
5065
                ram_size = value;
5066
                break;
5067
            }
5068
            case QEMU_OPTION_d:
5069
                {
5070
                    int mask;
5071
                    const CPULogItem *item;
5072

    
5073
                    mask = cpu_str_to_log_mask(optarg);
5074
                    if (!mask) {
5075
                        printf("Log items (comma separated):\n");
5076
                    for(item = cpu_log_items; item->mask != 0; item++) {
5077
                        printf("%-10s %s\n", item->name, item->help);
5078
                    }
5079
                    exit(1);
5080
                    }
5081
                    cpu_set_log(mask);
5082
                }
5083
                break;
5084
            case QEMU_OPTION_s:
5085
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5086
                break;
5087
            case QEMU_OPTION_gdb:
5088
                gdbstub_dev = optarg;
5089
                break;
5090
            case QEMU_OPTION_L:
5091
                data_dir = optarg;
5092
                break;
5093
            case QEMU_OPTION_bios:
5094
                bios_name = optarg;
5095
                break;
5096
            case QEMU_OPTION_singlestep:
5097
                singlestep = 1;
5098
                break;
5099
            case QEMU_OPTION_S:
5100
                autostart = 0;
5101
                break;
5102
            case QEMU_OPTION_k:
5103
                keyboard_layout = optarg;
5104
                break;
5105
            case QEMU_OPTION_localtime:
5106
                rtc_utc = 0;
5107
                break;
5108
            case QEMU_OPTION_vga:
5109
                select_vgahw (optarg);
5110
                break;
5111
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5112
            case QEMU_OPTION_g:
5113
                {
5114
                    const char *p;
5115
                    int w, h, depth;
5116
                    p = optarg;
5117
                    w = strtol(p, (char **)&p, 10);
5118
                    if (w <= 0) {
5119
                    graphic_error:
5120
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5121
                        exit(1);
5122
                    }
5123
                    if (*p != 'x')
5124
                        goto graphic_error;
5125
                    p++;
5126
                    h = strtol(p, (char **)&p, 10);
5127
                    if (h <= 0)
5128
                        goto graphic_error;
5129
                    if (*p == 'x') {
5130
                        p++;
5131
                        depth = strtol(p, (char **)&p, 10);
5132
                        if (depth != 8 && depth != 15 && depth != 16 &&
5133
                            depth != 24 && depth != 32)
5134
                            goto graphic_error;
5135
                    } else if (*p == '\0') {
5136
                        depth = graphic_depth;
5137
                    } else {
5138
                        goto graphic_error;
5139
                    }
5140

    
5141
                    graphic_width = w;
5142
                    graphic_height = h;
5143
                    graphic_depth = depth;
5144
                }
5145
                break;
5146
#endif
5147
            case QEMU_OPTION_echr:
5148
                {
5149
                    char *r;
5150
                    term_escape_char = strtol(optarg, &r, 0);
5151
                    if (r == optarg)
5152
                        printf("Bad argument to echr\n");
5153
                    break;
5154
                }
5155
            case QEMU_OPTION_monitor:
5156
                monitor_parse(optarg, "readline");
5157
                default_monitor = 0;
5158
                break;
5159
            case QEMU_OPTION_qmp:
5160
                monitor_parse(optarg, "control");
5161
                default_monitor = 0;
5162
                break;
5163
            case QEMU_OPTION_mon:
5164
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5165
                if (!opts) {
5166
                    fprintf(stderr, "parse error: %s\n", optarg);
5167
                    exit(1);
5168
                }
5169
                default_monitor = 0;
5170
                break;
5171
            case QEMU_OPTION_chardev:
5172
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5173
                if (!opts) {
5174
                    fprintf(stderr, "parse error: %s\n", optarg);
5175
                    exit(1);
5176
                }
5177
                break;
5178
            case QEMU_OPTION_serial:
5179
                add_device_config(DEV_SERIAL, optarg);
5180
                default_serial = 0;
5181
                break;
5182
            case QEMU_OPTION_watchdog:
5183
                if (watchdog) {
5184
                    fprintf(stderr,
5185
                            "qemu: only one watchdog option may be given\n");
5186
                    return 1;
5187
                }
5188
                watchdog = optarg;
5189
                break;
5190
            case QEMU_OPTION_watchdog_action:
5191
                if (select_watchdog_action(optarg) == -1) {
5192
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
5193
                    exit(1);
5194
                }
5195
                break;
5196
            case QEMU_OPTION_virtiocon:
5197
                add_device_config(DEV_VIRTCON, optarg);
5198
                default_virtcon = 0;
5199
                break;
5200
            case QEMU_OPTION_parallel:
5201
                add_device_config(DEV_PARALLEL, optarg);
5202
                default_parallel = 0;
5203
                break;
5204
            case QEMU_OPTION_debugcon:
5205
                add_device_config(DEV_DEBUGCON, optarg);
5206
                break;
5207
            case QEMU_OPTION_loadvm:
5208
                loadvm = optarg;
5209
                break;
5210
            case QEMU_OPTION_full_screen:
5211
                full_screen = 1;
5212
                break;
5213
#ifdef CONFIG_SDL
5214
            case QEMU_OPTION_no_frame:
5215
                no_frame = 1;
5216
                break;
5217
            case QEMU_OPTION_alt_grab:
5218
                alt_grab = 1;
5219
                break;
5220
            case QEMU_OPTION_ctrl_grab:
5221
                ctrl_grab = 1;
5222
                break;
5223
            case QEMU_OPTION_no_quit:
5224
                no_quit = 1;
5225
                break;
5226
            case QEMU_OPTION_sdl:
5227
                display_type = DT_SDL;
5228
                break;
5229
#endif
5230
            case QEMU_OPTION_pidfile:
5231
                pid_file = optarg;
5232
                break;
5233
#ifdef TARGET_I386
5234
            case QEMU_OPTION_win2k_hack:
5235
                win2k_install_hack = 1;
5236
                break;
5237
            case QEMU_OPTION_rtc_td_hack:
5238
                rtc_td_hack = 1;
5239
                break;
5240
            case QEMU_OPTION_acpitable:
5241
                if(acpi_table_add(optarg) < 0) {
5242
                    fprintf(stderr, "Wrong acpi table provided\n");
5243
                    exit(1);
5244
                }
5245
                break;
5246
            case QEMU_OPTION_smbios:
5247
                if(smbios_entry_add(optarg) < 0) {
5248
                    fprintf(stderr, "Wrong smbios provided\n");
5249
                    exit(1);
5250
                }
5251
                break;
5252
#endif
5253
#ifdef CONFIG_KVM
5254
            case QEMU_OPTION_enable_kvm:
5255
                kvm_allowed = 1;
5256
                break;
5257
#endif
5258
            case QEMU_OPTION_usb:
5259
                usb_enabled = 1;
5260
                break;
5261
            case QEMU_OPTION_usbdevice:
5262
                usb_enabled = 1;
5263
                add_device_config(DEV_USB, optarg);
5264
                break;
5265
            case QEMU_OPTION_device:
5266
                if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5267
                    exit(1);
5268
                }
5269
                break;
5270
            case QEMU_OPTION_smp:
5271
                smp_parse(optarg);
5272
                if (smp_cpus < 1) {
5273
                    fprintf(stderr, "Invalid number of CPUs\n");
5274
                    exit(1);
5275
                }
5276
                if (max_cpus < smp_cpus) {
5277
                    fprintf(stderr, "maxcpus must be equal to or greater than "
5278
                            "smp\n");
5279
                    exit(1);
5280
                }
5281
                if (max_cpus > 255) {
5282
                    fprintf(stderr, "Unsupported number of maxcpus\n");
5283
                    exit(1);
5284
                }
5285
                break;
5286
            case QEMU_OPTION_vnc:
5287
                display_type = DT_VNC;
5288
                vnc_display = optarg;
5289
                break;
5290
#ifdef TARGET_I386
5291
            case QEMU_OPTION_no_acpi:
5292
                acpi_enabled = 0;
5293
                break;
5294
            case QEMU_OPTION_no_hpet:
5295
                no_hpet = 1;
5296
                break;
5297
            case QEMU_OPTION_balloon:
5298
                if (balloon_parse(optarg) < 0) {
5299
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5300
                    exit(1);
5301
                }
5302
                break;
5303
#endif
5304
            case QEMU_OPTION_no_reboot:
5305
                no_reboot = 1;
5306
                break;
5307
            case QEMU_OPTION_no_shutdown:
5308
                no_shutdown = 1;
5309
                break;
5310
            case QEMU_OPTION_show_cursor:
5311
                cursor_hide = 0;
5312
                break;
5313
            case QEMU_OPTION_uuid:
5314
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5315
                    fprintf(stderr, "Fail to parse UUID string."
5316
                            " Wrong format.\n");
5317
                    exit(1);
5318
                }
5319
                break;
5320
#ifndef _WIN32
5321
            case QEMU_OPTION_daemonize:
5322
                daemonize = 1;
5323
                break;
5324
#endif
5325
            case QEMU_OPTION_option_rom:
5326
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5327
                    fprintf(stderr, "Too many option ROMs\n");
5328
                    exit(1);
5329
                }
5330
                option_rom[nb_option_roms] = optarg;
5331
                nb_option_roms++;
5332
                break;
5333
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5334
            case QEMU_OPTION_semihosting:
5335
                semihosting_enabled = 1;
5336
                break;
5337
#endif
5338
            case QEMU_OPTION_name:
5339
                qemu_name = qemu_strdup(optarg);
5340
                 {
5341
                     char *p = strchr(qemu_name, ',');
5342
                     if (p != NULL) {
5343
                        *p++ = 0;
5344
                        if (strncmp(p, "process=", 8)) {
5345
                            fprintf(stderr, "Unknown subargument %s to -name", p);
5346
                            exit(1);
5347
                        }
5348
                        p += 8;
5349
                        set_proc_name(p);
5350
                     }        
5351
                 }        
5352
                break;
5353
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5354
            case QEMU_OPTION_prom_env:
5355
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5356
                    fprintf(stderr, "Too many prom variables\n");
5357
                    exit(1);
5358
                }
5359
                prom_envs[nb_prom_envs] = optarg;
5360
                nb_prom_envs++;
5361
                break;
5362
#endif
5363
#ifdef TARGET_ARM
5364
            case QEMU_OPTION_old_param:
5365
                old_param = 1;
5366
                break;
5367
#endif
5368
            case QEMU_OPTION_clock:
5369
                configure_alarms(optarg);
5370
                break;
5371
            case QEMU_OPTION_startdate:
5372
                configure_rtc_date_offset(optarg, 1);
5373
                break;
5374
            case QEMU_OPTION_rtc:
5375
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5376
                if (!opts) {
5377
                    fprintf(stderr, "parse error: %s\n", optarg);
5378
                    exit(1);
5379
                }
5380
                configure_rtc(opts);
5381
                break;
5382
            case QEMU_OPTION_tb_size:
5383
                tb_size = strtol(optarg, NULL, 0);
5384
                if (tb_size < 0)
5385
                    tb_size = 0;
5386
                break;
5387
            case QEMU_OPTION_icount:
5388
                use_icount = 1;
5389
                if (strcmp(optarg, "auto") == 0) {
5390
                    icount_time_shift = -1;
5391
                } else {
5392
                    icount_time_shift = strtol(optarg, NULL, 0);
5393
                }
5394
                break;
5395
            case QEMU_OPTION_incoming:
5396
                incoming = optarg;
5397
                break;
5398
            case QEMU_OPTION_nodefaults:
5399
                default_serial = 0;
5400
                default_parallel = 0;
5401
                default_virtcon = 0;
5402
                default_monitor = 0;
5403
                default_vga = 0;
5404
                default_net = 0;
5405
                default_floppy = 0;
5406
                default_cdrom = 0;
5407
                default_sdcard = 0;
5408
                break;
5409
#ifndef _WIN32
5410
            case QEMU_OPTION_chroot:
5411
                chroot_dir = optarg;
5412
                break;
5413
            case QEMU_OPTION_runas:
5414
                run_as = optarg;
5415
                break;
5416
#endif
5417
#ifdef CONFIG_XEN
5418
            case QEMU_OPTION_xen_domid:
5419
                xen_domid = atoi(optarg);
5420
                break;
5421
            case QEMU_OPTION_xen_create:
5422
                xen_mode = XEN_CREATE;
5423
                break;
5424
            case QEMU_OPTION_xen_attach:
5425
                xen_mode = XEN_ATTACH;
5426
                break;
5427
#endif
5428
            case QEMU_OPTION_readconfig:
5429
                {
5430
                    FILE *fp;
5431
                    fp = fopen(optarg, "r");
5432
                    if (fp == NULL) {
5433
                        fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5434
                        exit(1);
5435
                    }
5436
                    if (qemu_config_parse(fp) != 0) {
5437
                        exit(1);
5438
                    }
5439
                    fclose(fp);
5440
                    break;
5441
                }
5442
            case QEMU_OPTION_writeconfig:
5443
                {
5444
                    FILE *fp;
5445
                    if (strcmp(optarg, "-") == 0) {
5446
                        fp = stdout;
5447
                    } else {
5448
                        fp = fopen(optarg, "w");
5449
                        if (fp == NULL) {
5450
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5451
                            exit(1);
5452
                        }
5453
                    }
5454
                    qemu_config_write(fp);
5455
                    fclose(fp);
5456
                    break;
5457
                }
5458
            }
5459
        }
5460
    }
5461

    
5462
    /* If no data_dir is specified then try to find it relative to the
5463
       executable path.  */
5464
    if (!data_dir) {
5465
        data_dir = find_datadir(argv[0]);
5466
    }
5467
    /* If all else fails use the install patch specified when building.  */
5468
    if (!data_dir) {
5469
        data_dir = CONFIG_QEMU_SHAREDIR;
5470
    }
5471

    
5472
    /*
5473
     * Default to max_cpus = smp_cpus, in case the user doesn't
5474
     * specify a max_cpus value.
5475
     */
5476
    if (!max_cpus)
5477
        max_cpus = smp_cpus;
5478

    
5479
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5480
    if (smp_cpus > machine->max_cpus) {
5481
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5482
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5483
                machine->max_cpus);
5484
        exit(1);
5485
    }
5486

    
5487
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5488
    qemu_opts_foreach(&qemu_global_opts, default_driver_check, NULL, 0);
5489

    
5490
    if (machine->no_serial) {
5491
        default_serial = 0;
5492
    }
5493
    if (machine->no_parallel) {
5494
        default_parallel = 0;
5495
    }
5496
    if (!machine->use_virtcon) {
5497
        default_virtcon = 0;
5498
    }
5499
    if (machine->no_vga) {
5500
        default_vga = 0;
5501
    }
5502
    if (machine->no_floppy) {
5503
        default_floppy = 0;
5504
    }
5505
    if (machine->no_cdrom) {
5506
        default_cdrom = 0;
5507
    }
5508
    if (machine->no_sdcard) {
5509
        default_sdcard = 0;
5510
    }
5511

    
5512
    if (display_type == DT_NOGRAPHIC) {
5513
        if (default_parallel)
5514
            add_device_config(DEV_PARALLEL, "null");
5515
        if (default_serial && default_monitor) {
5516
            add_device_config(DEV_SERIAL, "mon:stdio");
5517
        } else if (default_virtcon && default_monitor) {
5518
            add_device_config(DEV_VIRTCON, "mon:stdio");
5519
        } else {
5520
            if (default_serial)
5521
                add_device_config(DEV_SERIAL, "stdio");
5522
            if (default_virtcon)
5523
                add_device_config(DEV_VIRTCON, "stdio");
5524
            if (default_monitor)
5525
                monitor_parse("stdio", "readline");
5526
        }
5527
    } else {
5528
        if (default_serial)
5529
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5530
        if (default_parallel)
5531
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5532
        if (default_monitor)
5533
            monitor_parse("vc:80Cx24C", "readline");
5534
        if (default_virtcon)
5535
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5536
    }
5537
    if (default_vga)
5538
        vga_interface_type = VGA_CIRRUS;
5539

    
5540
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5541
        exit(1);
5542

    
5543
#ifndef _WIN32
5544
    if (daemonize) {
5545
        pid_t pid;
5546

    
5547
        if (pipe(fds) == -1)
5548
            exit(1);
5549

    
5550
        pid = fork();
5551
        if (pid > 0) {
5552
            uint8_t status;
5553
            ssize_t len;
5554

    
5555
            close(fds[1]);
5556

    
5557
        again:
5558
            len = read(fds[0], &status, 1);
5559
            if (len == -1 && (errno == EINTR))
5560
                goto again;
5561

    
5562
            if (len != 1)
5563
                exit(1);
5564
            else if (status == 1) {
5565
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5566
                exit(1);
5567
            } else
5568
                exit(0);
5569
        } else if (pid < 0)
5570
            exit(1);
5571

    
5572
        close(fds[0]);
5573
        qemu_set_cloexec(fds[1]);
5574

    
5575
        setsid();
5576

    
5577
        pid = fork();
5578
        if (pid > 0)
5579
            exit(0);
5580
        else if (pid < 0)
5581
            exit(1);
5582

    
5583
        umask(027);
5584

    
5585
        signal(SIGTSTP, SIG_IGN);
5586
        signal(SIGTTOU, SIG_IGN);
5587
        signal(SIGTTIN, SIG_IGN);
5588
    }
5589
#endif
5590

    
5591
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5592
#ifndef _WIN32
5593
        if (daemonize) {
5594
            uint8_t status = 1;
5595
            write(fds[1], &status, 1);
5596
        } else
5597
#endif
5598
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5599
        exit(1);
5600
    }
5601

    
5602
    if (kvm_enabled()) {
5603
        int ret;
5604

    
5605
        ret = kvm_init(smp_cpus);
5606
        if (ret < 0) {
5607
            fprintf(stderr, "failed to initialize KVM\n");
5608
            exit(1);
5609
        }
5610
    }
5611

    
5612
    if (qemu_init_main_loop()) {
5613
        fprintf(stderr, "qemu_init_main_loop failed\n");
5614
        exit(1);
5615
    }
5616
    linux_boot = (kernel_filename != NULL);
5617

    
5618
    if (!linux_boot && *kernel_cmdline != '\0') {
5619
        fprintf(stderr, "-append only allowed with -kernel option\n");
5620
        exit(1);
5621
    }
5622

    
5623
    if (!linux_boot && initrd_filename != NULL) {
5624
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5625
        exit(1);
5626
    }
5627

    
5628
#ifndef _WIN32
5629
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5630
    setvbuf(stdout, NULL, _IOLBF, 0);
5631
#endif
5632

    
5633
    if (init_timer_alarm() < 0) {
5634
        fprintf(stderr, "could not initialize alarm timer\n");
5635
        exit(1);
5636
    }
5637
    if (use_icount && icount_time_shift < 0) {
5638
        use_icount = 2;
5639
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5640
           It will be corrected fairly quickly anyway.  */
5641
        icount_time_shift = 3;
5642
        init_icount_adjust();
5643
    }
5644

    
5645
#ifdef _WIN32
5646
    socket_init();
5647
#endif
5648

    
5649
    if (net_init_clients() < 0) {
5650
        exit(1);
5651
    }
5652

    
5653
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5654
    net_set_boot_mask(net_boot);
5655

    
5656
    /* init the bluetooth world */
5657
    if (foreach_device_config(DEV_BT, bt_parse))
5658
        exit(1);
5659

    
5660
    /* init the memory */
5661
    if (ram_size == 0)
5662
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5663

    
5664
    /* init the dynamic translator */
5665
    cpu_exec_init_all(tb_size * 1024 * 1024);
5666

    
5667
    bdrv_init_with_whitelist();
5668

    
5669
    blk_mig_init();
5670

    
5671
    if (default_cdrom) {
5672
        /* we always create the cdrom drive, even if no disk is there */
5673
        drive_add(NULL, CDROM_ALIAS);
5674
    }
5675

    
5676
    if (default_floppy) {
5677
        /* we always create at least one floppy */
5678
        drive_add(NULL, FD_ALIAS, 0);
5679
    }
5680

    
5681
    if (default_sdcard) {
5682
        /* we always create one sd slot, even if no card is in it */
5683
        drive_add(NULL, SD_ALIAS);
5684
    }
5685

    
5686
    /* open the virtual block devices */
5687
    if (snapshot)
5688
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5689
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5690
        exit(1);
5691

    
5692
    vmstate_register(0, &vmstate_timers ,&timers_state);
5693
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5694
                         ram_load, NULL);
5695

    
5696
    if (nb_numa_nodes > 0) {
5697
        int i;
5698

    
5699
        if (nb_numa_nodes > smp_cpus) {
5700
            nb_numa_nodes = smp_cpus;
5701
        }
5702

    
5703
        /* If no memory size if given for any node, assume the default case
5704
         * and distribute the available memory equally across all nodes
5705
         */
5706
        for (i = 0; i < nb_numa_nodes; i++) {
5707
            if (node_mem[i] != 0)
5708
                break;
5709
        }
5710
        if (i == nb_numa_nodes) {
5711
            uint64_t usedmem = 0;
5712

    
5713
            /* On Linux, the each node's border has to be 8MB aligned,
5714
             * the final node gets the rest.
5715
             */
5716
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5717
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5718
                usedmem += node_mem[i];
5719
            }
5720
            node_mem[i] = ram_size - usedmem;
5721
        }
5722

    
5723
        for (i = 0; i < nb_numa_nodes; i++) {
5724
            if (node_cpumask[i] != 0)
5725
                break;
5726
        }
5727
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5728
         * must cope with this anyway, because there are BIOSes out there in
5729
         * real machines which also use this scheme.
5730
         */
5731
        if (i == nb_numa_nodes) {
5732
            for (i = 0; i < smp_cpus; i++) {
5733
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5734
            }
5735
        }
5736
    }
5737

    
5738
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5739
        exit(1);
5740
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5741
        exit(1);
5742
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5743
        exit(1);
5744
    if (foreach_device_config(DEV_DEBUGCON, debugcon_parse) < 0)
5745
        exit(1);
5746

    
5747
    module_call_init(MODULE_INIT_DEVICE);
5748

    
5749
    if (watchdog) {
5750
        i = select_watchdog(watchdog);
5751
        if (i > 0)
5752
            exit (i == 1 ? 1 : 0);
5753
    }
5754

    
5755
    if (machine->compat_props) {
5756
        qdev_prop_register_global_list(machine->compat_props);
5757
    }
5758
    qemu_add_globals();
5759

    
5760
    machine->init(ram_size, boot_devices,
5761
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5762

    
5763

    
5764
#ifndef _WIN32
5765
    /* must be after terminal init, SDL library changes signal handlers */
5766
    sighandler_setup();
5767
#endif
5768

    
5769
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5770
        for (i = 0; i < nb_numa_nodes; i++) {
5771
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5772
                env->numa_node = i;
5773
            }
5774
        }
5775
    }
5776

    
5777
    current_machine = machine;
5778

    
5779
    /* init USB devices */
5780
    if (usb_enabled) {
5781
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
5782
            exit(1);
5783
    }
5784

    
5785
    /* init generic devices */
5786
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5787
        exit(1);
5788

    
5789
    if (!display_state)
5790
        dumb_display_init();
5791
    /* just use the first displaystate for the moment */
5792
    ds = display_state;
5793

    
5794
    if (display_type == DT_DEFAULT) {
5795
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5796
        display_type = DT_SDL;
5797
#else
5798
        display_type = DT_VNC;
5799
        vnc_display = "localhost:0,to=99";
5800
        show_vnc_port = 1;
5801
#endif
5802
    }
5803
        
5804

    
5805
    switch (display_type) {
5806
    case DT_NOGRAPHIC:
5807
        break;
5808
#if defined(CONFIG_CURSES)
5809
    case DT_CURSES:
5810
        curses_display_init(ds, full_screen);
5811
        break;
5812
#endif
5813
#if defined(CONFIG_SDL)
5814
    case DT_SDL:
5815
        sdl_display_init(ds, full_screen, no_frame);
5816
        break;
5817
#elif defined(CONFIG_COCOA)
5818
    case DT_SDL:
5819
        cocoa_display_init(ds, full_screen);
5820
        break;
5821
#endif
5822
    case DT_VNC:
5823
        vnc_display_init(ds);
5824
        if (vnc_display_open(ds, vnc_display) < 0)
5825
            exit(1);
5826

    
5827
        if (show_vnc_port) {
5828
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5829
        }
5830
        break;
5831
    default:
5832
        break;
5833
    }
5834
    dpy_resize(ds);
5835

    
5836
    dcl = ds->listeners;
5837
    while (dcl != NULL) {
5838
        if (dcl->dpy_refresh != NULL) {
5839
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5840
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5841
        }
5842
        dcl = dcl->next;
5843
    }
5844

    
5845
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5846
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5847
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5848
    }
5849

    
5850
    text_consoles_set_display(display_state);
5851

    
5852
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
5853
        exit(1);
5854

    
5855
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5856
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5857
                gdbstub_dev);
5858
        exit(1);
5859
    }
5860

    
5861
    qdev_machine_creation_done();
5862

    
5863
    if (rom_load_all() != 0) {
5864
        fprintf(stderr, "rom loading failed\n");
5865
        exit(1);
5866
    }
5867

    
5868
    qemu_system_reset();
5869
    if (loadvm) {
5870
        if (load_vmstate(cur_mon, loadvm) < 0) {
5871
            autostart = 0;
5872
        }
5873
    }
5874

    
5875
    if (incoming) {
5876
        qemu_start_incoming_migration(incoming);
5877
    } else if (autostart) {
5878
        vm_start();
5879
    }
5880

    
5881
#ifndef _WIN32
5882
    if (daemonize) {
5883
        uint8_t status = 0;
5884
        ssize_t len;
5885

    
5886
    again1:
5887
        len = write(fds[1], &status, 1);
5888
        if (len == -1 && (errno == EINTR))
5889
            goto again1;
5890

    
5891
        if (len != 1)
5892
            exit(1);
5893

    
5894
        chdir("/");
5895
        TFR(fd = qemu_open("/dev/null", O_RDWR));
5896
        if (fd == -1)
5897
            exit(1);
5898
    }
5899

    
5900
    if (run_as) {
5901
        pwd = getpwnam(run_as);
5902
        if (!pwd) {
5903
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5904
            exit(1);
5905
        }
5906
    }
5907

    
5908
    if (chroot_dir) {
5909
        if (chroot(chroot_dir) < 0) {
5910
            fprintf(stderr, "chroot failed\n");
5911
            exit(1);
5912
        }
5913
        chdir("/");
5914
    }
5915

    
5916
    if (run_as) {
5917
        if (setgid(pwd->pw_gid) < 0) {
5918
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5919
            exit(1);
5920
        }
5921
        if (setuid(pwd->pw_uid) < 0) {
5922
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5923
            exit(1);
5924
        }
5925
        if (setuid(0) != -1) {
5926
            fprintf(stderr, "Dropping privileges failed\n");
5927
            exit(1);
5928
        }
5929
    }
5930

    
5931
    if (daemonize) {
5932
        dup2(fd, 0);
5933
        dup2(fd, 1);
5934
        dup2(fd, 2);
5935

    
5936
        close(fd);
5937
    }
5938
#endif
5939

    
5940
    main_loop();
5941
    quit_timers();
5942
    net_cleanup();
5943

    
5944
    return 0;
5945
}