Statistics
| Branch: | Revision:

root / vl.c @ f64382ba

History | View | Annotate | Download (152.2 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
#if defined(__NetBSD__)
48
#include <net/if_tap.h>
49
#endif
50
#ifdef __linux__
51
#include <linux/if_tun.h>
52
#endif
53
#include <arpa/inet.h>
54
#include <dirent.h>
55
#include <netdb.h>
56
#include <sys/select.h>
57
#ifdef CONFIG_BSD
58
#include <sys/stat.h>
59
#if defined(__FreeBSD__) || defined(__DragonFly__)
60
#include <libutil.h>
61
#else
62
#include <util.h>
63
#endif
64
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
65
#include <freebsd/stdlib.h>
66
#else
67
#ifdef __linux__
68
#include <pty.h>
69
#include <malloc.h>
70
#include <linux/rtc.h>
71
#include <sys/prctl.h>
72

    
73
/* For the benefit of older linux systems which don't supply it,
74
   we use a local copy of hpet.h. */
75
/* #include <linux/hpet.h> */
76
#include "hpet.h"
77

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

    
102
#if defined(__OpenBSD__)
103
#include <util.h>
104
#endif
105

    
106
#if defined(CONFIG_VDE)
107
#include <libvdeplug.h>
108
#endif
109

    
110
#ifdef _WIN32
111
#include <windows.h>
112
#include <mmsystem.h>
113
#endif
114

    
115
#ifdef CONFIG_SDL
116
#if defined(__APPLE__) || defined(main)
117
#include <SDL.h>
118
int qemu_main(int argc, char **argv, char **envp);
119
int main(int argc, char **argv)
120
{
121
    return qemu_main(argc, argv, NULL);
122
}
123
#undef main
124
#define main qemu_main
125
#endif
126
#endif /* CONFIG_SDL */
127

    
128
#ifdef CONFIG_COCOA
129
#undef main
130
#define main qemu_main
131
#endif /* CONFIG_COCOA */
132

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

    
164
#include "disas.h"
165

    
166
#include "exec-all.h"
167

    
168
#include "qemu_socket.h"
169

    
170
#include "slirp/libslirp.h"
171

    
172
#include "qemu-queue.h"
173

    
174
//#define DEBUG_NET
175
//#define DEBUG_SLIRP
176

    
177
#define DEFAULT_RAM_SIZE 128
178

    
179
/* Maximum number of monitor devices */
180
#define MAX_MONITOR_DEVICES 10
181

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

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

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

    
271
uint8_t qemu_uuid[16];
272

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

    
276
/***********************************************************/
277
/* x86 ISA bus support */
278

    
279
target_phys_addr_t isa_mem_base = 0;
280
PicState2 *isa_pic;
281

    
282
/***********************************************************/
283
void hw_error(const char *fmt, ...)
284
{
285
    va_list ap;
286
    CPUState *env;
287

    
288
    va_start(ap, fmt);
289
    fprintf(stderr, "qemu: hardware error: ");
290
    vfprintf(stderr, fmt, ap);
291
    fprintf(stderr, "\n");
292
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
293
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
294
#ifdef TARGET_I386
295
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
296
#else
297
        cpu_dump_state(env, stderr, fprintf, 0);
298
#endif
299
    }
300
    va_end(ap);
301
    abort();
302
}
303

    
304
static void set_proc_name(const char *s)
305
{
306
#if defined(__linux__) && defined(PR_SET_NAME)
307
    char name[16];
308
    if (!s)
309
        return;
310
    name[sizeof(name) - 1] = 0;
311
    strncpy(name, s, sizeof(name));
312
    /* Could rewrite argv[0] too, but that's a bit more complicated.
313
       This simple way is enough for `top'. */
314
    prctl(PR_SET_NAME, name);
315
#endif            
316
}
317
 
318
/***************/
319
/* ballooning */
320

    
321
static QEMUBalloonEvent *qemu_balloon_event;
322
void *qemu_balloon_event_opaque;
323

    
324
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
325
{
326
    qemu_balloon_event = func;
327
    qemu_balloon_event_opaque = opaque;
328
}
329

    
330
void qemu_balloon(ram_addr_t target)
331
{
332
    if (qemu_balloon_event)
333
        qemu_balloon_event(qemu_balloon_event_opaque, target);
334
}
335

    
336
ram_addr_t qemu_balloon_status(void)
337
{
338
    if (qemu_balloon_event)
339
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
340
    return 0;
341
}
342

    
343
/***********************************************************/
344
/* keyboard/mouse */
345

    
346
static QEMUPutKBDEvent *qemu_put_kbd_event;
347
static void *qemu_put_kbd_event_opaque;
348
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
349
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
350

    
351
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
352
{
353
    qemu_put_kbd_event_opaque = opaque;
354
    qemu_put_kbd_event = func;
355
}
356

    
357
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
358
                                                void *opaque, int absolute,
359
                                                const char *name)
360
{
361
    QEMUPutMouseEntry *s, *cursor;
362

    
363
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
364

    
365
    s->qemu_put_mouse_event = func;
366
    s->qemu_put_mouse_event_opaque = opaque;
367
    s->qemu_put_mouse_event_absolute = absolute;
368
    s->qemu_put_mouse_event_name = qemu_strdup(name);
369
    s->next = NULL;
370

    
371
    if (!qemu_put_mouse_event_head) {
372
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
373
        return s;
374
    }
375

    
376
    cursor = qemu_put_mouse_event_head;
377
    while (cursor->next != NULL)
378
        cursor = cursor->next;
379

    
380
    cursor->next = s;
381
    qemu_put_mouse_event_current = s;
382

    
383
    return s;
384
}
385

    
386
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
387
{
388
    QEMUPutMouseEntry *prev = NULL, *cursor;
389

    
390
    if (!qemu_put_mouse_event_head || entry == NULL)
391
        return;
392

    
393
    cursor = qemu_put_mouse_event_head;
394
    while (cursor != NULL && cursor != entry) {
395
        prev = cursor;
396
        cursor = cursor->next;
397
    }
398

    
399
    if (cursor == NULL) // does not exist or list empty
400
        return;
401
    else if (prev == NULL) { // entry is head
402
        qemu_put_mouse_event_head = cursor->next;
403
        if (qemu_put_mouse_event_current == entry)
404
            qemu_put_mouse_event_current = cursor->next;
405
        qemu_free(entry->qemu_put_mouse_event_name);
406
        qemu_free(entry);
407
        return;
408
    }
409

    
410
    prev->next = entry->next;
411

    
412
    if (qemu_put_mouse_event_current == entry)
413
        qemu_put_mouse_event_current = prev;
414

    
415
    qemu_free(entry->qemu_put_mouse_event_name);
416
    qemu_free(entry);
417
}
418

    
419
void kbd_put_keycode(int keycode)
420
{
421
    if (qemu_put_kbd_event) {
422
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
423
    }
424
}
425

    
426
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
427
{
428
    QEMUPutMouseEvent *mouse_event;
429
    void *mouse_event_opaque;
430
    int width;
431

    
432
    if (!qemu_put_mouse_event_current) {
433
        return;
434
    }
435

    
436
    mouse_event =
437
        qemu_put_mouse_event_current->qemu_put_mouse_event;
438
    mouse_event_opaque =
439
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
440

    
441
    if (mouse_event) {
442
        if (graphic_rotate) {
443
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
444
                width = 0x7fff;
445
            else
446
                width = graphic_width - 1;
447
            mouse_event(mouse_event_opaque,
448
                                 width - dy, dx, dz, buttons_state);
449
        } else
450
            mouse_event(mouse_event_opaque,
451
                                 dx, dy, dz, buttons_state);
452
    }
453
}
454

    
455
int kbd_mouse_is_absolute(void)
456
{
457
    if (!qemu_put_mouse_event_current)
458
        return 0;
459

    
460
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
461
}
462

    
463
void do_info_mice(Monitor *mon)
464
{
465
    QEMUPutMouseEntry *cursor;
466
    int index = 0;
467

    
468
    if (!qemu_put_mouse_event_head) {
469
        monitor_printf(mon, "No mouse devices connected\n");
470
        return;
471
    }
472

    
473
    monitor_printf(mon, "Mouse devices available:\n");
474
    cursor = qemu_put_mouse_event_head;
475
    while (cursor != NULL) {
476
        monitor_printf(mon, "%c Mouse #%d: %s\n",
477
                       (cursor == qemu_put_mouse_event_current ? '*' : ' '),
478
                       index, cursor->qemu_put_mouse_event_name);
479
        index++;
480
        cursor = cursor->next;
481
    }
482
}
483

    
484
void do_mouse_set(Monitor *mon, const QDict *qdict)
485
{
486
    QEMUPutMouseEntry *cursor;
487
    int i = 0;
488
    int index = qdict_get_int(qdict, "index");
489

    
490
    if (!qemu_put_mouse_event_head) {
491
        monitor_printf(mon, "No mouse devices connected\n");
492
        return;
493
    }
494

    
495
    cursor = qemu_put_mouse_event_head;
496
    while (cursor != NULL && index != i) {
497
        i++;
498
        cursor = cursor->next;
499
    }
500

    
501
    if (cursor != NULL)
502
        qemu_put_mouse_event_current = cursor;
503
    else
504
        monitor_printf(mon, "Mouse at given index not found\n");
505
}
506

    
507
/* compute with 96 bit intermediate result: (a*b)/c */
508
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
509
{
510
    union {
511
        uint64_t ll;
512
        struct {
513
#ifdef HOST_WORDS_BIGENDIAN
514
            uint32_t high, low;
515
#else
516
            uint32_t low, high;
517
#endif
518
        } l;
519
    } u, res;
520
    uint64_t rl, rh;
521

    
522
    u.ll = a;
523
    rl = (uint64_t)u.l.low * (uint64_t)b;
524
    rh = (uint64_t)u.l.high * (uint64_t)b;
525
    rh += (rl >> 32);
526
    res.l.high = rh / c;
527
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
528
    return res.ll;
529
}
530

    
531
/***********************************************************/
532
/* real time host monotonic timer */
533

    
534
#ifdef WIN32
535

    
536
static int64_t clock_freq;
537

    
538
static void init_get_clock(void)
539
{
540
    LARGE_INTEGER freq;
541
    int ret;
542
    ret = QueryPerformanceFrequency(&freq);
543
    if (ret == 0) {
544
        fprintf(stderr, "Could not calibrate ticks\n");
545
        exit(1);
546
    }
547
    clock_freq = freq.QuadPart;
548
}
549

    
550
static int64_t get_clock(void)
551
{
552
    LARGE_INTEGER ti;
553
    QueryPerformanceCounter(&ti);
554
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
555
}
556

    
557
#else
558

    
559
static int use_rt_clock;
560

    
561
static void init_get_clock(void)
562
{
563
    use_rt_clock = 0;
564
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
565
    || defined(__DragonFly__)
566
    {
567
        struct timespec ts;
568
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
569
            use_rt_clock = 1;
570
        }
571
    }
572
#endif
573
}
574

    
575
static int64_t get_clock(void)
576
{
577
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
578
        || defined(__DragonFly__)
579
    if (use_rt_clock) {
580
        struct timespec ts;
581
        clock_gettime(CLOCK_MONOTONIC, &ts);
582
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
583
    } else
584
#endif
585
    {
586
        /* XXX: using gettimeofday leads to problems if the date
587
           changes, so it should be avoided. */
588
        struct timeval tv;
589
        gettimeofday(&tv, NULL);
590
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
591
    }
592
}
593
#endif
594

    
595
/* Return the virtual CPU time, based on the instruction counter.  */
596
static int64_t cpu_get_icount(void)
597
{
598
    int64_t icount;
599
    CPUState *env = cpu_single_env;;
600
    icount = qemu_icount;
601
    if (env) {
602
        if (!can_do_io(env))
603
            fprintf(stderr, "Bad clock read\n");
604
        icount -= (env->icount_decr.u16.low + env->icount_extra);
605
    }
606
    return qemu_icount_bias + (icount << icount_time_shift);
607
}
608

    
609
/***********************************************************/
610
/* guest cycle counter */
611

    
612
typedef struct TimersState {
613
    int64_t cpu_ticks_prev;
614
    int64_t cpu_ticks_offset;
615
    int64_t cpu_clock_offset;
616
    int32_t cpu_ticks_enabled;
617
    int64_t dummy;
618
} TimersState;
619

    
620
TimersState timers_state;
621

    
622
/* return the host CPU cycle counter and handle stop/restart */
623
int64_t cpu_get_ticks(void)
624
{
625
    if (use_icount) {
626
        return cpu_get_icount();
627
    }
628
    if (!timers_state.cpu_ticks_enabled) {
629
        return timers_state.cpu_ticks_offset;
630
    } else {
631
        int64_t ticks;
632
        ticks = cpu_get_real_ticks();
633
        if (timers_state.cpu_ticks_prev > ticks) {
634
            /* Note: non increasing ticks may happen if the host uses
635
               software suspend */
636
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
637
        }
638
        timers_state.cpu_ticks_prev = ticks;
639
        return ticks + timers_state.cpu_ticks_offset;
640
    }
641
}
642

    
643
/* return the host CPU monotonic timer and handle stop/restart */
644
static int64_t cpu_get_clock(void)
645
{
646
    int64_t ti;
647
    if (!timers_state.cpu_ticks_enabled) {
648
        return timers_state.cpu_clock_offset;
649
    } else {
650
        ti = get_clock();
651
        return ti + timers_state.cpu_clock_offset;
652
    }
653
}
654

    
655
/* enable cpu_get_ticks() */
656
void cpu_enable_ticks(void)
657
{
658
    if (!timers_state.cpu_ticks_enabled) {
659
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
660
        timers_state.cpu_clock_offset -= get_clock();
661
        timers_state.cpu_ticks_enabled = 1;
662
    }
663
}
664

    
665
/* disable cpu_get_ticks() : the clock is stopped. You must not call
666
   cpu_get_ticks() after that.  */
667
void cpu_disable_ticks(void)
668
{
669
    if (timers_state.cpu_ticks_enabled) {
670
        timers_state.cpu_ticks_offset = cpu_get_ticks();
671
        timers_state.cpu_clock_offset = cpu_get_clock();
672
        timers_state.cpu_ticks_enabled = 0;
673
    }
674
}
675

    
676
/***********************************************************/
677
/* timers */
678

    
679
#define QEMU_CLOCK_REALTIME 0
680
#define QEMU_CLOCK_VIRTUAL  1
681

    
682
struct QEMUClock {
683
    int type;
684
    /* XXX: add frequency */
685
};
686

    
687
struct QEMUTimer {
688
    QEMUClock *clock;
689
    int64_t expire_time;
690
    QEMUTimerCB *cb;
691
    void *opaque;
692
    struct QEMUTimer *next;
693
};
694

    
695
struct qemu_alarm_timer {
696
    char const *name;
697
    unsigned int flags;
698

    
699
    int (*start)(struct qemu_alarm_timer *t);
700
    void (*stop)(struct qemu_alarm_timer *t);
701
    void (*rearm)(struct qemu_alarm_timer *t);
702
    void *priv;
703
};
704

    
705
#define ALARM_FLAG_DYNTICKS  0x1
706
#define ALARM_FLAG_EXPIRED   0x2
707

    
708
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
709
{
710
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
711
}
712

    
713
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
714
{
715
    if (!alarm_has_dynticks(t))
716
        return;
717

    
718
    t->rearm(t);
719
}
720

    
721
/* TODO: MIN_TIMER_REARM_US should be optimized */
722
#define MIN_TIMER_REARM_US 250
723

    
724
static struct qemu_alarm_timer *alarm_timer;
725

    
726
#ifdef _WIN32
727

    
728
struct qemu_alarm_win32 {
729
    MMRESULT timerId;
730
    unsigned int period;
731
} alarm_win32_data = {0, -1};
732

    
733
static int win32_start_timer(struct qemu_alarm_timer *t);
734
static void win32_stop_timer(struct qemu_alarm_timer *t);
735
static void win32_rearm_timer(struct qemu_alarm_timer *t);
736

    
737
#else
738

    
739
static int unix_start_timer(struct qemu_alarm_timer *t);
740
static void unix_stop_timer(struct qemu_alarm_timer *t);
741

    
742
#ifdef __linux__
743

    
744
static int dynticks_start_timer(struct qemu_alarm_timer *t);
745
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
746
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
747

    
748
static int hpet_start_timer(struct qemu_alarm_timer *t);
749
static void hpet_stop_timer(struct qemu_alarm_timer *t);
750

    
751
static int rtc_start_timer(struct qemu_alarm_timer *t);
752
static void rtc_stop_timer(struct qemu_alarm_timer *t);
753

    
754
#endif /* __linux__ */
755

    
756
#endif /* _WIN32 */
757

    
758
/* Correlation between real and virtual time is always going to be
759
   fairly approximate, so ignore small variation.
760
   When the guest is idle real and virtual time will be aligned in
761
   the IO wait loop.  */
762
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
763

    
764
static void icount_adjust(void)
765
{
766
    int64_t cur_time;
767
    int64_t cur_icount;
768
    int64_t delta;
769
    static int64_t last_delta;
770
    /* If the VM is not running, then do nothing.  */
771
    if (!vm_running)
772
        return;
773

    
774
    cur_time = cpu_get_clock();
775
    cur_icount = qemu_get_clock(vm_clock);
776
    delta = cur_icount - cur_time;
777
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
778
    if (delta > 0
779
        && last_delta + ICOUNT_WOBBLE < delta * 2
780
        && icount_time_shift > 0) {
781
        /* The guest is getting too far ahead.  Slow time down.  */
782
        icount_time_shift--;
783
    }
784
    if (delta < 0
785
        && last_delta - ICOUNT_WOBBLE > delta * 2
786
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
787
        /* The guest is getting too far behind.  Speed time up.  */
788
        icount_time_shift++;
789
    }
790
    last_delta = delta;
791
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
792
}
793

    
794
static void icount_adjust_rt(void * opaque)
795
{
796
    qemu_mod_timer(icount_rt_timer,
797
                   qemu_get_clock(rt_clock) + 1000);
798
    icount_adjust();
799
}
800

    
801
static void icount_adjust_vm(void * opaque)
802
{
803
    qemu_mod_timer(icount_vm_timer,
804
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
805
    icount_adjust();
806
}
807

    
808
static void init_icount_adjust(void)
809
{
810
    /* Have both realtime and virtual time triggers for speed adjustment.
811
       The realtime trigger catches emulated time passing too slowly,
812
       the virtual time trigger catches emulated time passing too fast.
813
       Realtime triggers occur even when idle, so use them less frequently
814
       than VM triggers.  */
815
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
816
    qemu_mod_timer(icount_rt_timer,
817
                   qemu_get_clock(rt_clock) + 1000);
818
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
819
    qemu_mod_timer(icount_vm_timer,
820
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
821
}
822

    
823
static struct qemu_alarm_timer alarm_timers[] = {
824
#ifndef _WIN32
825
#ifdef __linux__
826
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
827
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
828
    /* HPET - if available - is preferred */
829
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
830
    /* ...otherwise try RTC */
831
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
832
#endif
833
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
834
#else
835
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
836
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
837
    {"win32", 0, win32_start_timer,
838
     win32_stop_timer, NULL, &alarm_win32_data},
839
#endif
840
    {NULL, }
841
};
842

    
843
static void show_available_alarms(void)
844
{
845
    int i;
846

    
847
    printf("Available alarm timers, in order of precedence:\n");
848
    for (i = 0; alarm_timers[i].name; i++)
849
        printf("%s\n", alarm_timers[i].name);
850
}
851

    
852
static void configure_alarms(char const *opt)
853
{
854
    int i;
855
    int cur = 0;
856
    int count = ARRAY_SIZE(alarm_timers) - 1;
857
    char *arg;
858
    char *name;
859
    struct qemu_alarm_timer tmp;
860

    
861
    if (!strcmp(opt, "?")) {
862
        show_available_alarms();
863
        exit(0);
864
    }
865

    
866
    arg = qemu_strdup(opt);
867

    
868
    /* Reorder the array */
869
    name = strtok(arg, ",");
870
    while (name) {
871
        for (i = 0; i < count && alarm_timers[i].name; i++) {
872
            if (!strcmp(alarm_timers[i].name, name))
873
                break;
874
        }
875

    
876
        if (i == count) {
877
            fprintf(stderr, "Unknown clock %s\n", name);
878
            goto next;
879
        }
880

    
881
        if (i < cur)
882
            /* Ignore */
883
            goto next;
884

    
885
        /* Swap */
886
        tmp = alarm_timers[i];
887
        alarm_timers[i] = alarm_timers[cur];
888
        alarm_timers[cur] = tmp;
889

    
890
        cur++;
891
next:
892
        name = strtok(NULL, ",");
893
    }
894

    
895
    qemu_free(arg);
896

    
897
    if (cur) {
898
        /* Disable remaining timers */
899
        for (i = cur; i < count; i++)
900
            alarm_timers[i].name = NULL;
901
    } else {
902
        show_available_alarms();
903
        exit(1);
904
    }
905
}
906

    
907
QEMUClock *rt_clock;
908
QEMUClock *vm_clock;
909

    
910
static QEMUTimer *active_timers[2];
911

    
912
static QEMUClock *qemu_new_clock(int type)
913
{
914
    QEMUClock *clock;
915
    clock = qemu_mallocz(sizeof(QEMUClock));
916
    clock->type = type;
917
    return clock;
918
}
919

    
920
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
921
{
922
    QEMUTimer *ts;
923

    
924
    ts = qemu_mallocz(sizeof(QEMUTimer));
925
    ts->clock = clock;
926
    ts->cb = cb;
927
    ts->opaque = opaque;
928
    return ts;
929
}
930

    
931
void qemu_free_timer(QEMUTimer *ts)
932
{
933
    qemu_free(ts);
934
}
935

    
936
/* stop a timer, but do not dealloc it */
937
void qemu_del_timer(QEMUTimer *ts)
938
{
939
    QEMUTimer **pt, *t;
940

    
941
    /* NOTE: this code must be signal safe because
942
       qemu_timer_expired() can be called from a signal. */
943
    pt = &active_timers[ts->clock->type];
944
    for(;;) {
945
        t = *pt;
946
        if (!t)
947
            break;
948
        if (t == ts) {
949
            *pt = t->next;
950
            break;
951
        }
952
        pt = &t->next;
953
    }
954
}
955

    
956
/* modify the current timer so that it will be fired when current_time
957
   >= expire_time. The corresponding callback will be called. */
958
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
959
{
960
    QEMUTimer **pt, *t;
961

    
962
    qemu_del_timer(ts);
963

    
964
    /* add the timer in the sorted list */
965
    /* NOTE: this code must be signal safe because
966
       qemu_timer_expired() can be called from a signal. */
967
    pt = &active_timers[ts->clock->type];
968
    for(;;) {
969
        t = *pt;
970
        if (!t)
971
            break;
972
        if (t->expire_time > expire_time)
973
            break;
974
        pt = &t->next;
975
    }
976
    ts->expire_time = expire_time;
977
    ts->next = *pt;
978
    *pt = ts;
979

    
980
    /* Rearm if necessary  */
981
    if (pt == &active_timers[ts->clock->type]) {
982
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
983
            qemu_rearm_alarm_timer(alarm_timer);
984
        }
985
        /* Interrupt execution to force deadline recalculation.  */
986
        if (use_icount)
987
            qemu_notify_event();
988
    }
989
}
990

    
991
int qemu_timer_pending(QEMUTimer *ts)
992
{
993
    QEMUTimer *t;
994
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
995
        if (t == ts)
996
            return 1;
997
    }
998
    return 0;
999
}
1000

    
1001
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1002
{
1003
    if (!timer_head)
1004
        return 0;
1005
    return (timer_head->expire_time <= current_time);
1006
}
1007

    
1008
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1009
{
1010
    QEMUTimer *ts;
1011

    
1012
    for(;;) {
1013
        ts = *ptimer_head;
1014
        if (!ts || ts->expire_time > current_time)
1015
            break;
1016
        /* remove timer from the list before calling the callback */
1017
        *ptimer_head = ts->next;
1018
        ts->next = NULL;
1019

    
1020
        /* run the callback (the timer list can be modified) */
1021
        ts->cb(ts->opaque);
1022
    }
1023
}
1024

    
1025
int64_t qemu_get_clock(QEMUClock *clock)
1026
{
1027
    switch(clock->type) {
1028
    case QEMU_CLOCK_REALTIME:
1029
        return get_clock() / 1000000;
1030
    default:
1031
    case QEMU_CLOCK_VIRTUAL:
1032
        if (use_icount) {
1033
            return cpu_get_icount();
1034
        } else {
1035
            return cpu_get_clock();
1036
        }
1037
    }
1038
}
1039

    
1040
static void init_clocks(void)
1041
{
1042
    init_get_clock();
1043
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1044
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1045
}
1046

    
1047
/* save a timer */
1048
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1049
{
1050
    uint64_t expire_time;
1051

    
1052
    if (qemu_timer_pending(ts)) {
1053
        expire_time = ts->expire_time;
1054
    } else {
1055
        expire_time = -1;
1056
    }
1057
    qemu_put_be64(f, expire_time);
1058
}
1059

    
1060
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1061
{
1062
    uint64_t expire_time;
1063

    
1064
    expire_time = qemu_get_be64(f);
1065
    if (expire_time != -1) {
1066
        qemu_mod_timer(ts, expire_time);
1067
    } else {
1068
        qemu_del_timer(ts);
1069
    }
1070
}
1071

    
1072
static const VMStateDescription vmstate_timers = {
1073
    .name = "timer",
1074
    .version_id = 2,
1075
    .minimum_version_id = 1,
1076
    .minimum_version_id_old = 1,
1077
    .fields      = (VMStateField []) {
1078
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
1079
        VMSTATE_INT64(dummy, TimersState),
1080
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1081
        VMSTATE_END_OF_LIST()
1082
    }
1083
};
1084

    
1085
static void qemu_event_increment(void);
1086

    
1087
#ifdef _WIN32
1088
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1089
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1090
                                        DWORD_PTR dw2)
1091
#else
1092
static void host_alarm_handler(int host_signum)
1093
#endif
1094
{
1095
#if 0
1096
#define DISP_FREQ 1000
1097
    {
1098
        static int64_t delta_min = INT64_MAX;
1099
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1100
        static int count;
1101
        ti = qemu_get_clock(vm_clock);
1102
        if (last_clock != 0) {
1103
            delta = ti - last_clock;
1104
            if (delta < delta_min)
1105
                delta_min = delta;
1106
            if (delta > delta_max)
1107
                delta_max = delta;
1108
            delta_cum += delta;
1109
            if (++count == DISP_FREQ) {
1110
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1111
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1112
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1113
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1114
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1115
                count = 0;
1116
                delta_min = INT64_MAX;
1117
                delta_max = 0;
1118
                delta_cum = 0;
1119
            }
1120
        }
1121
        last_clock = ti;
1122
    }
1123
#endif
1124
    if (alarm_has_dynticks(alarm_timer) ||
1125
        (!use_icount &&
1126
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1127
                               qemu_get_clock(vm_clock))) ||
1128
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1129
                           qemu_get_clock(rt_clock))) {
1130
        qemu_event_increment();
1131
        if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1132

    
1133
#ifndef CONFIG_IOTHREAD
1134
        if (next_cpu) {
1135
            /* stop the currently executing cpu because a timer occured */
1136
            cpu_exit(next_cpu);
1137
        }
1138
#endif
1139
        timer_alarm_pending = 1;
1140
        qemu_notify_event();
1141
    }
1142
}
1143

    
1144
static int64_t qemu_next_deadline(void)
1145
{
1146
    int64_t delta;
1147

    
1148
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1149
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1150
                     qemu_get_clock(vm_clock);
1151
    } else {
1152
        /* To avoid problems with overflow limit this to 2^32.  */
1153
        delta = INT32_MAX;
1154
    }
1155

    
1156
    if (delta < 0)
1157
        delta = 0;
1158

    
1159
    return delta;
1160
}
1161

    
1162
#if defined(__linux__)
1163
static uint64_t qemu_next_deadline_dyntick(void)
1164
{
1165
    int64_t delta;
1166
    int64_t rtdelta;
1167

    
1168
    if (use_icount)
1169
        delta = INT32_MAX;
1170
    else
1171
        delta = (qemu_next_deadline() + 999) / 1000;
1172

    
1173
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1174
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1175
                 qemu_get_clock(rt_clock))*1000;
1176
        if (rtdelta < delta)
1177
            delta = rtdelta;
1178
    }
1179

    
1180
    if (delta < MIN_TIMER_REARM_US)
1181
        delta = MIN_TIMER_REARM_US;
1182

    
1183
    return delta;
1184
}
1185
#endif
1186

    
1187
#ifndef _WIN32
1188

    
1189
/* Sets a specific flag */
1190
static int fcntl_setfl(int fd, int flag)
1191
{
1192
    int flags;
1193

    
1194
    flags = fcntl(fd, F_GETFL);
1195
    if (flags == -1)
1196
        return -errno;
1197

    
1198
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1199
        return -errno;
1200

    
1201
    return 0;
1202
}
1203

    
1204
#if defined(__linux__)
1205

    
1206
#define RTC_FREQ 1024
1207

    
1208
static void enable_sigio_timer(int fd)
1209
{
1210
    struct sigaction act;
1211

    
1212
    /* timer signal */
1213
    sigfillset(&act.sa_mask);
1214
    act.sa_flags = 0;
1215
    act.sa_handler = host_alarm_handler;
1216

    
1217
    sigaction(SIGIO, &act, NULL);
1218
    fcntl_setfl(fd, O_ASYNC);
1219
    fcntl(fd, F_SETOWN, getpid());
1220
}
1221

    
1222
static int hpet_start_timer(struct qemu_alarm_timer *t)
1223
{
1224
    struct hpet_info info;
1225
    int r, fd;
1226

    
1227
    fd = open("/dev/hpet", O_RDONLY);
1228
    if (fd < 0)
1229
        return -1;
1230

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

    
1240
    /* Check capabilities */
1241
    r = ioctl(fd, HPET_INFO, &info);
1242
    if (r < 0)
1243
        goto fail;
1244

    
1245
    /* Enable periodic mode */
1246
    r = ioctl(fd, HPET_EPI, 0);
1247
    if (info.hi_flags && (r < 0))
1248
        goto fail;
1249

    
1250
    /* Enable interrupt */
1251
    r = ioctl(fd, HPET_IE_ON, 0);
1252
    if (r < 0)
1253
        goto fail;
1254

    
1255
    enable_sigio_timer(fd);
1256
    t->priv = (void *)(long)fd;
1257

    
1258
    return 0;
1259
fail:
1260
    close(fd);
1261
    return -1;
1262
}
1263

    
1264
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1265
{
1266
    int fd = (long)t->priv;
1267

    
1268
    close(fd);
1269
}
1270

    
1271
static int rtc_start_timer(struct qemu_alarm_timer *t)
1272
{
1273
    int rtc_fd;
1274
    unsigned long current_rtc_freq = 0;
1275

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

    
1293
    enable_sigio_timer(rtc_fd);
1294

    
1295
    t->priv = (void *)(long)rtc_fd;
1296

    
1297
    return 0;
1298
}
1299

    
1300
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1301
{
1302
    int rtc_fd = (long)t->priv;
1303

    
1304
    close(rtc_fd);
1305
}
1306

    
1307
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1308
{
1309
    struct sigevent ev;
1310
    timer_t host_timer;
1311
    struct sigaction act;
1312

    
1313
    sigfillset(&act.sa_mask);
1314
    act.sa_flags = 0;
1315
    act.sa_handler = host_alarm_handler;
1316

    
1317
    sigaction(SIGALRM, &act, NULL);
1318

    
1319
    /* 
1320
     * Initialize ev struct to 0 to avoid valgrind complaining
1321
     * about uninitialized data in timer_create call
1322
     */
1323
    memset(&ev, 0, sizeof(ev));
1324
    ev.sigev_value.sival_int = 0;
1325
    ev.sigev_notify = SIGEV_SIGNAL;
1326
    ev.sigev_signo = SIGALRM;
1327

    
1328
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1329
        perror("timer_create");
1330

    
1331
        /* disable dynticks */
1332
        fprintf(stderr, "Dynamic Ticks disabled\n");
1333

    
1334
        return -1;
1335
    }
1336

    
1337
    t->priv = (void *)(long)host_timer;
1338

    
1339
    return 0;
1340
}
1341

    
1342
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1343
{
1344
    timer_t host_timer = (timer_t)(long)t->priv;
1345

    
1346
    timer_delete(host_timer);
1347
}
1348

    
1349
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1350
{
1351
    timer_t host_timer = (timer_t)(long)t->priv;
1352
    struct itimerspec timeout;
1353
    int64_t nearest_delta_us = INT64_MAX;
1354
    int64_t current_us;
1355

    
1356
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1357
        !active_timers[QEMU_CLOCK_VIRTUAL])
1358
        return;
1359

    
1360
    nearest_delta_us = qemu_next_deadline_dyntick();
1361

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

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

    
1383
#endif /* defined(__linux__) */
1384

    
1385
static int unix_start_timer(struct qemu_alarm_timer *t)
1386
{
1387
    struct sigaction act;
1388
    struct itimerval itv;
1389
    int err;
1390

    
1391
    /* timer signal */
1392
    sigfillset(&act.sa_mask);
1393
    act.sa_flags = 0;
1394
    act.sa_handler = host_alarm_handler;
1395

    
1396
    sigaction(SIGALRM, &act, NULL);
1397

    
1398
    itv.it_interval.tv_sec = 0;
1399
    /* for i386 kernel 2.6 to get 1 ms */
1400
    itv.it_interval.tv_usec = 999;
1401
    itv.it_value.tv_sec = 0;
1402
    itv.it_value.tv_usec = 10 * 1000;
1403

    
1404
    err = setitimer(ITIMER_REAL, &itv, NULL);
1405
    if (err)
1406
        return -1;
1407

    
1408
    return 0;
1409
}
1410

    
1411
static void unix_stop_timer(struct qemu_alarm_timer *t)
1412
{
1413
    struct itimerval itv;
1414

    
1415
    memset(&itv, 0, sizeof(itv));
1416
    setitimer(ITIMER_REAL, &itv, NULL);
1417
}
1418

    
1419
#endif /* !defined(_WIN32) */
1420

    
1421

    
1422
#ifdef _WIN32
1423

    
1424
static int win32_start_timer(struct qemu_alarm_timer *t)
1425
{
1426
    TIMECAPS tc;
1427
    struct qemu_alarm_win32 *data = t->priv;
1428
    UINT flags;
1429

    
1430
    memset(&tc, 0, sizeof(tc));
1431
    timeGetDevCaps(&tc, sizeof(tc));
1432

    
1433
    if (data->period < tc.wPeriodMin)
1434
        data->period = tc.wPeriodMin;
1435

    
1436
    timeBeginPeriod(data->period);
1437

    
1438
    flags = TIME_CALLBACK_FUNCTION;
1439
    if (alarm_has_dynticks(t))
1440
        flags |= TIME_ONESHOT;
1441
    else
1442
        flags |= TIME_PERIODIC;
1443

    
1444
    data->timerId = timeSetEvent(1,         // interval (ms)
1445
                        data->period,       // resolution
1446
                        host_alarm_handler, // function
1447
                        (DWORD)t,           // parameter
1448
                        flags);
1449

    
1450
    if (!data->timerId) {
1451
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1452
                GetLastError());
1453
        timeEndPeriod(data->period);
1454
        return -1;
1455
    }
1456

    
1457
    return 0;
1458
}
1459

    
1460
static void win32_stop_timer(struct qemu_alarm_timer *t)
1461
{
1462
    struct qemu_alarm_win32 *data = t->priv;
1463

    
1464
    timeKillEvent(data->timerId);
1465
    timeEndPeriod(data->period);
1466
}
1467

    
1468
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1469
{
1470
    struct qemu_alarm_win32 *data = t->priv;
1471

    
1472
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1473
        !active_timers[QEMU_CLOCK_VIRTUAL])
1474
        return;
1475

    
1476
    timeKillEvent(data->timerId);
1477

    
1478
    data->timerId = timeSetEvent(1,
1479
                        data->period,
1480
                        host_alarm_handler,
1481
                        (DWORD)t,
1482
                        TIME_ONESHOT | TIME_PERIODIC);
1483

    
1484
    if (!data->timerId) {
1485
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1486
                GetLastError());
1487

    
1488
        timeEndPeriod(data->period);
1489
        exit(1);
1490
    }
1491
}
1492

    
1493
#endif /* _WIN32 */
1494

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

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

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

    
1508
    if (err) {
1509
        err = -ENOENT;
1510
        goto fail;
1511
    }
1512

    
1513
    alarm_timer = t;
1514

    
1515
    return 0;
1516

    
1517
fail:
1518
    return err;
1519
}
1520

    
1521
static void quit_timers(void)
1522
{
1523
    alarm_timer->stop(alarm_timer);
1524
    alarm_timer = NULL;
1525
}
1526

    
1527
/***********************************************************/
1528
/* host time/date access */
1529
void qemu_get_timedate(struct tm *tm, int offset)
1530
{
1531
    time_t ti;
1532
    struct tm *ret;
1533

    
1534
    time(&ti);
1535
    ti += offset;
1536
    if (rtc_date_offset == -1) {
1537
        if (rtc_utc)
1538
            ret = gmtime(&ti);
1539
        else
1540
            ret = localtime(&ti);
1541
    } else {
1542
        ti -= rtc_date_offset;
1543
        ret = gmtime(&ti);
1544
    }
1545

    
1546
    memcpy(tm, ret, sizeof(struct tm));
1547
}
1548

    
1549
int qemu_timedate_diff(struct tm *tm)
1550
{
1551
    time_t seconds;
1552

    
1553
    if (rtc_date_offset == -1)
1554
        if (rtc_utc)
1555
            seconds = mktimegm(tm);
1556
        else
1557
            seconds = mktime(tm);
1558
    else
1559
        seconds = mktimegm(tm) + rtc_date_offset;
1560

    
1561
    return seconds - time(NULL);
1562
}
1563

    
1564
#ifdef _WIN32
1565
static void socket_cleanup(void)
1566
{
1567
    WSACleanup();
1568
}
1569

    
1570
static int socket_init(void)
1571
{
1572
    WSADATA Data;
1573
    int ret, err;
1574

    
1575
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1576
    if (ret != 0) {
1577
        err = WSAGetLastError();
1578
        fprintf(stderr, "WSAStartup: %d\n", err);
1579
        return -1;
1580
    }
1581
    atexit(socket_cleanup);
1582
    return 0;
1583
}
1584
#endif
1585

    
1586
/***********************************************************/
1587
/* Bluetooth support */
1588
static int nb_hcis;
1589
static int cur_hci;
1590
static struct HCIInfo *hci_table[MAX_NICS];
1591

    
1592
static struct bt_vlan_s {
1593
    struct bt_scatternet_s net;
1594
    int id;
1595
    struct bt_vlan_s *next;
1596
} *first_bt_vlan;
1597

    
1598
/* find or alloc a new bluetooth "VLAN" */
1599
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1600
{
1601
    struct bt_vlan_s **pvlan, *vlan;
1602
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1603
        if (vlan->id == id)
1604
            return &vlan->net;
1605
    }
1606
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1607
    vlan->id = id;
1608
    pvlan = &first_bt_vlan;
1609
    while (*pvlan != NULL)
1610
        pvlan = &(*pvlan)->next;
1611
    *pvlan = vlan;
1612
    return &vlan->net;
1613
}
1614

    
1615
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1616
{
1617
}
1618

    
1619
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1620
{
1621
    return -ENOTSUP;
1622
}
1623

    
1624
static struct HCIInfo null_hci = {
1625
    .cmd_send = null_hci_send,
1626
    .sco_send = null_hci_send,
1627
    .acl_send = null_hci_send,
1628
    .bdaddr_set = null_hci_addr_set,
1629
};
1630

    
1631
struct HCIInfo *qemu_next_hci(void)
1632
{
1633
    if (cur_hci == nb_hcis)
1634
        return &null_hci;
1635

    
1636
    return hci_table[cur_hci++];
1637
}
1638

    
1639
static struct HCIInfo *hci_init(const char *str)
1640
{
1641
    char *endp;
1642
    struct bt_scatternet_s *vlan = 0;
1643

    
1644
    if (!strcmp(str, "null"))
1645
        /* null */
1646
        return &null_hci;
1647
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1648
        /* host[:hciN] */
1649
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1650
    else if (!strncmp(str, "hci", 3)) {
1651
        /* hci[,vlan=n] */
1652
        if (str[3]) {
1653
            if (!strncmp(str + 3, ",vlan=", 6)) {
1654
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1655
                if (*endp)
1656
                    vlan = 0;
1657
            }
1658
        } else
1659
            vlan = qemu_find_bt_vlan(0);
1660
        if (vlan)
1661
           return bt_new_hci(vlan);
1662
    }
1663

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

    
1666
    return 0;
1667
}
1668

    
1669
static int bt_hci_parse(const char *str)
1670
{
1671
    struct HCIInfo *hci;
1672
    bdaddr_t bdaddr;
1673

    
1674
    if (nb_hcis >= MAX_NICS) {
1675
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1676
        return -1;
1677
    }
1678

    
1679
    hci = hci_init(str);
1680
    if (!hci)
1681
        return -1;
1682

    
1683
    bdaddr.b[0] = 0x52;
1684
    bdaddr.b[1] = 0x54;
1685
    bdaddr.b[2] = 0x00;
1686
    bdaddr.b[3] = 0x12;
1687
    bdaddr.b[4] = 0x34;
1688
    bdaddr.b[5] = 0x56 + nb_hcis;
1689
    hci->bdaddr_set(hci, bdaddr.b);
1690

    
1691
    hci_table[nb_hcis++] = hci;
1692

    
1693
    return 0;
1694
}
1695

    
1696
static void bt_vhci_add(int vlan_id)
1697
{
1698
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1699

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

    
1704
    bt_vhci_init(bt_new_hci(vlan));
1705
}
1706

    
1707
static struct bt_device_s *bt_device_add(const char *opt)
1708
{
1709
    struct bt_scatternet_s *vlan;
1710
    int vlan_id = 0;
1711
    char *endp = strstr(opt, ",vlan=");
1712
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1713
    char devname[10];
1714

    
1715
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1716

    
1717
    if (endp) {
1718
        vlan_id = strtol(endp + 6, &endp, 0);
1719
        if (*endp) {
1720
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1721
            return 0;
1722
        }
1723
    }
1724

    
1725
    vlan = qemu_find_bt_vlan(vlan_id);
1726

    
1727
    if (!vlan->slave)
1728
        fprintf(stderr, "qemu: warning: adding a slave device to "
1729
                        "an empty scatternet %i\n", vlan_id);
1730

    
1731
    if (!strcmp(devname, "keyboard"))
1732
        return bt_keyboard_init(vlan);
1733

    
1734
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1735
    return 0;
1736
}
1737

    
1738
static int bt_parse(const char *opt)
1739
{
1740
    const char *endp, *p;
1741
    int vlan;
1742

    
1743
    if (strstart(opt, "hci", &endp)) {
1744
        if (!*endp || *endp == ',') {
1745
            if (*endp)
1746
                if (!strstart(endp, ",vlan=", 0))
1747
                    opt = endp + 1;
1748

    
1749
            return bt_hci_parse(opt);
1750
       }
1751
    } else if (strstart(opt, "vhci", &endp)) {
1752
        if (!*endp || *endp == ',') {
1753
            if (*endp) {
1754
                if (strstart(endp, ",vlan=", &p)) {
1755
                    vlan = strtol(p, (char **) &endp, 0);
1756
                    if (*endp) {
1757
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1758
                        return 1;
1759
                    }
1760
                } else {
1761
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1762
                    return 1;
1763
                }
1764
            } else
1765
                vlan = 0;
1766

    
1767
            bt_vhci_add(vlan);
1768
            return 0;
1769
        }
1770
    } else if (strstart(opt, "device:", &endp))
1771
        return !bt_device_add(endp);
1772

    
1773
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1774
    return 1;
1775
}
1776

    
1777
/***********************************************************/
1778
/* QEMU Block devices */
1779

    
1780
#define HD_ALIAS "index=%d,media=disk"
1781
#define CDROM_ALIAS "index=2,media=cdrom"
1782
#define FD_ALIAS "index=%d,if=floppy"
1783
#define PFLASH_ALIAS "if=pflash"
1784
#define MTD_ALIAS "if=mtd"
1785
#define SD_ALIAS "index=0,if=sd"
1786

    
1787
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1788
{
1789
    va_list ap;
1790
    char optstr[1024];
1791
    QemuOpts *opts;
1792

    
1793
    va_start(ap, fmt);
1794
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1795
    va_end(ap);
1796

    
1797
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1798
    if (!opts) {
1799
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1800
                __FUNCTION__, optstr);
1801
        return NULL;
1802
    }
1803
    if (file)
1804
        qemu_opt_set(opts, "file", file);
1805
    return opts;
1806
}
1807

    
1808
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1809
{
1810
    DriveInfo *dinfo;
1811

    
1812
    /* seek interface, bus and unit */
1813

    
1814
    QTAILQ_FOREACH(dinfo, &drives, next) {
1815
        if (dinfo->type == type &&
1816
            dinfo->bus == bus &&
1817
            dinfo->unit == unit)
1818
            return dinfo;
1819
    }
1820

    
1821
    return NULL;
1822
}
1823

    
1824
DriveInfo *drive_get_by_id(const char *id)
1825
{
1826
    DriveInfo *dinfo;
1827

    
1828
    QTAILQ_FOREACH(dinfo, &drives, next) {
1829
        if (strcmp(id, dinfo->id))
1830
            continue;
1831
        return dinfo;
1832
    }
1833
    return NULL;
1834
}
1835

    
1836
int drive_get_max_bus(BlockInterfaceType type)
1837
{
1838
    int max_bus;
1839
    DriveInfo *dinfo;
1840

    
1841
    max_bus = -1;
1842
    QTAILQ_FOREACH(dinfo, &drives, next) {
1843
        if(dinfo->type == type &&
1844
           dinfo->bus > max_bus)
1845
            max_bus = dinfo->bus;
1846
    }
1847
    return max_bus;
1848
}
1849

    
1850
const char *drive_get_serial(BlockDriverState *bdrv)
1851
{
1852
    DriveInfo *dinfo;
1853

    
1854
    QTAILQ_FOREACH(dinfo, &drives, next) {
1855
        if (dinfo->bdrv == bdrv)
1856
            return dinfo->serial;
1857
    }
1858

    
1859
    return "\0";
1860
}
1861

    
1862
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1863
{
1864
    DriveInfo *dinfo;
1865

    
1866
    QTAILQ_FOREACH(dinfo, &drives, next) {
1867
        if (dinfo->bdrv == bdrv)
1868
            return dinfo->onerror;
1869
    }
1870

    
1871
    return BLOCK_ERR_STOP_ENOSPC;
1872
}
1873

    
1874
static void bdrv_format_print(void *opaque, const char *name)
1875
{
1876
    fprintf(stderr, " %s", name);
1877
}
1878

    
1879
void drive_uninit(BlockDriverState *bdrv)
1880
{
1881
    DriveInfo *dinfo;
1882

    
1883
    QTAILQ_FOREACH(dinfo, &drives, next) {
1884
        if (dinfo->bdrv != bdrv)
1885
            continue;
1886
        qemu_opts_del(dinfo->opts);
1887
        QTAILQ_REMOVE(&drives, dinfo, next);
1888
        qemu_free(dinfo);
1889
        break;
1890
    }
1891
}
1892

    
1893
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1894
                      int *fatal_error)
1895
{
1896
    const char *buf;
1897
    const char *file = NULL;
1898
    char devname[128];
1899
    const char *serial;
1900
    const char *mediastr = "";
1901
    BlockInterfaceType type;
1902
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1903
    int bus_id, unit_id;
1904
    int cyls, heads, secs, translation;
1905
    BlockDriver *drv = NULL;
1906
    QEMUMachine *machine = opaque;
1907
    int max_devs;
1908
    int index;
1909
    int cache;
1910
    int aio = 0;
1911
    int bdrv_flags, onerror;
1912
    const char *devaddr;
1913
    DriveInfo *dinfo;
1914
    int snapshot = 0;
1915

    
1916
    *fatal_error = 1;
1917

    
1918
    translation = BIOS_ATA_TRANSLATION_AUTO;
1919
    cache = 1;
1920

    
1921
    if (machine && machine->use_scsi) {
1922
        type = IF_SCSI;
1923
        max_devs = MAX_SCSI_DEVS;
1924
        pstrcpy(devname, sizeof(devname), "scsi");
1925
    } else {
1926
        type = IF_IDE;
1927
        max_devs = MAX_IDE_DEVS;
1928
        pstrcpy(devname, sizeof(devname), "ide");
1929
    }
1930
    media = MEDIA_DISK;
1931

    
1932
    /* extract parameters */
1933
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1934
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1935
    index   = qemu_opt_get_number(opts, "index", -1);
1936

    
1937
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1938
    heads = qemu_opt_get_number(opts, "heads", 0);
1939
    secs  = qemu_opt_get_number(opts, "secs", 0);
1940

    
1941
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1942

    
1943
    file = qemu_opt_get(opts, "file");
1944
    serial = qemu_opt_get(opts, "serial");
1945

    
1946
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
1947
        pstrcpy(devname, sizeof(devname), buf);
1948
        if (!strcmp(buf, "ide")) {
1949
            type = IF_IDE;
1950
            max_devs = MAX_IDE_DEVS;
1951
        } else if (!strcmp(buf, "scsi")) {
1952
            type = IF_SCSI;
1953
            max_devs = MAX_SCSI_DEVS;
1954
        } else if (!strcmp(buf, "floppy")) {
1955
            type = IF_FLOPPY;
1956
            max_devs = 0;
1957
        } else if (!strcmp(buf, "pflash")) {
1958
            type = IF_PFLASH;
1959
            max_devs = 0;
1960
        } else if (!strcmp(buf, "mtd")) {
1961
            type = IF_MTD;
1962
            max_devs = 0;
1963
        } else if (!strcmp(buf, "sd")) {
1964
            type = IF_SD;
1965
            max_devs = 0;
1966
        } else if (!strcmp(buf, "virtio")) {
1967
            type = IF_VIRTIO;
1968
            max_devs = 0;
1969
        } else if (!strcmp(buf, "xen")) {
1970
            type = IF_XEN;
1971
            max_devs = 0;
1972
        } else if (!strcmp(buf, "none")) {
1973
            type = IF_NONE;
1974
            max_devs = 0;
1975
        } else {
1976
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
1977
            return NULL;
1978
        }
1979
    }
1980

    
1981
    if (cyls || heads || secs) {
1982
        if (cyls < 1 || cyls > 16383) {
1983
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1984
            return NULL;
1985
        }
1986
        if (heads < 1 || heads > 16) {
1987
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1988
            return NULL;
1989
        }
1990
        if (secs < 1 || secs > 63) {
1991
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1992
            return NULL;
1993
        }
1994
    }
1995

    
1996
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
1997
        if (!cyls) {
1998
            fprintf(stderr,
1999
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2000
                    buf);
2001
            return NULL;
2002
        }
2003
        if (!strcmp(buf, "none"))
2004
            translation = BIOS_ATA_TRANSLATION_NONE;
2005
        else if (!strcmp(buf, "lba"))
2006
            translation = BIOS_ATA_TRANSLATION_LBA;
2007
        else if (!strcmp(buf, "auto"))
2008
            translation = BIOS_ATA_TRANSLATION_AUTO;
2009
        else {
2010
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2011
            return NULL;
2012
        }
2013
    }
2014

    
2015
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2016
        if (!strcmp(buf, "disk")) {
2017
            media = MEDIA_DISK;
2018
        } else if (!strcmp(buf, "cdrom")) {
2019
            if (cyls || secs || heads) {
2020
                fprintf(stderr,
2021
                        "qemu: '%s' invalid physical CHS format\n", buf);
2022
                return NULL;
2023
            }
2024
            media = MEDIA_CDROM;
2025
        } else {
2026
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2027
            return NULL;
2028
        }
2029
    }
2030

    
2031
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2032
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2033
            cache = 0;
2034
        else if (!strcmp(buf, "writethrough"))
2035
            cache = 1;
2036
        else if (!strcmp(buf, "writeback"))
2037
            cache = 2;
2038
        else {
2039
           fprintf(stderr, "qemu: invalid cache option\n");
2040
           return NULL;
2041
        }
2042
    }
2043

    
2044
#ifdef CONFIG_LINUX_AIO
2045
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2046
        if (!strcmp(buf, "threads"))
2047
            aio = 0;
2048
        else if (!strcmp(buf, "native"))
2049
            aio = 1;
2050
        else {
2051
           fprintf(stderr, "qemu: invalid aio option\n");
2052
           return NULL;
2053
        }
2054
    }
2055
#endif
2056

    
2057
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2058
       if (strcmp(buf, "?") == 0) {
2059
            fprintf(stderr, "qemu: Supported formats:");
2060
            bdrv_iterate_format(bdrv_format_print, NULL);
2061
            fprintf(stderr, "\n");
2062
            return NULL;
2063
        }
2064
        drv = bdrv_find_format(buf);
2065
        if (!drv) {
2066
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2067
            return NULL;
2068
        }
2069
    }
2070

    
2071
    onerror = BLOCK_ERR_STOP_ENOSPC;
2072
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2073
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2074
            fprintf(stderr, "werror is no supported by this format\n");
2075
            return NULL;
2076
        }
2077
        if (!strcmp(buf, "ignore"))
2078
            onerror = BLOCK_ERR_IGNORE;
2079
        else if (!strcmp(buf, "enospc"))
2080
            onerror = BLOCK_ERR_STOP_ENOSPC;
2081
        else if (!strcmp(buf, "stop"))
2082
            onerror = BLOCK_ERR_STOP_ANY;
2083
        else if (!strcmp(buf, "report"))
2084
            onerror = BLOCK_ERR_REPORT;
2085
        else {
2086
            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2087
            return NULL;
2088
        }
2089
    }
2090

    
2091
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2092
        if (type != IF_VIRTIO) {
2093
            fprintf(stderr, "addr is not supported\n");
2094
            return NULL;
2095
        }
2096
    }
2097

    
2098
    /* compute bus and unit according index */
2099

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

    
2116
    /* if user doesn't specify a unit_id,
2117
     * try to find the first free
2118
     */
2119

    
2120
    if (unit_id == -1) {
2121
       unit_id = 0;
2122
       while (drive_get(type, bus_id, unit_id) != NULL) {
2123
           unit_id++;
2124
           if (max_devs && unit_id >= max_devs) {
2125
               unit_id -= max_devs;
2126
               bus_id++;
2127
           }
2128
       }
2129
    }
2130

    
2131
    /* check unit id */
2132

    
2133
    if (max_devs && unit_id >= max_devs) {
2134
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2135
                unit_id, max_devs - 1);
2136
        return NULL;
2137
    }
2138

    
2139
    /*
2140
     * ignore multiple definitions
2141
     */
2142

    
2143
    if (drive_get(type, bus_id, unit_id) != NULL) {
2144
        *fatal_error = 0;
2145
        return NULL;
2146
    }
2147

    
2148
    /* init */
2149

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

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

    
2227
    if (aio == 1) {
2228
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2229
    } else {
2230
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2231
    }
2232

    
2233
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2234
        fprintf(stderr, "qemu: could not open disk image %s\n",
2235
                        file);
2236
        return NULL;
2237
    }
2238

    
2239
    if (bdrv_key_required(dinfo->bdrv))
2240
        autostart = 0;
2241
    *fatal_error = 0;
2242
    return dinfo;
2243
}
2244

    
2245
static int drive_init_func(QemuOpts *opts, void *opaque)
2246
{
2247
    QEMUMachine *machine = opaque;
2248
    int fatal_error = 0;
2249

    
2250
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2251
        if (fatal_error)
2252
            return 1;
2253
    }
2254
    return 0;
2255
}
2256

    
2257
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2258
{
2259
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2260
        qemu_opt_set(opts, "snapshot", "on");
2261
    }
2262
    return 0;
2263
}
2264

    
2265
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2266
{
2267
    boot_set_handler = func;
2268
    boot_set_opaque = opaque;
2269
}
2270

    
2271
int qemu_boot_set(const char *boot_devices)
2272
{
2273
    if (!boot_set_handler) {
2274
        return -EINVAL;
2275
    }
2276
    return boot_set_handler(boot_set_opaque, boot_devices);
2277
}
2278

    
2279
static int parse_bootdevices(char *devices)
2280
{
2281
    /* We just do some generic consistency checks */
2282
    const char *p;
2283
    int bitmap = 0;
2284

    
2285
    for (p = devices; *p != '\0'; p++) {
2286
        /* Allowed boot devices are:
2287
         * a-b: floppy disk drives
2288
         * c-f: IDE disk drives
2289
         * g-m: machine implementation dependant drives
2290
         * n-p: network devices
2291
         * It's up to each machine implementation to check if the given boot
2292
         * devices match the actual hardware implementation and firmware
2293
         * features.
2294
         */
2295
        if (*p < 'a' || *p > 'p') {
2296
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2297
            exit(1);
2298
        }
2299
        if (bitmap & (1 << (*p - 'a'))) {
2300
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2301
            exit(1);
2302
        }
2303
        bitmap |= 1 << (*p - 'a');
2304
    }
2305
    return bitmap;
2306
}
2307

    
2308
static void restore_boot_devices(void *opaque)
2309
{
2310
    char *standard_boot_devices = opaque;
2311

    
2312
    qemu_boot_set(standard_boot_devices);
2313

    
2314
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2315
    qemu_free(standard_boot_devices);
2316
}
2317

    
2318
static void numa_add(const char *optarg)
2319
{
2320
    char option[128];
2321
    char *endptr;
2322
    unsigned long long value, endvalue;
2323
    int nodenr;
2324

    
2325
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2326
    if (!strcmp(option, "node")) {
2327
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2328
            nodenr = nb_numa_nodes;
2329
        } else {
2330
            nodenr = strtoull(option, NULL, 10);
2331
        }
2332

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

    
2374
static void smp_parse(const char *optarg)
2375
{
2376
    int smp, sockets = 0, threads = 0, cores = 0;
2377
    char *endptr;
2378
    char option[128];
2379

    
2380
    smp = strtoul(optarg, &endptr, 10);
2381
    if (endptr != optarg) {
2382
        if (*endptr == ',') {
2383
            endptr++;
2384
        }
2385
    }
2386
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2387
        sockets = strtoull(option, NULL, 10);
2388
    if (get_param_value(option, 128, "cores", endptr) != 0)
2389
        cores = strtoull(option, NULL, 10);
2390
    if (get_param_value(option, 128, "threads", endptr) != 0)
2391
        threads = strtoull(option, NULL, 10);
2392
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2393
        max_cpus = strtoull(option, NULL, 10);
2394

    
2395
    /* compute missing values, prefer sockets over cores over threads */
2396
    if (smp == 0 || sockets == 0) {
2397
        sockets = sockets > 0 ? sockets : 1;
2398
        cores = cores > 0 ? cores : 1;
2399
        threads = threads > 0 ? threads : 1;
2400
        if (smp == 0) {
2401
            smp = cores * threads * sockets;
2402
        } else {
2403
            sockets = smp / (cores * threads);
2404
        }
2405
    } else {
2406
        if (cores == 0) {
2407
            threads = threads > 0 ? threads : 1;
2408
            cores = smp / (sockets * threads);
2409
        } else {
2410
            if (sockets == 0) {
2411
                sockets = smp / (cores * threads);
2412
            } else {
2413
                threads = smp / (cores * sockets);
2414
            }
2415
        }
2416
    }
2417
    smp_cpus = smp;
2418
    smp_cores = cores > 0 ? cores : 1;
2419
    smp_threads = threads > 0 ? threads : 1;
2420
    if (max_cpus == 0)
2421
        max_cpus = smp_cpus;
2422
}
2423

    
2424
/***********************************************************/
2425
/* USB devices */
2426

    
2427
static void usb_msd_password_cb(void *opaque, int err)
2428
{
2429
    USBDevice *dev = opaque;
2430

    
2431
    if (!err)
2432
        usb_device_attach(dev);
2433
    else
2434
        dev->info->handle_destroy(dev);
2435
}
2436

    
2437
static struct {
2438
    const char *name;
2439
    const char *qdev;
2440
} usbdevs[] = {
2441
    {
2442
        .name = "mouse",
2443
        .qdev = "QEMU USB Mouse",
2444
    },{
2445
        .name = "tablet",
2446
        .qdev = "QEMU USB Tablet",
2447
    },{
2448
        .name = "keyboard",
2449
        .qdev = "QEMU USB Keyboard",
2450
    },{
2451
        .name = "wacom-tablet",
2452
        .qdev = "QEMU PenPartner Tablet",
2453
    }
2454
};
2455

    
2456
static int usb_device_add(const char *devname, int is_hotplug)
2457
{
2458
    const char *p;
2459
    USBBus *bus = usb_bus_find(-1 /* any */);
2460
    USBDevice *dev = NULL;
2461
    int i;
2462

    
2463
    if (!usb_enabled)
2464
        return -1;
2465

    
2466
    /* simple devices which don't need extra care */
2467
    for (i = 0; i < ARRAY_SIZE(usbdevs); i++) {
2468
        if (strcmp(devname, usbdevs[i].name) != 0)
2469
            continue;
2470
        dev = usb_create_simple(bus, usbdevs[i].qdev);
2471
        goto done;
2472
    }
2473

    
2474
    /* the other ones */
2475
    if (strstart(devname, "host:", &p)) {
2476
        dev = usb_host_device_open(p);
2477
    } else if (strstart(devname, "disk:", &p)) {
2478
        BlockDriverState *bs;
2479

    
2480
        dev = usb_msd_init(p);
2481
        if (!dev)
2482
            return -1;
2483
        bs = usb_msd_get_bdrv(dev);
2484
        if (bdrv_key_required(bs)) {
2485
            autostart = 0;
2486
            if (is_hotplug) {
2487
                monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2488
                                            dev);
2489
                return 0;
2490
            }
2491
        }
2492
    } else if (strstart(devname, "serial:", &p)) {
2493
        dev = usb_serial_init(p);
2494
#ifdef CONFIG_BRLAPI
2495
    } else if (!strcmp(devname, "braille")) {
2496
        dev = usb_baum_init();
2497
#endif
2498
    } else if (strstart(devname, "net:", &p)) {
2499
        int nic = nb_nics;
2500

    
2501
        if (net_client_init(NULL, "nic", p) < 0)
2502
            return -1;
2503
        nd_table[nic].model = "usb";
2504
        dev = usb_net_init(&nd_table[nic]);
2505
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2506
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2507
                        bt_new_hci(qemu_find_bt_vlan(0)));
2508
    } else {
2509
        return -1;
2510
    }
2511
    if (!dev)
2512
        return -1;
2513

    
2514
done:
2515
    return 0;
2516
}
2517

    
2518
static int usb_device_del(const char *devname)
2519
{
2520
    int bus_num, addr;
2521
    const char *p;
2522

    
2523
    if (strstart(devname, "host:", &p))
2524
        return usb_host_device_close(p);
2525

    
2526
    if (!usb_enabled)
2527
        return -1;
2528

    
2529
    p = strchr(devname, '.');
2530
    if (!p)
2531
        return -1;
2532
    bus_num = strtoul(devname, NULL, 0);
2533
    addr = strtoul(p + 1, NULL, 0);
2534

    
2535
    return usb_device_delete_addr(bus_num, addr);
2536
}
2537

    
2538
static int usb_parse(const char *cmdline)
2539
{
2540
    return usb_device_add(cmdline, 0);
2541
}
2542

    
2543
void do_usb_add(Monitor *mon, const QDict *qdict)
2544
{
2545
    usb_device_add(qdict_get_str(qdict, "devname"), 1);
2546
}
2547

    
2548
void do_usb_del(Monitor *mon, const QDict *qdict)
2549
{
2550
    usb_device_del(qdict_get_str(qdict, "devname"));
2551
}
2552

    
2553
/***********************************************************/
2554
/* PCMCIA/Cardbus */
2555

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

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

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

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

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

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

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

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

    
2596
/***********************************************************/
2597
/* register display */
2598

    
2599
struct DisplayAllocator default_allocator = {
2600
    defaultallocator_create_displaysurface,
2601
    defaultallocator_resize_displaysurface,
2602
    defaultallocator_free_displaysurface
2603
};
2604

    
2605
void register_displaystate(DisplayState *ds)
2606
{
2607
    DisplayState **s;
2608
    s = &display_state;
2609
    while (*s != NULL)
2610
        s = &(*s)->next;
2611
    ds->next = NULL;
2612
    *s = ds;
2613
}
2614

    
2615
DisplayState *get_displaystate(void)
2616
{
2617
    return display_state;
2618
}
2619

    
2620
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2621
{
2622
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2623
    return ds->allocator;
2624
}
2625

    
2626
/* dumb display */
2627

    
2628
static void dumb_display_init(void)
2629
{
2630
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2631
    ds->allocator = &default_allocator;
2632
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2633
    register_displaystate(ds);
2634
}
2635

    
2636
/***********************************************************/
2637
/* I/O handling */
2638

    
2639
typedef struct IOHandlerRecord {
2640
    int fd;
2641
    IOCanRWHandler *fd_read_poll;
2642
    IOHandler *fd_read;
2643
    IOHandler *fd_write;
2644
    int deleted;
2645
    void *opaque;
2646
    /* temporary data */
2647
    struct pollfd *ufd;
2648
    struct IOHandlerRecord *next;
2649
} IOHandlerRecord;
2650

    
2651
static IOHandlerRecord *first_io_handler;
2652

    
2653
/* XXX: fd_read_poll should be suppressed, but an API change is
2654
   necessary in the character devices to suppress fd_can_read(). */
2655
int qemu_set_fd_handler2(int fd,
2656
                         IOCanRWHandler *fd_read_poll,
2657
                         IOHandler *fd_read,
2658
                         IOHandler *fd_write,
2659
                         void *opaque)
2660
{
2661
    IOHandlerRecord **pioh, *ioh;
2662

    
2663
    if (!fd_read && !fd_write) {
2664
        pioh = &first_io_handler;
2665
        for(;;) {
2666
            ioh = *pioh;
2667
            if (ioh == NULL)
2668
                break;
2669
            if (ioh->fd == fd) {
2670
                ioh->deleted = 1;
2671
                break;
2672
            }
2673
            pioh = &ioh->next;
2674
        }
2675
    } else {
2676
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2677
            if (ioh->fd == fd)
2678
                goto found;
2679
        }
2680
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2681
        ioh->next = first_io_handler;
2682
        first_io_handler = ioh;
2683
    found:
2684
        ioh->fd = fd;
2685
        ioh->fd_read_poll = fd_read_poll;
2686
        ioh->fd_read = fd_read;
2687
        ioh->fd_write = fd_write;
2688
        ioh->opaque = opaque;
2689
        ioh->deleted = 0;
2690
    }
2691
    return 0;
2692
}
2693

    
2694
int qemu_set_fd_handler(int fd,
2695
                        IOHandler *fd_read,
2696
                        IOHandler *fd_write,
2697
                        void *opaque)
2698
{
2699
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2700
}
2701

    
2702
#ifdef _WIN32
2703
/***********************************************************/
2704
/* Polling handling */
2705

    
2706
typedef struct PollingEntry {
2707
    PollingFunc *func;
2708
    void *opaque;
2709
    struct PollingEntry *next;
2710
} PollingEntry;
2711

    
2712
static PollingEntry *first_polling_entry;
2713

    
2714
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2715
{
2716
    PollingEntry **ppe, *pe;
2717
    pe = qemu_mallocz(sizeof(PollingEntry));
2718
    pe->func = func;
2719
    pe->opaque = opaque;
2720
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2721
    *ppe = pe;
2722
    return 0;
2723
}
2724

    
2725
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2726
{
2727
    PollingEntry **ppe, *pe;
2728
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2729
        pe = *ppe;
2730
        if (pe->func == func && pe->opaque == opaque) {
2731
            *ppe = pe->next;
2732
            qemu_free(pe);
2733
            break;
2734
        }
2735
    }
2736
}
2737

    
2738
/***********************************************************/
2739
/* Wait objects support */
2740
typedef struct WaitObjects {
2741
    int num;
2742
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2743
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2744
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2745
} WaitObjects;
2746

    
2747
static WaitObjects wait_objects = {0};
2748

    
2749
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2750
{
2751
    WaitObjects *w = &wait_objects;
2752

    
2753
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2754
        return -1;
2755
    w->events[w->num] = handle;
2756
    w->func[w->num] = func;
2757
    w->opaque[w->num] = opaque;
2758
    w->num++;
2759
    return 0;
2760
}
2761

    
2762
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2763
{
2764
    int i, found;
2765
    WaitObjects *w = &wait_objects;
2766

    
2767
    found = 0;
2768
    for (i = 0; i < w->num; i++) {
2769
        if (w->events[i] == handle)
2770
            found = 1;
2771
        if (found) {
2772
            w->events[i] = w->events[i + 1];
2773
            w->func[i] = w->func[i + 1];
2774
            w->opaque[i] = w->opaque[i + 1];
2775
        }
2776
    }
2777
    if (found)
2778
        w->num--;
2779
}
2780
#endif
2781

    
2782
/***********************************************************/
2783
/* ram save/restore */
2784

    
2785
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2786
#define RAM_SAVE_FLAG_COMPRESS        0x02
2787
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2788
#define RAM_SAVE_FLAG_PAGE        0x08
2789
#define RAM_SAVE_FLAG_EOS        0x10
2790

    
2791
static int is_dup_page(uint8_t *page, uint8_t ch)
2792
{
2793
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2794
    uint32_t *array = (uint32_t *)page;
2795
    int i;
2796

    
2797
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2798
        if (array[i] != val)
2799
            return 0;
2800
    }
2801

    
2802
    return 1;
2803
}
2804

    
2805
static int ram_save_block(QEMUFile *f)
2806
{
2807
    static ram_addr_t current_addr = 0;
2808
    ram_addr_t saved_addr = current_addr;
2809
    ram_addr_t addr = 0;
2810
    int found = 0;
2811

    
2812
    while (addr < last_ram_offset) {
2813
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2814
            uint8_t *p;
2815

    
2816
            cpu_physical_memory_reset_dirty(current_addr,
2817
                                            current_addr + TARGET_PAGE_SIZE,
2818
                                            MIGRATION_DIRTY_FLAG);
2819

    
2820
            p = qemu_get_ram_ptr(current_addr);
2821

    
2822
            if (is_dup_page(p, *p)) {
2823
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2824
                qemu_put_byte(f, *p);
2825
            } else {
2826
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2827
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2828
            }
2829

    
2830
            found = 1;
2831
            break;
2832
        }
2833
        addr += TARGET_PAGE_SIZE;
2834
        current_addr = (saved_addr + addr) % last_ram_offset;
2835
    }
2836

    
2837
    return found;
2838
}
2839

    
2840
static uint64_t bytes_transferred = 0;
2841

    
2842
static ram_addr_t ram_save_remaining(void)
2843
{
2844
    ram_addr_t addr;
2845
    ram_addr_t count = 0;
2846

    
2847
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2848
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2849
            count++;
2850
    }
2851

    
2852
    return count;
2853
}
2854

    
2855
uint64_t ram_bytes_remaining(void)
2856
{
2857
    return ram_save_remaining() * TARGET_PAGE_SIZE;
2858
}
2859

    
2860
uint64_t ram_bytes_transferred(void)
2861
{
2862
    return bytes_transferred;
2863
}
2864

    
2865
uint64_t ram_bytes_total(void)
2866
{
2867
    return last_ram_offset;
2868
}
2869

    
2870
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
2871
{
2872
    ram_addr_t addr;
2873
    uint64_t bytes_transferred_last;
2874
    double bwidth = 0;
2875
    uint64_t expected_time = 0;
2876

    
2877
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
2878
        qemu_file_set_error(f);
2879
        return 0;
2880
    }
2881

    
2882
    if (stage == 1) {
2883
        /* Make sure all dirty bits are set */
2884
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
2885
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
2886
                cpu_physical_memory_set_dirty(addr);
2887
        }
2888

    
2889
        /* Enable dirty memory tracking */
2890
        cpu_physical_memory_set_dirty_tracking(1);
2891

    
2892
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
2893
    }
2894

    
2895
    bytes_transferred_last = bytes_transferred;
2896
    bwidth = get_clock();
2897

    
2898
    while (!qemu_file_rate_limit(f)) {
2899
        int ret;
2900

    
2901
        ret = ram_save_block(f);
2902
        bytes_transferred += ret * TARGET_PAGE_SIZE;
2903
        if (ret == 0) /* no more blocks */
2904
            break;
2905
    }
2906

    
2907
    bwidth = get_clock() - bwidth;
2908
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
2909

    
2910
    /* if we haven't transferred anything this round, force expected_time to a
2911
     * a very high value, but without crashing */
2912
    if (bwidth == 0)
2913
        bwidth = 0.000001;
2914

    
2915
    /* try transferring iterative blocks of memory */
2916

    
2917
    if (stage == 3) {
2918

    
2919
        /* flush all remaining blocks regardless of rate limiting */
2920
        while (ram_save_block(f) != 0) {
2921
            bytes_transferred += TARGET_PAGE_SIZE;
2922
        }
2923
        cpu_physical_memory_set_dirty_tracking(0);
2924
    }
2925

    
2926
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2927

    
2928
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
2929

    
2930
    return (stage == 2) && (expected_time <= migrate_max_downtime());
2931
}
2932

    
2933
static int ram_load(QEMUFile *f, void *opaque, int version_id)
2934
{
2935
    ram_addr_t addr;
2936
    int flags;
2937

    
2938
    if (version_id != 3)
2939
        return -EINVAL;
2940

    
2941
    do {
2942
        addr = qemu_get_be64(f);
2943

    
2944
        flags = addr & ~TARGET_PAGE_MASK;
2945
        addr &= TARGET_PAGE_MASK;
2946

    
2947
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
2948
            if (addr != last_ram_offset)
2949
                return -EINVAL;
2950
        }
2951

    
2952
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
2953
            uint8_t ch = qemu_get_byte(f);
2954
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
2955
#ifndef _WIN32
2956
            if (ch == 0 &&
2957
                (!kvm_enabled() || kvm_has_sync_mmu())) {
2958
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
2959
            }
2960
#endif
2961
        } else if (flags & RAM_SAVE_FLAG_PAGE)
2962
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
2963
    } while (!(flags & RAM_SAVE_FLAG_EOS));
2964

    
2965
    return 0;
2966
}
2967

    
2968
void qemu_service_io(void)
2969
{
2970
    qemu_notify_event();
2971
}
2972

    
2973
/***********************************************************/
2974
/* bottom halves (can be seen as timers which expire ASAP) */
2975

    
2976
struct QEMUBH {
2977
    QEMUBHFunc *cb;
2978
    void *opaque;
2979
    int scheduled;
2980
    int idle;
2981
    int deleted;
2982
    QEMUBH *next;
2983
};
2984

    
2985
static QEMUBH *first_bh = NULL;
2986

    
2987
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
2988
{
2989
    QEMUBH *bh;
2990
    bh = qemu_mallocz(sizeof(QEMUBH));
2991
    bh->cb = cb;
2992
    bh->opaque = opaque;
2993
    bh->next = first_bh;
2994
    first_bh = bh;
2995
    return bh;
2996
}
2997

    
2998
int qemu_bh_poll(void)
2999
{
3000
    QEMUBH *bh, **bhp;
3001
    int ret;
3002

    
3003
    ret = 0;
3004
    for (bh = first_bh; bh; bh = bh->next) {
3005
        if (!bh->deleted && bh->scheduled) {
3006
            bh->scheduled = 0;
3007
            if (!bh->idle)
3008
                ret = 1;
3009
            bh->idle = 0;
3010
            bh->cb(bh->opaque);
3011
        }
3012
    }
3013

    
3014
    /* remove deleted bhs */
3015
    bhp = &first_bh;
3016
    while (*bhp) {
3017
        bh = *bhp;
3018
        if (bh->deleted) {
3019
            *bhp = bh->next;
3020
            qemu_free(bh);
3021
        } else
3022
            bhp = &bh->next;
3023
    }
3024

    
3025
    return ret;
3026
}
3027

    
3028
void qemu_bh_schedule_idle(QEMUBH *bh)
3029
{
3030
    if (bh->scheduled)
3031
        return;
3032
    bh->scheduled = 1;
3033
    bh->idle = 1;
3034
}
3035

    
3036
void qemu_bh_schedule(QEMUBH *bh)
3037
{
3038
    if (bh->scheduled)
3039
        return;
3040
    bh->scheduled = 1;
3041
    bh->idle = 0;
3042
    /* stop the currently executing CPU to execute the BH ASAP */
3043
    qemu_notify_event();
3044
}
3045

    
3046
void qemu_bh_cancel(QEMUBH *bh)
3047
{
3048
    bh->scheduled = 0;
3049
}
3050

    
3051
void qemu_bh_delete(QEMUBH *bh)
3052
{
3053
    bh->scheduled = 0;
3054
    bh->deleted = 1;
3055
}
3056

    
3057
static void qemu_bh_update_timeout(int *timeout)
3058
{
3059
    QEMUBH *bh;
3060

    
3061
    for (bh = first_bh; bh; bh = bh->next) {
3062
        if (!bh->deleted && bh->scheduled) {
3063
            if (bh->idle) {
3064
                /* idle bottom halves will be polled at least
3065
                 * every 10ms */
3066
                *timeout = MIN(10, *timeout);
3067
            } else {
3068
                /* non-idle bottom halves will be executed
3069
                 * immediately */
3070
                *timeout = 0;
3071
                break;
3072
            }
3073
        }
3074
    }
3075
}
3076

    
3077
/***********************************************************/
3078
/* machine registration */
3079

    
3080
static QEMUMachine *first_machine = NULL;
3081
QEMUMachine *current_machine = NULL;
3082

    
3083
int qemu_register_machine(QEMUMachine *m)
3084
{
3085
    QEMUMachine **pm;
3086
    pm = &first_machine;
3087
    while (*pm != NULL)
3088
        pm = &(*pm)->next;
3089
    m->next = NULL;
3090
    *pm = m;
3091
    return 0;
3092
}
3093

    
3094
static QEMUMachine *find_machine(const char *name)
3095
{
3096
    QEMUMachine *m;
3097

    
3098
    for(m = first_machine; m != NULL; m = m->next) {
3099
        if (!strcmp(m->name, name))
3100
            return m;
3101
        if (m->alias && !strcmp(m->alias, name))
3102
            return m;
3103
    }
3104
    return NULL;
3105
}
3106

    
3107
static QEMUMachine *find_default_machine(void)
3108
{
3109
    QEMUMachine *m;
3110

    
3111
    for(m = first_machine; m != NULL; m = m->next) {
3112
        if (m->is_default) {
3113
            return m;
3114
        }
3115
    }
3116
    return NULL;
3117
}
3118

    
3119
/***********************************************************/
3120
/* main execution loop */
3121

    
3122
static void gui_update(void *opaque)
3123
{
3124
    uint64_t interval = GUI_REFRESH_INTERVAL;
3125
    DisplayState *ds = opaque;
3126
    DisplayChangeListener *dcl = ds->listeners;
3127

    
3128
    dpy_refresh(ds);
3129

    
3130
    while (dcl != NULL) {
3131
        if (dcl->gui_timer_interval &&
3132
            dcl->gui_timer_interval < interval)
3133
            interval = dcl->gui_timer_interval;
3134
        dcl = dcl->next;
3135
    }
3136
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3137
}
3138

    
3139
static void nographic_update(void *opaque)
3140
{
3141
    uint64_t interval = GUI_REFRESH_INTERVAL;
3142

    
3143
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3144
}
3145

    
3146
struct vm_change_state_entry {
3147
    VMChangeStateHandler *cb;
3148
    void *opaque;
3149
    QLIST_ENTRY (vm_change_state_entry) entries;
3150
};
3151

    
3152
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3153

    
3154
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3155
                                                     void *opaque)
3156
{
3157
    VMChangeStateEntry *e;
3158

    
3159
    e = qemu_mallocz(sizeof (*e));
3160

    
3161
    e->cb = cb;
3162
    e->opaque = opaque;
3163
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3164
    return e;
3165
}
3166

    
3167
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3168
{
3169
    QLIST_REMOVE (e, entries);
3170
    qemu_free (e);
3171
}
3172

    
3173
static void vm_state_notify(int running, int reason)
3174
{
3175
    VMChangeStateEntry *e;
3176

    
3177
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3178
        e->cb(e->opaque, running, reason);
3179
    }
3180
}
3181

    
3182
static void resume_all_vcpus(void);
3183
static void pause_all_vcpus(void);
3184

    
3185
void vm_start(void)
3186
{
3187
    if (!vm_running) {
3188
        cpu_enable_ticks();
3189
        vm_running = 1;
3190
        vm_state_notify(1, 0);
3191
        qemu_rearm_alarm_timer(alarm_timer);
3192
        resume_all_vcpus();
3193
    }
3194
}
3195

    
3196
/* reset/shutdown handler */
3197

    
3198
typedef struct QEMUResetEntry {
3199
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3200
    QEMUResetHandler *func;
3201
    void *opaque;
3202
} QEMUResetEntry;
3203

    
3204
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3205
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3206
static int reset_requested;
3207
static int shutdown_requested;
3208
static int powerdown_requested;
3209
static int debug_requested;
3210
static int vmstop_requested;
3211

    
3212
int qemu_shutdown_requested(void)
3213
{
3214
    int r = shutdown_requested;
3215
    shutdown_requested = 0;
3216
    return r;
3217
}
3218

    
3219
int qemu_reset_requested(void)
3220
{
3221
    int r = reset_requested;
3222
    reset_requested = 0;
3223
    return r;
3224
}
3225

    
3226
int qemu_powerdown_requested(void)
3227
{
3228
    int r = powerdown_requested;
3229
    powerdown_requested = 0;
3230
    return r;
3231
}
3232

    
3233
static int qemu_debug_requested(void)
3234
{
3235
    int r = debug_requested;
3236
    debug_requested = 0;
3237
    return r;
3238
}
3239

    
3240
static int qemu_vmstop_requested(void)
3241
{
3242
    int r = vmstop_requested;
3243
    vmstop_requested = 0;
3244
    return r;
3245
}
3246

    
3247
static void do_vm_stop(int reason)
3248
{
3249
    if (vm_running) {
3250
        cpu_disable_ticks();
3251
        vm_running = 0;
3252
        pause_all_vcpus();
3253
        vm_state_notify(0, reason);
3254
    }
3255
}
3256

    
3257
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3258
{
3259
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3260

    
3261
    re->func = func;
3262
    re->opaque = opaque;
3263
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3264
}
3265

    
3266
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3267
{
3268
    QEMUResetEntry *re;
3269

    
3270
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3271
        if (re->func == func && re->opaque == opaque) {
3272
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3273
            qemu_free(re);
3274
            return;
3275
        }
3276
    }
3277
}
3278

    
3279
void qemu_system_reset(void)
3280
{
3281
    QEMUResetEntry *re, *nre;
3282

    
3283
    /* reset all devices */
3284
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3285
        re->func(re->opaque);
3286
    }
3287
}
3288

    
3289
void qemu_system_reset_request(void)
3290
{
3291
    if (no_reboot) {
3292
        shutdown_requested = 1;
3293
    } else {
3294
        reset_requested = 1;
3295
    }
3296
    qemu_notify_event();
3297
}
3298

    
3299
void qemu_system_shutdown_request(void)
3300
{
3301
    shutdown_requested = 1;
3302
    qemu_notify_event();
3303
}
3304

    
3305
void qemu_system_powerdown_request(void)
3306
{
3307
    powerdown_requested = 1;
3308
    qemu_notify_event();
3309
}
3310

    
3311
#ifdef CONFIG_IOTHREAD
3312
static void qemu_system_vmstop_request(int reason)
3313
{
3314
    vmstop_requested = reason;
3315
    qemu_notify_event();
3316
}
3317
#endif
3318

    
3319
#ifndef _WIN32
3320
static int io_thread_fd = -1;
3321

    
3322
static void qemu_event_increment(void)
3323
{
3324
    static const char byte = 0;
3325

    
3326
    if (io_thread_fd == -1)
3327
        return;
3328

    
3329
    write(io_thread_fd, &byte, sizeof(byte));
3330
}
3331

    
3332
static void qemu_event_read(void *opaque)
3333
{
3334
    int fd = (unsigned long)opaque;
3335
    ssize_t len;
3336

    
3337
    /* Drain the notify pipe */
3338
    do {
3339
        char buffer[512];
3340
        len = read(fd, buffer, sizeof(buffer));
3341
    } while ((len == -1 && errno == EINTR) || len > 0);
3342
}
3343

    
3344
static int qemu_event_init(void)
3345
{
3346
    int err;
3347
    int fds[2];
3348

    
3349
    err = pipe(fds);
3350
    if (err == -1)
3351
        return -errno;
3352

    
3353
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3354
    if (err < 0)
3355
        goto fail;
3356

    
3357
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3358
    if (err < 0)
3359
        goto fail;
3360

    
3361
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3362
                         (void *)(unsigned long)fds[0]);
3363

    
3364
    io_thread_fd = fds[1];
3365
    return 0;
3366

    
3367
fail:
3368
    close(fds[0]);
3369
    close(fds[1]);
3370
    return err;
3371
}
3372
#else
3373
HANDLE qemu_event_handle;
3374

    
3375
static void dummy_event_handler(void *opaque)
3376
{
3377
}
3378

    
3379
static int qemu_event_init(void)
3380
{
3381
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3382
    if (!qemu_event_handle) {
3383
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3384
        return -1;
3385
    }
3386
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3387
    return 0;
3388
}
3389

    
3390
static void qemu_event_increment(void)
3391
{
3392
    if (!SetEvent(qemu_event_handle)) {
3393
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3394
                GetLastError());
3395
        exit (1);
3396
    }
3397
}
3398
#endif
3399

    
3400
static int cpu_can_run(CPUState *env)
3401
{
3402
    if (env->stop)
3403
        return 0;
3404
    if (env->stopped)
3405
        return 0;
3406
    return 1;
3407
}
3408

    
3409
#ifndef CONFIG_IOTHREAD
3410
static int qemu_init_main_loop(void)
3411
{
3412
    return qemu_event_init();
3413
}
3414

    
3415
void qemu_init_vcpu(void *_env)
3416
{
3417
    CPUState *env = _env;
3418

    
3419
    if (kvm_enabled())
3420
        kvm_init_vcpu(env);
3421
    env->nr_cores = smp_cores;
3422
    env->nr_threads = smp_threads;
3423
    return;
3424
}
3425

    
3426
int qemu_cpu_self(void *env)
3427
{
3428
    return 1;
3429
}
3430

    
3431
static void resume_all_vcpus(void)
3432
{
3433
}
3434

    
3435
static void pause_all_vcpus(void)
3436
{
3437
}
3438

    
3439
void qemu_cpu_kick(void *env)
3440
{
3441
    return;
3442
}
3443

    
3444
void qemu_notify_event(void)
3445
{
3446
    CPUState *env = cpu_single_env;
3447

    
3448
    if (env) {
3449
        cpu_exit(env);
3450
    }
3451
}
3452

    
3453
#define qemu_mutex_lock_iothread() do { } while (0)
3454
#define qemu_mutex_unlock_iothread() do { } while (0)
3455

    
3456
void vm_stop(int reason)
3457
{
3458
    do_vm_stop(reason);
3459
}
3460

    
3461
#else /* CONFIG_IOTHREAD */
3462

    
3463
#include "qemu-thread.h"
3464

    
3465
QemuMutex qemu_global_mutex;
3466
static QemuMutex qemu_fair_mutex;
3467

    
3468
static QemuThread io_thread;
3469

    
3470
static QemuThread *tcg_cpu_thread;
3471
static QemuCond *tcg_halt_cond;
3472

    
3473
static int qemu_system_ready;
3474
/* cpu creation */
3475
static QemuCond qemu_cpu_cond;
3476
/* system init */
3477
static QemuCond qemu_system_cond;
3478
static QemuCond qemu_pause_cond;
3479

    
3480
static void block_io_signals(void);
3481
static void unblock_io_signals(void);
3482
static int tcg_has_work(void);
3483

    
3484
static int qemu_init_main_loop(void)
3485
{
3486
    int ret;
3487

    
3488
    ret = qemu_event_init();
3489
    if (ret)
3490
        return ret;
3491

    
3492
    qemu_cond_init(&qemu_pause_cond);
3493
    qemu_mutex_init(&qemu_fair_mutex);
3494
    qemu_mutex_init(&qemu_global_mutex);
3495
    qemu_mutex_lock(&qemu_global_mutex);
3496

    
3497
    unblock_io_signals();
3498
    qemu_thread_self(&io_thread);
3499

    
3500
    return 0;
3501
}
3502

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

    
3508
    qemu_mutex_unlock(&qemu_global_mutex);
3509

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

    
3518
    qemu_mutex_lock(&qemu_global_mutex);
3519
    if (env->stop) {
3520
        env->stop = 0;
3521
        env->stopped = 1;
3522
        qemu_cond_signal(&qemu_pause_cond);
3523
    }
3524
}
3525

    
3526
static int qemu_cpu_exec(CPUState *env);
3527

    
3528
static void *kvm_cpu_thread_fn(void *arg)
3529
{
3530
    CPUState *env = arg;
3531

    
3532
    block_io_signals();
3533
    qemu_thread_self(env->thread);
3534
    if (kvm_enabled())
3535
        kvm_init_vcpu(env);
3536

    
3537
    /* signal CPU creation */
3538
    qemu_mutex_lock(&qemu_global_mutex);
3539
    env->created = 1;
3540
    qemu_cond_signal(&qemu_cpu_cond);
3541

    
3542
    /* and wait for machine initialization */
3543
    while (!qemu_system_ready)
3544
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3545

    
3546
    while (1) {
3547
        if (cpu_can_run(env))
3548
            qemu_cpu_exec(env);
3549
        qemu_wait_io_event(env);
3550
    }
3551

    
3552
    return NULL;
3553
}
3554

    
3555
static void tcg_cpu_exec(void);
3556

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

    
3561
    block_io_signals();
3562
    qemu_thread_self(env->thread);
3563

    
3564
    /* signal CPU creation */
3565
    qemu_mutex_lock(&qemu_global_mutex);
3566
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3567
        env->created = 1;
3568
    qemu_cond_signal(&qemu_cpu_cond);
3569

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

    
3574
    while (1) {
3575
        tcg_cpu_exec();
3576
        qemu_wait_io_event(cur_cpu);
3577
    }
3578

    
3579
    return NULL;
3580
}
3581

    
3582
void qemu_cpu_kick(void *_env)
3583
{
3584
    CPUState *env = _env;
3585
    qemu_cond_broadcast(env->halt_cond);
3586
    if (kvm_enabled())
3587
        qemu_thread_signal(env->thread, SIGUSR1);
3588
}
3589

    
3590
int qemu_cpu_self(void *_env)
3591
{
3592
    CPUState *env = _env;
3593
    QemuThread this;
3594
 
3595
    qemu_thread_self(&this);
3596
 
3597
    return qemu_thread_equal(&this, env->thread);
3598
}
3599

    
3600
static void cpu_signal(int sig)
3601
{
3602
    if (cpu_single_env)
3603
        cpu_exit(cpu_single_env);
3604
}
3605

    
3606
static void block_io_signals(void)
3607
{
3608
    sigset_t set;
3609
    struct sigaction sigact;
3610

    
3611
    sigemptyset(&set);
3612
    sigaddset(&set, SIGUSR2);
3613
    sigaddset(&set, SIGIO);
3614
    sigaddset(&set, SIGALRM);
3615
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3616

    
3617
    sigemptyset(&set);
3618
    sigaddset(&set, SIGUSR1);
3619
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3620

    
3621
    memset(&sigact, 0, sizeof(sigact));
3622
    sigact.sa_handler = cpu_signal;
3623
    sigaction(SIGUSR1, &sigact, NULL);
3624
}
3625

    
3626
static void unblock_io_signals(void)
3627
{
3628
    sigset_t set;
3629

    
3630
    sigemptyset(&set);
3631
    sigaddset(&set, SIGUSR2);
3632
    sigaddset(&set, SIGIO);
3633
    sigaddset(&set, SIGALRM);
3634
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3635

    
3636
    sigemptyset(&set);
3637
    sigaddset(&set, SIGUSR1);
3638
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3639
}
3640

    
3641
static void qemu_signal_lock(unsigned int msecs)
3642
{
3643
    qemu_mutex_lock(&qemu_fair_mutex);
3644

    
3645
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3646
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3647
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3648
            break;
3649
    }
3650
    qemu_mutex_unlock(&qemu_fair_mutex);
3651
}
3652

    
3653
static void qemu_mutex_lock_iothread(void)
3654
{
3655
    if (kvm_enabled()) {
3656
        qemu_mutex_lock(&qemu_fair_mutex);
3657
        qemu_mutex_lock(&qemu_global_mutex);
3658
        qemu_mutex_unlock(&qemu_fair_mutex);
3659
    } else
3660
        qemu_signal_lock(100);
3661
}
3662

    
3663
static void qemu_mutex_unlock_iothread(void)
3664
{
3665
    qemu_mutex_unlock(&qemu_global_mutex);
3666
}
3667

    
3668
static int all_vcpus_paused(void)
3669
{
3670
    CPUState *penv = first_cpu;
3671

    
3672
    while (penv) {
3673
        if (!penv->stopped)
3674
            return 0;
3675
        penv = (CPUState *)penv->next_cpu;
3676
    }
3677

    
3678
    return 1;
3679
}
3680

    
3681
static void pause_all_vcpus(void)
3682
{
3683
    CPUState *penv = first_cpu;
3684

    
3685
    while (penv) {
3686
        penv->stop = 1;
3687
        qemu_thread_signal(penv->thread, SIGUSR1);
3688
        qemu_cpu_kick(penv);
3689
        penv = (CPUState *)penv->next_cpu;
3690
    }
3691

    
3692
    while (!all_vcpus_paused()) {
3693
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3694
        penv = first_cpu;
3695
        while (penv) {
3696
            qemu_thread_signal(penv->thread, SIGUSR1);
3697
            penv = (CPUState *)penv->next_cpu;
3698
        }
3699
    }
3700
}
3701

    
3702
static void resume_all_vcpus(void)
3703
{
3704
    CPUState *penv = first_cpu;
3705

    
3706
    while (penv) {
3707
        penv->stop = 0;
3708
        penv->stopped = 0;
3709
        qemu_thread_signal(penv->thread, SIGUSR1);
3710
        qemu_cpu_kick(penv);
3711
        penv = (CPUState *)penv->next_cpu;
3712
    }
3713
}
3714

    
3715
static void tcg_init_vcpu(void *_env)
3716
{
3717
    CPUState *env = _env;
3718
    /* share a single thread for all cpus with TCG */
3719
    if (!tcg_cpu_thread) {
3720
        env->thread = qemu_mallocz(sizeof(QemuThread));
3721
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3722
        qemu_cond_init(env->halt_cond);
3723
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3724
        while (env->created == 0)
3725
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3726
        tcg_cpu_thread = env->thread;
3727
        tcg_halt_cond = env->halt_cond;
3728
    } else {
3729
        env->thread = tcg_cpu_thread;
3730
        env->halt_cond = tcg_halt_cond;
3731
    }
3732
}
3733

    
3734
static void kvm_start_vcpu(CPUState *env)
3735
{
3736
    env->thread = qemu_mallocz(sizeof(QemuThread));
3737
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3738
    qemu_cond_init(env->halt_cond);
3739
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3740
    while (env->created == 0)
3741
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3742
}
3743

    
3744
void qemu_init_vcpu(void *_env)
3745
{
3746
    CPUState *env = _env;
3747

    
3748
    if (kvm_enabled())
3749
        kvm_start_vcpu(env);
3750
    else
3751
        tcg_init_vcpu(env);
3752
    env->nr_cores = smp_cores;
3753
    env->nr_threads = smp_threads;
3754
}
3755

    
3756
void qemu_notify_event(void)
3757
{
3758
    qemu_event_increment();
3759
}
3760

    
3761
void vm_stop(int reason)
3762
{
3763
    QemuThread me;
3764
    qemu_thread_self(&me);
3765

    
3766
    if (!qemu_thread_equal(&me, &io_thread)) {
3767
        qemu_system_vmstop_request(reason);
3768
        /*
3769
         * FIXME: should not return to device code in case
3770
         * vm_stop() has been requested.
3771
         */
3772
        if (cpu_single_env) {
3773
            cpu_exit(cpu_single_env);
3774
            cpu_single_env->stop = 1;
3775
        }
3776
        return;
3777
    }
3778
    do_vm_stop(reason);
3779
}
3780

    
3781
#endif
3782

    
3783

    
3784
#ifdef _WIN32
3785
static void host_main_loop_wait(int *timeout)
3786
{
3787
    int ret, ret2, i;
3788
    PollingEntry *pe;
3789

    
3790

    
3791
    /* XXX: need to suppress polling by better using win32 events */
3792
    ret = 0;
3793
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3794
        ret |= pe->func(pe->opaque);
3795
    }
3796
    if (ret == 0) {
3797
        int err;
3798
        WaitObjects *w = &wait_objects;
3799

    
3800
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3801
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3802
            if (w->func[ret - WAIT_OBJECT_0])
3803
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3804

    
3805
            /* Check for additional signaled events */
3806
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3807

    
3808
                /* Check if event is signaled */
3809
                ret2 = WaitForSingleObject(w->events[i], 0);
3810
                if(ret2 == WAIT_OBJECT_0) {
3811
                    if (w->func[i])
3812
                        w->func[i](w->opaque[i]);
3813
                } else if (ret2 == WAIT_TIMEOUT) {
3814
                } else {
3815
                    err = GetLastError();
3816
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3817
                }
3818
            }
3819
        } else if (ret == WAIT_TIMEOUT) {
3820
        } else {
3821
            err = GetLastError();
3822
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3823
        }
3824
    }
3825

    
3826
    *timeout = 0;
3827
}
3828
#else
3829
static void host_main_loop_wait(int *timeout)
3830
{
3831
}
3832
#endif
3833

    
3834
void main_loop_wait(int timeout)
3835
{
3836
    IOHandlerRecord *ioh;
3837
    fd_set rfds, wfds, xfds;
3838
    int ret, nfds;
3839
    struct timeval tv;
3840

    
3841
    qemu_bh_update_timeout(&timeout);
3842

    
3843
    host_main_loop_wait(&timeout);
3844

    
3845
    /* poll any events */
3846
    /* XXX: separate device handlers from system ones */
3847
    nfds = -1;
3848
    FD_ZERO(&rfds);
3849
    FD_ZERO(&wfds);
3850
    FD_ZERO(&xfds);
3851
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3852
        if (ioh->deleted)
3853
            continue;
3854
        if (ioh->fd_read &&
3855
            (!ioh->fd_read_poll ||
3856
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3857
            FD_SET(ioh->fd, &rfds);
3858
            if (ioh->fd > nfds)
3859
                nfds = ioh->fd;
3860
        }
3861
        if (ioh->fd_write) {
3862
            FD_SET(ioh->fd, &wfds);
3863
            if (ioh->fd > nfds)
3864
                nfds = ioh->fd;
3865
        }
3866
    }
3867

    
3868
    tv.tv_sec = timeout / 1000;
3869
    tv.tv_usec = (timeout % 1000) * 1000;
3870

    
3871
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3872

    
3873
    qemu_mutex_unlock_iothread();
3874
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3875
    qemu_mutex_lock_iothread();
3876
    if (ret > 0) {
3877
        IOHandlerRecord **pioh;
3878

    
3879
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3880
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3881
                ioh->fd_read(ioh->opaque);
3882
            }
3883
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3884
                ioh->fd_write(ioh->opaque);
3885
            }
3886
        }
3887

    
3888
        /* remove deleted IO handlers */
3889
        pioh = &first_io_handler;
3890
        while (*pioh) {
3891
            ioh = *pioh;
3892
            if (ioh->deleted) {
3893
                *pioh = ioh->next;
3894
                qemu_free(ioh);
3895
            } else
3896
                pioh = &ioh->next;
3897
        }
3898
    }
3899

    
3900
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3901

    
3902
    /* rearm timer, if not periodic */
3903
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3904
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3905
        qemu_rearm_alarm_timer(alarm_timer);
3906
    }
3907

    
3908
    /* vm time timers */
3909
    if (vm_running) {
3910
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3911
            qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3912
                            qemu_get_clock(vm_clock));
3913
    }
3914

    
3915
    /* real time timers */
3916
    qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3917
                    qemu_get_clock(rt_clock));
3918

    
3919
    /* Check bottom-halves last in case any of the earlier events triggered
3920
       them.  */
3921
    qemu_bh_poll();
3922

    
3923
}
3924

    
3925
static int qemu_cpu_exec(CPUState *env)
3926
{
3927
    int ret;
3928
#ifdef CONFIG_PROFILER
3929
    int64_t ti;
3930
#endif
3931

    
3932
#ifdef CONFIG_PROFILER
3933
    ti = profile_getclock();
3934
#endif
3935
    if (use_icount) {
3936
        int64_t count;
3937
        int decr;
3938
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3939
        env->icount_decr.u16.low = 0;
3940
        env->icount_extra = 0;
3941
        count = qemu_next_deadline();
3942
        count = (count + (1 << icount_time_shift) - 1)
3943
                >> icount_time_shift;
3944
        qemu_icount += count;
3945
        decr = (count > 0xffff) ? 0xffff : count;
3946
        count -= decr;
3947
        env->icount_decr.u16.low = decr;
3948
        env->icount_extra = count;
3949
    }
3950
    ret = cpu_exec(env);
3951
#ifdef CONFIG_PROFILER
3952
    qemu_time += profile_getclock() - ti;
3953
#endif
3954
    if (use_icount) {
3955
        /* Fold pending instructions back into the
3956
           instruction counter, and clear the interrupt flag.  */
3957
        qemu_icount -= (env->icount_decr.u16.low
3958
                        + env->icount_extra);
3959
        env->icount_decr.u32 = 0;
3960
        env->icount_extra = 0;
3961
    }
3962
    return ret;
3963
}
3964

    
3965
static void tcg_cpu_exec(void)
3966
{
3967
    int ret = 0;
3968

    
3969
    if (next_cpu == NULL)
3970
        next_cpu = first_cpu;
3971
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3972
        CPUState *env = cur_cpu = next_cpu;
3973

    
3974
        if (!vm_running)
3975
            break;
3976
        if (timer_alarm_pending) {
3977
            timer_alarm_pending = 0;
3978
            break;
3979
        }
3980
        if (cpu_can_run(env))
3981
            ret = qemu_cpu_exec(env);
3982
        if (ret == EXCP_DEBUG) {
3983
            gdb_set_stop_cpu(env);
3984
            debug_requested = 1;
3985
            break;
3986
        }
3987
    }
3988
}
3989

    
3990
static int cpu_has_work(CPUState *env)
3991
{
3992
    if (env->stop)
3993
        return 1;
3994
    if (env->stopped)
3995
        return 0;
3996
    if (!env->halted)
3997
        return 1;
3998
    if (qemu_cpu_has_work(env))
3999
        return 1;
4000
    return 0;
4001
}
4002

    
4003
static int tcg_has_work(void)
4004
{
4005
    CPUState *env;
4006

    
4007
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4008
        if (cpu_has_work(env))
4009
            return 1;
4010
    return 0;
4011
}
4012

    
4013
static int qemu_calculate_timeout(void)
4014
{
4015
#ifndef CONFIG_IOTHREAD
4016
    int timeout;
4017

    
4018
    if (!vm_running)
4019
        timeout = 5000;
4020
    else if (tcg_has_work())
4021
        timeout = 0;
4022
    else if (!use_icount)
4023
        timeout = 5000;
4024
    else {
4025
     /* XXX: use timeout computed from timers */
4026
        int64_t add;
4027
        int64_t delta;
4028
        /* Advance virtual time to the next event.  */
4029
        if (use_icount == 1) {
4030
            /* When not using an adaptive execution frequency
4031
               we tend to get badly out of sync with real time,
4032
               so just delay for a reasonable amount of time.  */
4033
            delta = 0;
4034
        } else {
4035
            delta = cpu_get_icount() - cpu_get_clock();
4036
        }
4037
        if (delta > 0) {
4038
            /* If virtual time is ahead of real time then just
4039
               wait for IO.  */
4040
            timeout = (delta / 1000000) + 1;
4041
        } else {
4042
            /* Wait for either IO to occur or the next
4043
               timer event.  */
4044
            add = qemu_next_deadline();
4045
            /* We advance the timer before checking for IO.
4046
               Limit the amount we advance so that early IO
4047
               activity won't get the guest too far ahead.  */
4048
            if (add > 10000000)
4049
                add = 10000000;
4050
            delta += add;
4051
            add = (add + (1 << icount_time_shift) - 1)
4052
                  >> icount_time_shift;
4053
            qemu_icount += add;
4054
            timeout = delta / 1000000;
4055
            if (timeout < 0)
4056
                timeout = 0;
4057
        }
4058
    }
4059

    
4060
    return timeout;
4061
#else /* CONFIG_IOTHREAD */
4062
    return 1000;
4063
#endif
4064
}
4065

    
4066
static int vm_can_run(void)
4067
{
4068
    if (powerdown_requested)
4069
        return 0;
4070
    if (reset_requested)
4071
        return 0;
4072
    if (shutdown_requested)
4073
        return 0;
4074
    if (debug_requested)
4075
        return 0;
4076
    return 1;
4077
}
4078

    
4079
qemu_irq qemu_system_powerdown;
4080

    
4081
static void main_loop(void)
4082
{
4083
    int r;
4084

    
4085
#ifdef CONFIG_IOTHREAD
4086
    qemu_system_ready = 1;
4087
    qemu_cond_broadcast(&qemu_system_cond);
4088
#endif
4089

    
4090
    for (;;) {
4091
        do {
4092
#ifdef CONFIG_PROFILER
4093
            int64_t ti;
4094
#endif
4095
#ifndef CONFIG_IOTHREAD
4096
            tcg_cpu_exec();
4097
#endif
4098
#ifdef CONFIG_PROFILER
4099
            ti = profile_getclock();
4100
#endif
4101
            main_loop_wait(qemu_calculate_timeout());
4102
#ifdef CONFIG_PROFILER
4103
            dev_time += profile_getclock() - ti;
4104
#endif
4105
        } while (vm_can_run());
4106

    
4107
        if (qemu_debug_requested())
4108
            vm_stop(EXCP_DEBUG);
4109
        if (qemu_shutdown_requested()) {
4110
            if (no_shutdown) {
4111
                vm_stop(0);
4112
                no_shutdown = 0;
4113
            } else
4114
                break;
4115
        }
4116
        if (qemu_reset_requested()) {
4117
            pause_all_vcpus();
4118
            qemu_system_reset();
4119
            resume_all_vcpus();
4120
        }
4121
        if (qemu_powerdown_requested()) {
4122
            qemu_irq_raise(qemu_system_powerdown);
4123
        }
4124
        if ((r = qemu_vmstop_requested()))
4125
            vm_stop(r);
4126
    }
4127
    pause_all_vcpus();
4128
}
4129

    
4130
static void version(void)
4131
{
4132
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4133
}
4134

    
4135
static void help(int exitcode)
4136
{
4137
    version();
4138
    printf("usage: %s [options] [disk_image]\n"
4139
           "\n"
4140
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4141
           "\n"
4142
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4143
           opt_help
4144
#define DEFHEADING(text) stringify(text) "\n"
4145
#include "qemu-options.h"
4146
#undef DEF
4147
#undef DEFHEADING
4148
#undef GEN_DOCS
4149
           "\n"
4150
           "During emulation, the following keys are useful:\n"
4151
           "ctrl-alt-f      toggle full screen\n"
4152
           "ctrl-alt-n      switch to virtual console 'n'\n"
4153
           "ctrl-alt        toggle mouse and keyboard grab\n"
4154
           "\n"
4155
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4156
           ,
4157
           "qemu",
4158
           DEFAULT_RAM_SIZE,
4159
#ifndef _WIN32
4160
           DEFAULT_NETWORK_SCRIPT,
4161
           DEFAULT_NETWORK_DOWN_SCRIPT,
4162
#endif
4163
           DEFAULT_GDBSTUB_PORT,
4164
           "/tmp/qemu.log");
4165
    exit(exitcode);
4166
}
4167

    
4168
#define HAS_ARG 0x0001
4169

    
4170
enum {
4171
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4172
    opt_enum,
4173
#define DEFHEADING(text)
4174
#include "qemu-options.h"
4175
#undef DEF
4176
#undef DEFHEADING
4177
#undef GEN_DOCS
4178
};
4179

    
4180
typedef struct QEMUOption {
4181
    const char *name;
4182
    int flags;
4183
    int index;
4184
} QEMUOption;
4185

    
4186
static const QEMUOption qemu_options[] = {
4187
    { "h", 0, QEMU_OPTION_h },
4188
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4189
    { option, opt_arg, opt_enum },
4190
#define DEFHEADING(text)
4191
#include "qemu-options.h"
4192
#undef DEF
4193
#undef DEFHEADING
4194
#undef GEN_DOCS
4195
    { NULL },
4196
};
4197

    
4198
#ifdef HAS_AUDIO
4199
struct soundhw soundhw[] = {
4200
#ifdef HAS_AUDIO_CHOICE
4201
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4202
    {
4203
        "pcspk",
4204
        "PC speaker",
4205
        0,
4206
        1,
4207
        { .init_isa = pcspk_audio_init }
4208
    },
4209
#endif
4210

    
4211
#ifdef CONFIG_SB16
4212
    {
4213
        "sb16",
4214
        "Creative Sound Blaster 16",
4215
        0,
4216
        1,
4217
        { .init_isa = SB16_init }
4218
    },
4219
#endif
4220

    
4221
#ifdef CONFIG_CS4231A
4222
    {
4223
        "cs4231a",
4224
        "CS4231A",
4225
        0,
4226
        1,
4227
        { .init_isa = cs4231a_init }
4228
    },
4229
#endif
4230

    
4231
#ifdef CONFIG_ADLIB
4232
    {
4233
        "adlib",
4234
#ifdef HAS_YMF262
4235
        "Yamaha YMF262 (OPL3)",
4236
#else
4237
        "Yamaha YM3812 (OPL2)",
4238
#endif
4239
        0,
4240
        1,
4241
        { .init_isa = Adlib_init }
4242
    },
4243
#endif
4244

    
4245
#ifdef CONFIG_GUS
4246
    {
4247
        "gus",
4248
        "Gravis Ultrasound GF1",
4249
        0,
4250
        1,
4251
        { .init_isa = GUS_init }
4252
    },
4253
#endif
4254

    
4255
#ifdef CONFIG_AC97
4256
    {
4257
        "ac97",
4258
        "Intel 82801AA AC97 Audio",
4259
        0,
4260
        0,
4261
        { .init_pci = ac97_init }
4262
    },
4263
#endif
4264

    
4265
#ifdef CONFIG_ES1370
4266
    {
4267
        "es1370",
4268
        "ENSONIQ AudioPCI ES1370",
4269
        0,
4270
        0,
4271
        { .init_pci = es1370_init }
4272
    },
4273
#endif
4274

    
4275
#endif /* HAS_AUDIO_CHOICE */
4276

    
4277
    { NULL, NULL, 0, 0, { NULL } }
4278
};
4279

    
4280
static void select_soundhw (const char *optarg)
4281
{
4282
    struct soundhw *c;
4283

    
4284
    if (*optarg == '?') {
4285
    show_valid_cards:
4286

    
4287
        printf ("Valid sound card names (comma separated):\n");
4288
        for (c = soundhw; c->name; ++c) {
4289
            printf ("%-11s %s\n", c->name, c->descr);
4290
        }
4291
        printf ("\n-soundhw all will enable all of the above\n");
4292
        exit (*optarg != '?');
4293
    }
4294
    else {
4295
        size_t l;
4296
        const char *p;
4297
        char *e;
4298
        int bad_card = 0;
4299

    
4300
        if (!strcmp (optarg, "all")) {
4301
            for (c = soundhw; c->name; ++c) {
4302
                c->enabled = 1;
4303
            }
4304
            return;
4305
        }
4306

    
4307
        p = optarg;
4308
        while (*p) {
4309
            e = strchr (p, ',');
4310
            l = !e ? strlen (p) : (size_t) (e - p);
4311

    
4312
            for (c = soundhw; c->name; ++c) {
4313
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4314
                    c->enabled = 1;
4315
                    break;
4316
                }
4317
            }
4318

    
4319
            if (!c->name) {
4320
                if (l > 80) {
4321
                    fprintf (stderr,
4322
                             "Unknown sound card name (too big to show)\n");
4323
                }
4324
                else {
4325
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4326
                             (int) l, p);
4327
                }
4328
                bad_card = 1;
4329
            }
4330
            p += l + (e != NULL);
4331
        }
4332

    
4333
        if (bad_card)
4334
            goto show_valid_cards;
4335
    }
4336
}
4337
#endif
4338

    
4339
static void select_vgahw (const char *p)
4340
{
4341
    const char *opts;
4342

    
4343
    vga_interface_type = VGA_NONE;
4344
    if (strstart(p, "std", &opts)) {
4345
        vga_interface_type = VGA_STD;
4346
    } else if (strstart(p, "cirrus", &opts)) {
4347
        vga_interface_type = VGA_CIRRUS;
4348
    } else if (strstart(p, "vmware", &opts)) {
4349
        vga_interface_type = VGA_VMWARE;
4350
    } else if (strstart(p, "xenfb", &opts)) {
4351
        vga_interface_type = VGA_XENFB;
4352
    } else if (!strstart(p, "none", &opts)) {
4353
    invalid_vga:
4354
        fprintf(stderr, "Unknown vga type: %s\n", p);
4355
        exit(1);
4356
    }
4357
    while (*opts) {
4358
        const char *nextopt;
4359

    
4360
        if (strstart(opts, ",retrace=", &nextopt)) {
4361
            opts = nextopt;
4362
            if (strstart(opts, "dumb", &nextopt))
4363
                vga_retrace_method = VGA_RETRACE_DUMB;
4364
            else if (strstart(opts, "precise", &nextopt))
4365
                vga_retrace_method = VGA_RETRACE_PRECISE;
4366
            else goto invalid_vga;
4367
        } else goto invalid_vga;
4368
        opts = nextopt;
4369
    }
4370
}
4371

    
4372
#ifdef TARGET_I386
4373
static int balloon_parse(const char *arg)
4374
{
4375
    QemuOpts *opts;
4376

    
4377
    if (strcmp(arg, "none") == 0) {
4378
        return 0;
4379
    }
4380

    
4381
    if (!strncmp(arg, "virtio", 6)) {
4382
        if (arg[6] == ',') {
4383
            /* have params -> parse them */
4384
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4385
            if (!opts)
4386
                return  -1;
4387
        } else {
4388
            /* create empty opts */
4389
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4390
        }
4391
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4392
        return 0;
4393
    }
4394

    
4395
    return -1;
4396
}
4397
#endif
4398

    
4399
#ifdef _WIN32
4400
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4401
{
4402
    exit(STATUS_CONTROL_C_EXIT);
4403
    return TRUE;
4404
}
4405
#endif
4406

    
4407
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4408
{
4409
    int ret;
4410

    
4411
    if(strlen(str) != 36)
4412
        return -1;
4413

    
4414
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4415
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4416
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4417

    
4418
    if(ret != 16)
4419
        return -1;
4420

    
4421
#ifdef TARGET_I386
4422
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4423
#endif
4424

    
4425
    return 0;
4426
}
4427

    
4428
#define MAX_NET_CLIENTS 32
4429

    
4430
#ifndef _WIN32
4431

    
4432
static void termsig_handler(int signal)
4433
{
4434
    qemu_system_shutdown_request();
4435
}
4436

    
4437
static void sigchld_handler(int signal)
4438
{
4439
    waitpid(-1, NULL, WNOHANG);
4440
}
4441

    
4442
static void sighandler_setup(void)
4443
{
4444
    struct sigaction act;
4445

    
4446
    memset(&act, 0, sizeof(act));
4447
    act.sa_handler = termsig_handler;
4448
    sigaction(SIGINT,  &act, NULL);
4449
    sigaction(SIGHUP,  &act, NULL);
4450
    sigaction(SIGTERM, &act, NULL);
4451

    
4452
    act.sa_handler = sigchld_handler;
4453
    act.sa_flags = SA_NOCLDSTOP;
4454
    sigaction(SIGCHLD, &act, NULL);
4455
}
4456

    
4457
#endif
4458

    
4459
#ifdef _WIN32
4460
/* Look for support files in the same directory as the executable.  */
4461
static char *find_datadir(const char *argv0)
4462
{
4463
    char *p;
4464
    char buf[MAX_PATH];
4465
    DWORD len;
4466

    
4467
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4468
    if (len == 0) {
4469
        return NULL;
4470
    }
4471

    
4472
    buf[len] = 0;
4473
    p = buf + len - 1;
4474
    while (p != buf && *p != '\\')
4475
        p--;
4476
    *p = 0;
4477
    if (access(buf, R_OK) == 0) {
4478
        return qemu_strdup(buf);
4479
    }
4480
    return NULL;
4481
}
4482
#else /* !_WIN32 */
4483

    
4484
/* Find a likely location for support files using the location of the binary.
4485
   For installed binaries this will be "$bindir/../share/qemu".  When
4486
   running from the build tree this will be "$bindir/../pc-bios".  */
4487
#define SHARE_SUFFIX "/share/qemu"
4488
#define BUILD_SUFFIX "/pc-bios"
4489
static char *find_datadir(const char *argv0)
4490
{
4491
    char *dir;
4492
    char *p = NULL;
4493
    char *res;
4494
    char buf[PATH_MAX];
4495
    size_t max_len;
4496

    
4497
#if defined(__linux__)
4498
    {
4499
        int len;
4500
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4501
        if (len > 0) {
4502
            buf[len] = 0;
4503
            p = buf;
4504
        }
4505
    }
4506
#elif defined(__FreeBSD__)
4507
    {
4508
        int len;
4509
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4510
        if (len > 0) {
4511
            buf[len] = 0;
4512
            p = buf;
4513
        }
4514
    }
4515
#endif
4516
    /* If we don't have any way of figuring out the actual executable
4517
       location then try argv[0].  */
4518
    if (!p) {
4519
        p = realpath(argv0, buf);
4520
        if (!p) {
4521
            return NULL;
4522
        }
4523
    }
4524
    dir = dirname(p);
4525
    dir = dirname(dir);
4526

    
4527
    max_len = strlen(dir) +
4528
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4529
    res = qemu_mallocz(max_len);
4530
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4531
    if (access(res, R_OK)) {
4532
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4533
        if (access(res, R_OK)) {
4534
            qemu_free(res);
4535
            res = NULL;
4536
        }
4537
    }
4538

    
4539
    return res;
4540
}
4541
#undef SHARE_SUFFIX
4542
#undef BUILD_SUFFIX
4543
#endif
4544

    
4545
char *qemu_find_file(int type, const char *name)
4546
{
4547
    int len;
4548
    const char *subdir;
4549
    char *buf;
4550

    
4551
    /* If name contains path separators then try it as a straight path.  */
4552
    if ((strchr(name, '/') || strchr(name, '\\'))
4553
        && access(name, R_OK) == 0) {
4554
        return qemu_strdup(name);
4555
    }
4556
    switch (type) {
4557
    case QEMU_FILE_TYPE_BIOS:
4558
        subdir = "";
4559
        break;
4560
    case QEMU_FILE_TYPE_KEYMAP:
4561
        subdir = "keymaps/";
4562
        break;
4563
    default:
4564
        abort();
4565
    }
4566
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4567
    buf = qemu_mallocz(len);
4568
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4569
    if (access(buf, R_OK)) {
4570
        qemu_free(buf);
4571
        return NULL;
4572
    }
4573
    return buf;
4574
}
4575

    
4576
static int device_init_func(QemuOpts *opts, void *opaque)
4577
{
4578
    DeviceState *dev;
4579

    
4580
    dev = qdev_device_add(opts);
4581
    if (!dev)
4582
        return -1;
4583
    return 0;
4584
}
4585

    
4586
struct device_config {
4587
    enum {
4588
        DEV_USB,       /* -usbdevice   */
4589
        DEV_BT,        /* -bt          */
4590
    } type;
4591
    const char *cmdline;
4592
    QTAILQ_ENTRY(device_config) next;
4593
};
4594
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4595

    
4596
static void add_device_config(int type, const char *cmdline)
4597
{
4598
    struct device_config *conf;
4599

    
4600
    conf = qemu_mallocz(sizeof(*conf));
4601
    conf->type = type;
4602
    conf->cmdline = cmdline;
4603
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4604
}
4605

    
4606
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4607
{
4608
    struct device_config *conf;
4609
    int rc;
4610

    
4611
    QTAILQ_FOREACH(conf, &device_configs, next) {
4612
        if (conf->type != type)
4613
            continue;
4614
        rc = func(conf->cmdline);
4615
        if (0 != rc)
4616
            return rc;
4617
    }
4618
    return 0;
4619
}
4620

    
4621
int main(int argc, char **argv, char **envp)
4622
{
4623
    const char *gdbstub_dev = NULL;
4624
    uint32_t boot_devices_bitmap = 0;
4625
    int i;
4626
    int snapshot, linux_boot, net_boot;
4627
    const char *initrd_filename;
4628
    const char *kernel_filename, *kernel_cmdline;
4629
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4630
    DisplayState *ds;
4631
    DisplayChangeListener *dcl;
4632
    int cyls, heads, secs, translation;
4633
    const char *net_clients[MAX_NET_CLIENTS];
4634
    int nb_net_clients;
4635
    QemuOpts *hda_opts = NULL, *opts;
4636
    int optind;
4637
    const char *r, *optarg;
4638
    CharDriverState *monitor_hds[MAX_MONITOR_DEVICES];
4639
    const char *monitor_devices[MAX_MONITOR_DEVICES];
4640
    int monitor_device_index;
4641
    const char *serial_devices[MAX_SERIAL_PORTS];
4642
    int serial_device_index;
4643
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4644
    int parallel_device_index;
4645
    const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4646
    int virtio_console_index;
4647
    const char *loadvm = NULL;
4648
    QEMUMachine *machine;
4649
    const char *cpu_model;
4650
#ifndef _WIN32
4651
    int fds[2];
4652
#endif
4653
    int tb_size;
4654
    const char *pid_file = NULL;
4655
    const char *incoming = NULL;
4656
#ifndef _WIN32
4657
    int fd = 0;
4658
    struct passwd *pwd = NULL;
4659
    const char *chroot_dir = NULL;
4660
    const char *run_as = NULL;
4661
#endif
4662
    CPUState *env;
4663
    int show_vnc_port = 0;
4664

    
4665
    qemu_errors_to_file(stderr);
4666
    qemu_cache_utils_init(envp);
4667

    
4668
    QLIST_INIT (&vm_change_state_head);
4669
#ifndef _WIN32
4670
    {
4671
        struct sigaction act;
4672
        sigfillset(&act.sa_mask);
4673
        act.sa_flags = 0;
4674
        act.sa_handler = SIG_IGN;
4675
        sigaction(SIGPIPE, &act, NULL);
4676
    }
4677
#else
4678
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4679
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4680
       QEMU to run on a single CPU */
4681
    {
4682
        HANDLE h;
4683
        DWORD mask, smask;
4684
        int i;
4685
        h = GetCurrentProcess();
4686
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4687
            for(i = 0; i < 32; i++) {
4688
                if (mask & (1 << i))
4689
                    break;
4690
            }
4691
            if (i != 32) {
4692
                mask = 1 << i;
4693
                SetProcessAffinityMask(h, mask);
4694
            }
4695
        }
4696
    }
4697
#endif
4698

    
4699
    module_call_init(MODULE_INIT_MACHINE);
4700
    machine = find_default_machine();
4701
    cpu_model = NULL;
4702
    initrd_filename = NULL;
4703
    ram_size = 0;
4704
    snapshot = 0;
4705
    kernel_filename = NULL;
4706
    kernel_cmdline = "";
4707
    cyls = heads = secs = 0;
4708
    translation = BIOS_ATA_TRANSLATION_AUTO;
4709

    
4710
    serial_devices[0] = "vc:80Cx24C";
4711
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4712
        serial_devices[i] = NULL;
4713
    serial_device_index = 0;
4714

    
4715
    parallel_devices[0] = "vc:80Cx24C";
4716
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4717
        parallel_devices[i] = NULL;
4718
    parallel_device_index = 0;
4719

    
4720
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4721
        virtio_consoles[i] = NULL;
4722
    virtio_console_index = 0;
4723

    
4724
    monitor_devices[0] = "vc:80Cx24C";
4725
    for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4726
        monitor_devices[i] = NULL;
4727
    }
4728
    monitor_device_index = 0;
4729

    
4730
    for (i = 0; i < MAX_NODES; i++) {
4731
        node_mem[i] = 0;
4732
        node_cpumask[i] = 0;
4733
    }
4734

    
4735
    nb_net_clients = 0;
4736
    nb_numa_nodes = 0;
4737
    nb_nics = 0;
4738

    
4739
    tb_size = 0;
4740
    autostart= 1;
4741

    
4742
    optind = 1;
4743
    for(;;) {
4744
        if (optind >= argc)
4745
            break;
4746
        r = argv[optind];
4747
        if (r[0] != '-') {
4748
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4749
        } else {
4750
            const QEMUOption *popt;
4751

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

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

    
4931
                    if (!strchr(optarg, '=')) {
4932
                        legacy = 1;
4933
                        pstrcpy(buf, sizeof(buf), optarg);
4934
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4935
                        fprintf(stderr,
4936
                                "qemu: unknown boot parameter '%s' in '%s'\n",
4937
                                buf, optarg);
4938
                        exit(1);
4939
                    }
4940

    
4941
                    if (legacy ||
4942
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
4943
                        boot_devices_bitmap = parse_bootdevices(buf);
4944
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
4945
                    }
4946
                    if (!legacy) {
4947
                        if (get_param_value(buf, sizeof(buf),
4948
                                            "once", optarg)) {
4949
                            boot_devices_bitmap |= parse_bootdevices(buf);
4950
                            standard_boot_devices = qemu_strdup(boot_devices);
4951
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
4952
                            qemu_register_reset(restore_boot_devices,
4953
                                                standard_boot_devices);
4954
                        }
4955
                        if (get_param_value(buf, sizeof(buf),
4956
                                            "menu", optarg)) {
4957
                            if (!strcmp(buf, "on")) {
4958
                                boot_menu = 1;
4959
                            } else if (!strcmp(buf, "off")) {
4960
                                boot_menu = 0;
4961
                            } else {
4962
                                fprintf(stderr,
4963
                                        "qemu: invalid option value '%s'\n",
4964
                                        buf);
4965
                                exit(1);
4966
                            }
4967
                        }
4968
                    }
4969
                }
4970
                break;
4971
            case QEMU_OPTION_fda:
4972
            case QEMU_OPTION_fdb:
4973
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4974
                break;
4975
#ifdef TARGET_I386
4976
            case QEMU_OPTION_no_fd_bootchk:
4977
                fd_bootchk = 0;
4978
                break;
4979
#endif
4980
            case QEMU_OPTION_net:
4981
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4982
                    fprintf(stderr, "qemu: too many network clients\n");
4983
                    exit(1);
4984
                }
4985
                net_clients[nb_net_clients] = optarg;
4986
                nb_net_clients++;
4987
                break;
4988
#ifdef CONFIG_SLIRP
4989
            case QEMU_OPTION_tftp:
4990
                legacy_tftp_prefix = optarg;
4991
                break;
4992
            case QEMU_OPTION_bootp:
4993
                legacy_bootp_filename = optarg;
4994
                break;
4995
#ifndef _WIN32
4996
            case QEMU_OPTION_smb:
4997
                net_slirp_smb(optarg);
4998
                break;
4999
#endif
5000
            case QEMU_OPTION_redir:
5001
                net_slirp_redir(optarg);
5002
                break;
5003
#endif
5004
            case QEMU_OPTION_bt:
5005
                add_device_config(DEV_BT, optarg);
5006
                break;
5007
#ifdef HAS_AUDIO
5008
            case QEMU_OPTION_audio_help:
5009
                AUD_help ();
5010
                exit (0);
5011
                break;
5012
            case QEMU_OPTION_soundhw:
5013
                select_soundhw (optarg);
5014
                break;
5015
#endif
5016
            case QEMU_OPTION_h:
5017
                help(0);
5018
                break;
5019
            case QEMU_OPTION_version:
5020
                version();
5021
                exit(0);
5022
                break;
5023
            case QEMU_OPTION_m: {
5024
                uint64_t value;
5025
                char *ptr;
5026

    
5027
                value = strtoul(optarg, &ptr, 10);
5028
                switch (*ptr) {
5029
                case 0: case 'M': case 'm':
5030
                    value <<= 20;
5031
                    break;
5032
                case 'G': case 'g':
5033
                    value <<= 30;
5034
                    break;
5035
                default:
5036
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5037
                    exit(1);
5038
                }
5039

    
5040
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5041
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5042
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5043
                    exit(1);
5044
                }
5045
                if (value != (uint64_t)(ram_addr_t)value) {
5046
                    fprintf(stderr, "qemu: ram size too large\n");
5047
                    exit(1);
5048
                }
5049
                ram_size = value;
5050
                break;
5051
            }
5052
            case QEMU_OPTION_d:
5053
                {
5054
                    int mask;
5055
                    const CPULogItem *item;
5056

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

    
5127
                    graphic_width = w;
5128
                    graphic_height = h;
5129
                    graphic_depth = depth;
5130
                }
5131
                break;
5132
#endif
5133
            case QEMU_OPTION_echr:
5134
                {
5135
                    char *r;
5136
                    term_escape_char = strtol(optarg, &r, 0);
5137
                    if (r == optarg)
5138
                        printf("Bad argument to echr\n");
5139
                    break;
5140
                }
5141
            case QEMU_OPTION_monitor:
5142
                if (monitor_device_index >= MAX_MONITOR_DEVICES) {
5143
                    fprintf(stderr, "qemu: too many monitor devices\n");
5144
                    exit(1);
5145
                }
5146
                monitor_devices[monitor_device_index] = optarg;
5147
                monitor_device_index++;
5148
                break;
5149
            case QEMU_OPTION_chardev:
5150
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5151
                if (!opts) {
5152
                    fprintf(stderr, "parse error: %s\n", optarg);
5153
                    exit(1);
5154
                }
5155
                if (qemu_chr_open_opts(opts, NULL) == NULL) {
5156
                    exit(1);
5157
                }
5158
                break;
5159
            case QEMU_OPTION_serial:
5160
                if (serial_device_index >= MAX_SERIAL_PORTS) {
5161
                    fprintf(stderr, "qemu: too many serial ports\n");
5162
                    exit(1);
5163
                }
5164
                serial_devices[serial_device_index] = optarg;
5165
                serial_device_index++;
5166
                break;
5167
            case QEMU_OPTION_watchdog:
5168
                if (watchdog) {
5169
                    fprintf(stderr,
5170
                            "qemu: only one watchdog option may be given\n");
5171
                    return 1;
5172
                }
5173
                watchdog = optarg;
5174
                break;
5175
            case QEMU_OPTION_watchdog_action:
5176
                if (select_watchdog_action(optarg) == -1) {
5177
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
5178
                    exit(1);
5179
                }
5180
                break;
5181
            case QEMU_OPTION_virtiocon:
5182
                if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5183
                    fprintf(stderr, "qemu: too many virtio consoles\n");
5184
                    exit(1);
5185
                }
5186
                virtio_consoles[virtio_console_index] = optarg;
5187
                virtio_console_index++;
5188
                break;
5189
            case QEMU_OPTION_parallel:
5190
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5191
                    fprintf(stderr, "qemu: too many parallel ports\n");
5192
                    exit(1);
5193
                }
5194
                parallel_devices[parallel_device_index] = optarg;
5195
                parallel_device_index++;
5196
                break;
5197
            case QEMU_OPTION_loadvm:
5198
                loadvm = optarg;
5199
                break;
5200
            case QEMU_OPTION_full_screen:
5201
                full_screen = 1;
5202
                break;
5203
#ifdef CONFIG_SDL
5204
            case QEMU_OPTION_no_frame:
5205
                no_frame = 1;
5206
                break;
5207
            case QEMU_OPTION_alt_grab:
5208
                alt_grab = 1;
5209
                break;
5210
            case QEMU_OPTION_no_quit:
5211
                no_quit = 1;
5212
                break;
5213
            case QEMU_OPTION_sdl:
5214
                display_type = DT_SDL;
5215
                break;
5216
#endif
5217
            case QEMU_OPTION_pidfile:
5218
                pid_file = optarg;
5219
                break;
5220
#ifdef TARGET_I386
5221
            case QEMU_OPTION_win2k_hack:
5222
                win2k_install_hack = 1;
5223
                break;
5224
            case QEMU_OPTION_rtc_td_hack:
5225
                rtc_td_hack = 1;
5226
                break;
5227
            case QEMU_OPTION_acpitable:
5228
                if(acpi_table_add(optarg) < 0) {
5229
                    fprintf(stderr, "Wrong acpi table provided\n");
5230
                    exit(1);
5231
                }
5232
                break;
5233
            case QEMU_OPTION_smbios:
5234
                if(smbios_entry_add(optarg) < 0) {
5235
                    fprintf(stderr, "Wrong smbios provided\n");
5236
                    exit(1);
5237
                }
5238
                break;
5239
#endif
5240
#ifdef CONFIG_KVM
5241
            case QEMU_OPTION_enable_kvm:
5242
                kvm_allowed = 1;
5243
                break;
5244
#endif
5245
            case QEMU_OPTION_usb:
5246
                usb_enabled = 1;
5247
                break;
5248
            case QEMU_OPTION_usbdevice:
5249
                usb_enabled = 1;
5250
                add_device_config(DEV_USB, optarg);
5251
                break;
5252
            case QEMU_OPTION_device:
5253
                opts = qemu_opts_parse(&qemu_device_opts, optarg, "driver");
5254
                if (!opts) {
5255
                    fprintf(stderr, "parse error: %s\n", optarg);
5256
                    exit(1);
5257
                }
5258
                break;
5259
            case QEMU_OPTION_smp:
5260
                smp_parse(optarg);
5261
                if (smp_cpus < 1) {
5262
                    fprintf(stderr, "Invalid number of CPUs\n");
5263
                    exit(1);
5264
                }
5265
                if (max_cpus < smp_cpus) {
5266
                    fprintf(stderr, "maxcpus must be equal to or greater than "
5267
                            "smp\n");
5268
                    exit(1);
5269
                }
5270
                if (max_cpus > 255) {
5271
                    fprintf(stderr, "Unsupported number of maxcpus\n");
5272
                    exit(1);
5273
                }
5274
                break;
5275
            case QEMU_OPTION_vnc:
5276
                display_type = DT_VNC;
5277
                vnc_display = optarg;
5278
                break;
5279
#ifdef TARGET_I386
5280
            case QEMU_OPTION_no_acpi:
5281
                acpi_enabled = 0;
5282
                break;
5283
            case QEMU_OPTION_no_hpet:
5284
                no_hpet = 1;
5285
                break;
5286
            case QEMU_OPTION_balloon:
5287
                if (balloon_parse(optarg) < 0) {
5288
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5289
                    exit(1);
5290
                }
5291
                break;
5292
#endif
5293
            case QEMU_OPTION_no_reboot:
5294
                no_reboot = 1;
5295
                break;
5296
            case QEMU_OPTION_no_shutdown:
5297
                no_shutdown = 1;
5298
                break;
5299
            case QEMU_OPTION_show_cursor:
5300
                cursor_hide = 0;
5301
                break;
5302
            case QEMU_OPTION_uuid:
5303
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5304
                    fprintf(stderr, "Fail to parse UUID string."
5305
                            " Wrong format.\n");
5306
                    exit(1);
5307
                }
5308
                break;
5309
#ifndef _WIN32
5310
            case QEMU_OPTION_daemonize:
5311
                daemonize = 1;
5312
                break;
5313
#endif
5314
            case QEMU_OPTION_option_rom:
5315
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5316
                    fprintf(stderr, "Too many option ROMs\n");
5317
                    exit(1);
5318
                }
5319
                option_rom[nb_option_roms] = optarg;
5320
                nb_option_roms++;
5321
                break;
5322
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5323
            case QEMU_OPTION_semihosting:
5324
                semihosting_enabled = 1;
5325
                break;
5326
#endif
5327
            case QEMU_OPTION_name:
5328
                qemu_name = qemu_strdup(optarg);
5329
                 {
5330
                     char *p = strchr(qemu_name, ',');
5331
                     if (p != NULL) {
5332
                        *p++ = 0;
5333
                        if (strncmp(p, "process=", 8)) {
5334
                            fprintf(stderr, "Unknown subargument %s to -name", p);
5335
                            exit(1);
5336
                        }
5337
                        p += 8;
5338
                        set_proc_name(p);
5339
                     }        
5340
                 }        
5341
                break;
5342
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5343
            case QEMU_OPTION_prom_env:
5344
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5345
                    fprintf(stderr, "Too many prom variables\n");
5346
                    exit(1);
5347
                }
5348
                prom_envs[nb_prom_envs] = optarg;
5349
                nb_prom_envs++;
5350
                break;
5351
#endif
5352
#ifdef TARGET_ARM
5353
            case QEMU_OPTION_old_param:
5354
                old_param = 1;
5355
                break;
5356
#endif
5357
            case QEMU_OPTION_clock:
5358
                configure_alarms(optarg);
5359
                break;
5360
            case QEMU_OPTION_startdate:
5361
                {
5362
                    struct tm tm;
5363
                    time_t rtc_start_date;
5364
                    if (!strcmp(optarg, "now")) {
5365
                        rtc_date_offset = -1;
5366
                    } else {
5367
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5368
                               &tm.tm_year,
5369
                               &tm.tm_mon,
5370
                               &tm.tm_mday,
5371
                               &tm.tm_hour,
5372
                               &tm.tm_min,
5373
                               &tm.tm_sec) == 6) {
5374
                            /* OK */
5375
                        } else if (sscanf(optarg, "%d-%d-%d",
5376
                                          &tm.tm_year,
5377
                                          &tm.tm_mon,
5378
                                          &tm.tm_mday) == 3) {
5379
                            tm.tm_hour = 0;
5380
                            tm.tm_min = 0;
5381
                            tm.tm_sec = 0;
5382
                        } else {
5383
                            goto date_fail;
5384
                        }
5385
                        tm.tm_year -= 1900;
5386
                        tm.tm_mon--;
5387
                        rtc_start_date = mktimegm(&tm);
5388
                        if (rtc_start_date == -1) {
5389
                        date_fail:
5390
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
5391
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5392
                            exit(1);
5393
                        }
5394
                        rtc_date_offset = time(NULL) - rtc_start_date;
5395
                    }
5396
                }
5397
                break;
5398
            case QEMU_OPTION_tb_size:
5399
                tb_size = strtol(optarg, NULL, 0);
5400
                if (tb_size < 0)
5401
                    tb_size = 0;
5402
                break;
5403
            case QEMU_OPTION_icount:
5404
                use_icount = 1;
5405
                if (strcmp(optarg, "auto") == 0) {
5406
                    icount_time_shift = -1;
5407
                } else {
5408
                    icount_time_shift = strtol(optarg, NULL, 0);
5409
                }
5410
                break;
5411
            case QEMU_OPTION_incoming:
5412
                incoming = optarg;
5413
                break;
5414
#ifndef _WIN32
5415
            case QEMU_OPTION_chroot:
5416
                chroot_dir = optarg;
5417
                break;
5418
            case QEMU_OPTION_runas:
5419
                run_as = optarg;
5420
                break;
5421
#endif
5422
#ifdef CONFIG_XEN
5423
            case QEMU_OPTION_xen_domid:
5424
                xen_domid = atoi(optarg);
5425
                break;
5426
            case QEMU_OPTION_xen_create:
5427
                xen_mode = XEN_CREATE;
5428
                break;
5429
            case QEMU_OPTION_xen_attach:
5430
                xen_mode = XEN_ATTACH;
5431
                break;
5432
#endif
5433
            }
5434
        }
5435
    }
5436

    
5437
    /* If no data_dir is specified then try to find it relative to the
5438
       executable path.  */
5439
    if (!data_dir) {
5440
        data_dir = find_datadir(argv[0]);
5441
    }
5442
    /* If all else fails use the install patch specified when building.  */
5443
    if (!data_dir) {
5444
        data_dir = CONFIG_QEMU_SHAREDIR;
5445
    }
5446

    
5447
    /*
5448
     * Default to max_cpus = smp_cpus, in case the user doesn't
5449
     * specify a max_cpus value.
5450
     */
5451
    if (!max_cpus)
5452
        max_cpus = smp_cpus;
5453

    
5454
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5455
    if (smp_cpus > machine->max_cpus) {
5456
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5457
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5458
                machine->max_cpus);
5459
        exit(1);
5460
    }
5461

    
5462
    if (display_type == DT_NOGRAPHIC) {
5463
       if (serial_device_index == 0)
5464
           serial_devices[0] = "stdio";
5465
       if (parallel_device_index == 0)
5466
           parallel_devices[0] = "null";
5467
       if (strncmp(monitor_devices[0], "vc", 2) == 0) {
5468
           monitor_devices[0] = "stdio";
5469
       }
5470
    }
5471

    
5472
#ifndef _WIN32
5473
    if (daemonize) {
5474
        pid_t pid;
5475

    
5476
        if (pipe(fds) == -1)
5477
            exit(1);
5478

    
5479
        pid = fork();
5480
        if (pid > 0) {
5481
            uint8_t status;
5482
            ssize_t len;
5483

    
5484
            close(fds[1]);
5485

    
5486
        again:
5487
            len = read(fds[0], &status, 1);
5488
            if (len == -1 && (errno == EINTR))
5489
                goto again;
5490

    
5491
            if (len != 1)
5492
                exit(1);
5493
            else if (status == 1) {
5494
                fprintf(stderr, "Could not acquire pidfile\n");
5495
                exit(1);
5496
            } else
5497
                exit(0);
5498
        } else if (pid < 0)
5499
            exit(1);
5500

    
5501
        setsid();
5502

    
5503
        pid = fork();
5504
        if (pid > 0)
5505
            exit(0);
5506
        else if (pid < 0)
5507
            exit(1);
5508

    
5509
        umask(027);
5510

    
5511
        signal(SIGTSTP, SIG_IGN);
5512
        signal(SIGTTOU, SIG_IGN);
5513
        signal(SIGTTIN, SIG_IGN);
5514
    }
5515

    
5516
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5517
        if (daemonize) {
5518
            uint8_t status = 1;
5519
            write(fds[1], &status, 1);
5520
        } else
5521
            fprintf(stderr, "Could not acquire pid file\n");
5522
        exit(1);
5523
    }
5524
#endif
5525

    
5526
    if (kvm_enabled()) {
5527
        int ret;
5528

    
5529
        ret = kvm_init(smp_cpus);
5530
        if (ret < 0) {
5531
            fprintf(stderr, "failed to initialize KVM\n");
5532
            exit(1);
5533
        }
5534
    }
5535

    
5536
    if (qemu_init_main_loop()) {
5537
        fprintf(stderr, "qemu_init_main_loop failed\n");
5538
        exit(1);
5539
    }
5540
    linux_boot = (kernel_filename != NULL);
5541

    
5542
    if (!linux_boot && *kernel_cmdline != '\0') {
5543
        fprintf(stderr, "-append only allowed with -kernel option\n");
5544
        exit(1);
5545
    }
5546

    
5547
    if (!linux_boot && initrd_filename != NULL) {
5548
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5549
        exit(1);
5550
    }
5551

    
5552
#ifndef _WIN32
5553
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5554
    setvbuf(stdout, NULL, _IOLBF, 0);
5555
#endif
5556

    
5557
    init_clocks();
5558
    if (init_timer_alarm() < 0) {
5559
        fprintf(stderr, "could not initialize alarm timer\n");
5560
        exit(1);
5561
    }
5562
    if (use_icount && icount_time_shift < 0) {
5563
        use_icount = 2;
5564
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5565
           It will be corrected fairly quickly anyway.  */
5566
        icount_time_shift = 3;
5567
        init_icount_adjust();
5568
    }
5569

    
5570
#ifdef _WIN32
5571
    socket_init();
5572
#endif
5573

    
5574
    /* init network clients */
5575
    if (nb_net_clients == 0) {
5576
        /* if no clients, we use a default config */
5577
        net_clients[nb_net_clients++] = "nic";
5578
#ifdef CONFIG_SLIRP
5579
        net_clients[nb_net_clients++] = "user";
5580
#endif
5581
    }
5582

    
5583
    for(i = 0;i < nb_net_clients; i++) {
5584
        if (net_client_parse(net_clients[i]) < 0)
5585
            exit(1);
5586
    }
5587

    
5588
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5589
    net_set_boot_mask(net_boot);
5590

    
5591
    net_client_check();
5592

    
5593
    /* init the bluetooth world */
5594
    if (foreach_device_config(DEV_BT, bt_parse))
5595
        exit(1);
5596

    
5597
    /* init the memory */
5598
    if (ram_size == 0)
5599
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5600

    
5601
    /* init the dynamic translator */
5602
    cpu_exec_init_all(tb_size * 1024 * 1024);
5603

    
5604
    bdrv_init();
5605

    
5606
    /* we always create the cdrom drive, even if no disk is there */
5607
    drive_add(NULL, CDROM_ALIAS);
5608

    
5609
    /* we always create at least one floppy */
5610
    drive_add(NULL, FD_ALIAS, 0);
5611

    
5612
    /* we always create one sd slot, even if no card is in it */
5613
    drive_add(NULL, SD_ALIAS);
5614

    
5615
    /* open the virtual block devices */
5616
    if (snapshot)
5617
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5618
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5619
        exit(1);
5620

    
5621
    vmstate_register(0, &vmstate_timers ,&timers_state);
5622
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5623

    
5624
    /* Maintain compatibility with multiple stdio monitors */
5625
    if (!strcmp(monitor_devices[0],"stdio")) {
5626
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5627
            const char *devname = serial_devices[i];
5628
            if (devname && !strcmp(devname,"mon:stdio")) {
5629
                monitor_devices[0] = NULL;
5630
                break;
5631
            } else if (devname && !strcmp(devname,"stdio")) {
5632
                monitor_devices[0] = NULL;
5633
                serial_devices[i] = "mon:stdio";
5634
                break;
5635
            }
5636
        }
5637
    }
5638

    
5639
    if (nb_numa_nodes > 0) {
5640
        int i;
5641

    
5642
        if (nb_numa_nodes > smp_cpus) {
5643
            nb_numa_nodes = smp_cpus;
5644
        }
5645

    
5646
        /* If no memory size if given for any node, assume the default case
5647
         * and distribute the available memory equally across all nodes
5648
         */
5649
        for (i = 0; i < nb_numa_nodes; i++) {
5650
            if (node_mem[i] != 0)
5651
                break;
5652
        }
5653
        if (i == nb_numa_nodes) {
5654
            uint64_t usedmem = 0;
5655

    
5656
            /* On Linux, the each node's border has to be 8MB aligned,
5657
             * the final node gets the rest.
5658
             */
5659
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5660
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5661
                usedmem += node_mem[i];
5662
            }
5663
            node_mem[i] = ram_size - usedmem;
5664
        }
5665

    
5666
        for (i = 0; i < nb_numa_nodes; i++) {
5667
            if (node_cpumask[i] != 0)
5668
                break;
5669
        }
5670
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5671
         * must cope with this anyway, because there are BIOSes out there in
5672
         * real machines which also use this scheme.
5673
         */
5674
        if (i == nb_numa_nodes) {
5675
            for (i = 0; i < smp_cpus; i++) {
5676
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5677
            }
5678
        }
5679
    }
5680

    
5681
    for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5682
        const char *devname = monitor_devices[i];
5683
        if (devname && strcmp(devname, "none")) {
5684
            char label[32];
5685
            if (i == 0) {
5686
                snprintf(label, sizeof(label), "monitor");
5687
            } else {
5688
                snprintf(label, sizeof(label), "monitor%d", i);
5689
            }
5690
            monitor_hds[i] = qemu_chr_open(label, devname, NULL);
5691
            if (!monitor_hds[i]) {
5692
                fprintf(stderr, "qemu: could not open monitor device '%s'\n",
5693
                        devname);
5694
                exit(1);
5695
            }
5696
        }
5697
    }
5698

    
5699
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5700
        const char *devname = serial_devices[i];
5701
        if (devname && strcmp(devname, "none")) {
5702
            char label[32];
5703
            snprintf(label, sizeof(label), "serial%d", i);
5704
            serial_hds[i] = qemu_chr_open(label, devname, NULL);
5705
            if (!serial_hds[i]) {
5706
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5707
                        devname);
5708
                exit(1);
5709
            }
5710
        }
5711
    }
5712

    
5713
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5714
        const char *devname = parallel_devices[i];
5715
        if (devname && strcmp(devname, "none")) {
5716
            char label[32];
5717
            snprintf(label, sizeof(label), "parallel%d", i);
5718
            parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5719
            if (!parallel_hds[i]) {
5720
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5721
                        devname);
5722
                exit(1);
5723
            }
5724
        }
5725
    }
5726

    
5727
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5728
        const char *devname = virtio_consoles[i];
5729
        if (devname && strcmp(devname, "none")) {
5730
            char label[32];
5731
            snprintf(label, sizeof(label), "virtcon%d", i);
5732
            virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5733
            if (!virtcon_hds[i]) {
5734
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5735
                        devname);
5736
                exit(1);
5737
            }
5738
        }
5739
    }
5740

    
5741
    module_call_init(MODULE_INIT_DEVICE);
5742

    
5743
    if (watchdog) {
5744
        i = select_watchdog(watchdog);
5745
        if (i > 0)
5746
            exit (i == 1 ? 1 : 0);
5747
    }
5748

    
5749
    if (machine->compat_props) {
5750
        qdev_prop_register_compat(machine->compat_props);
5751
    }
5752
    machine->init(ram_size, boot_devices,
5753
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5754

    
5755

    
5756
#ifndef _WIN32
5757
    /* must be after terminal init, SDL library changes signal handlers */
5758
    sighandler_setup();
5759
#endif
5760

    
5761
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5762
        for (i = 0; i < nb_numa_nodes; i++) {
5763
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5764
                env->numa_node = i;
5765
            }
5766
        }
5767
    }
5768

    
5769
    current_machine = machine;
5770

    
5771
    /* init USB devices */
5772
    if (usb_enabled) {
5773
        foreach_device_config(DEV_USB, usb_parse);
5774
    }
5775

    
5776
    /* init generic devices */
5777
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5778
        exit(1);
5779

    
5780
    if (!display_state)
5781
        dumb_display_init();
5782
    /* just use the first displaystate for the moment */
5783
    ds = display_state;
5784

    
5785
    if (display_type == DT_DEFAULT) {
5786
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5787
        display_type = DT_SDL;
5788
#else
5789
        display_type = DT_VNC;
5790
        vnc_display = "localhost:0,to=99";
5791
        show_vnc_port = 1;
5792
#endif
5793
    }
5794
        
5795

    
5796
    switch (display_type) {
5797
    case DT_NOGRAPHIC:
5798
        break;
5799
#if defined(CONFIG_CURSES)
5800
    case DT_CURSES:
5801
        curses_display_init(ds, full_screen);
5802
        break;
5803
#endif
5804
#if defined(CONFIG_SDL)
5805
    case DT_SDL:
5806
        sdl_display_init(ds, full_screen, no_frame);
5807
        break;
5808
#elif defined(CONFIG_COCOA)
5809
    case DT_SDL:
5810
        cocoa_display_init(ds, full_screen);
5811
        break;
5812
#endif
5813
    case DT_VNC:
5814
        vnc_display_init(ds);
5815
        if (vnc_display_open(ds, vnc_display) < 0)
5816
            exit(1);
5817

    
5818
        if (show_vnc_port) {
5819
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5820
        }
5821
        break;
5822
    default:
5823
        break;
5824
    }
5825
    dpy_resize(ds);
5826

    
5827
    dcl = ds->listeners;
5828
    while (dcl != NULL) {
5829
        if (dcl->dpy_refresh != NULL) {
5830
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5831
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5832
        }
5833
        dcl = dcl->next;
5834
    }
5835

    
5836
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
5837
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5838
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5839
    }
5840

    
5841
    text_consoles_set_display(display_state);
5842
    qemu_chr_initial_reset();
5843

    
5844
    for (i = 0; i < MAX_MONITOR_DEVICES; i++) {
5845
        if (monitor_devices[i] && monitor_hds[i]) {
5846
            monitor_init(monitor_hds[i],
5847
                         MONITOR_USE_READLINE |
5848
                         ((i == 0) ? MONITOR_IS_DEFAULT : 0));
5849
        }
5850
    }
5851

    
5852
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5853
        const char *devname = serial_devices[i];
5854
        if (devname && strcmp(devname, "none")) {
5855
            if (strstart(devname, "vc", 0))
5856
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5857
        }
5858
    }
5859

    
5860
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5861
        const char *devname = parallel_devices[i];
5862
        if (devname && strcmp(devname, "none")) {
5863
            if (strstart(devname, "vc", 0))
5864
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5865
        }
5866
    }
5867

    
5868
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5869
        const char *devname = virtio_consoles[i];
5870
        if (virtcon_hds[i] && devname) {
5871
            if (strstart(devname, "vc", 0))
5872
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5873
        }
5874
    }
5875

    
5876
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5877
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5878
                gdbstub_dev);
5879
        exit(1);
5880
    }
5881

    
5882
    if (loadvm) {
5883
        if (load_vmstate(cur_mon, loadvm) < 0) {
5884
            autostart = 0;
5885
        }
5886
    }
5887

    
5888
    if (incoming) {
5889
        qemu_start_incoming_migration(incoming);
5890
    } else if (autostart) {
5891
        vm_start();
5892
    }
5893

    
5894
#ifndef _WIN32
5895
    if (daemonize) {
5896
        uint8_t status = 0;
5897
        ssize_t len;
5898

    
5899
    again1:
5900
        len = write(fds[1], &status, 1);
5901
        if (len == -1 && (errno == EINTR))
5902
            goto again1;
5903

    
5904
        if (len != 1)
5905
            exit(1);
5906

    
5907
        chdir("/");
5908
        TFR(fd = open("/dev/null", O_RDWR));
5909
        if (fd == -1)
5910
            exit(1);
5911
    }
5912

    
5913
    if (run_as) {
5914
        pwd = getpwnam(run_as);
5915
        if (!pwd) {
5916
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5917
            exit(1);
5918
        }
5919
    }
5920

    
5921
    if (chroot_dir) {
5922
        if (chroot(chroot_dir) < 0) {
5923
            fprintf(stderr, "chroot failed\n");
5924
            exit(1);
5925
        }
5926
        chdir("/");
5927
    }
5928

    
5929
    if (run_as) {
5930
        if (setgid(pwd->pw_gid) < 0) {
5931
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5932
            exit(1);
5933
        }
5934
        if (setuid(pwd->pw_uid) < 0) {
5935
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5936
            exit(1);
5937
        }
5938
        if (setuid(0) != -1) {
5939
            fprintf(stderr, "Dropping privileges failed\n");
5940
            exit(1);
5941
        }
5942
    }
5943

    
5944
    if (daemonize) {
5945
        dup2(fd, 0);
5946
        dup2(fd, 1);
5947
        dup2(fd, 2);
5948

    
5949
        close(fd);
5950
    }
5951
#endif
5952

    
5953
    main_loop();
5954
    quit_timers();
5955
    net_cleanup();
5956

    
5957
    return 0;
5958
}