Statistics
| Branch: | Revision:

root / vl.c @ bd3c948d

History | View | Annotate | Download (155.9 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 HOST_BSD etc. */
33
#include "config-host.h"
34
/* Needed early to override system queue definitions on BSD */
35
#include "sys-queue.h"
36

    
37
#ifndef _WIN32
38
#include <libgen.h>
39
#include <pwd.h>
40
#include <sys/times.h>
41
#include <sys/wait.h>
42
#include <termios.h>
43
#include <sys/mman.h>
44
#include <sys/ioctl.h>
45
#include <sys/resource.h>
46
#include <sys/socket.h>
47
#include <netinet/in.h>
48
#include <net/if.h>
49
#if defined(__NetBSD__)
50
#include <net/if_tap.h>
51
#endif
52
#ifdef __linux__
53
#include <linux/if_tun.h>
54
#endif
55
#include <arpa/inet.h>
56
#include <dirent.h>
57
#include <netdb.h>
58
#include <sys/select.h>
59
#ifdef HOST_BSD
60
#include <sys/stat.h>
61
#if defined(__FreeBSD__) || defined(__DragonFly__)
62
#include <libutil.h>
63
#else
64
#include <util.h>
65
#endif
66
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
67
#include <freebsd/stdlib.h>
68
#else
69
#ifdef __linux__
70
#include <pty.h>
71
#include <malloc.h>
72
#include <linux/rtc.h>
73
#include <sys/prctl.h>
74

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

    
80
#include <linux/ppdev.h>
81
#include <linux/parport.h>
82
#endif
83
#ifdef __sun__
84
#include <sys/stat.h>
85
#include <sys/ethernet.h>
86
#include <sys/sockio.h>
87
#include <netinet/arp.h>
88
#include <netinet/in.h>
89
#include <netinet/in_systm.h>
90
#include <netinet/ip.h>
91
#include <netinet/ip_icmp.h> // must come after ip.h
92
#include <netinet/udp.h>
93
#include <netinet/tcp.h>
94
#include <net/if.h>
95
#include <syslog.h>
96
#include <stropts.h>
97
#endif
98
#endif
99
#endif
100

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

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

    
109
#ifdef _WIN32
110
#include <windows.h>
111
#include <malloc.h>
112
#include <sys/timeb.h>
113
#include <mmsystem.h>
114
#define getopt_long_only getopt_long
115
#define memalign(align, size) malloc(size)
116
#endif
117

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

    
131
#ifdef CONFIG_COCOA
132
#undef main
133
#define main qemu_main
134
#endif /* CONFIG_COCOA */
135

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

    
166
#include "disas.h"
167

    
168
#include "exec-all.h"
169

    
170
#include "qemu_socket.h"
171

    
172
#include "slirp/libslirp.h"
173

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

    
177
#define DEFAULT_RAM_SIZE 128
178

    
179
static const char *data_dir;
180
const char *bios_name = NULL;
181
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
182
   to store the VM snapshots */
183
DriveInfo drives_table[MAX_DRIVES+1];
184
int nb_drives;
185
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
186
static DisplayState *display_state;
187
DisplayType display_type = DT_DEFAULT;
188
const char* keyboard_layout = NULL;
189
int64_t ticks_per_sec;
190
ram_addr_t ram_size;
191
int nb_nics;
192
NICInfo nd_table[MAX_NICS];
193
int vm_running;
194
static int autostart;
195
static int rtc_utc = 1;
196
static int rtc_date_offset = -1; /* -1 means no change */
197
int cirrus_vga_enabled = 1;
198
int std_vga_enabled = 0;
199
int vmsvga_enabled = 0;
200
int xenfb_enabled = 0;
201
#ifdef TARGET_SPARC
202
int graphic_width = 1024;
203
int graphic_height = 768;
204
int graphic_depth = 8;
205
#else
206
int graphic_width = 800;
207
int graphic_height = 600;
208
int graphic_depth = 15;
209
#endif
210
static int full_screen = 0;
211
#ifdef CONFIG_SDL
212
static int no_frame = 0;
213
#endif
214
int no_quit = 0;
215
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
216
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
217
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
218
#ifdef TARGET_I386
219
int win2k_install_hack = 0;
220
int rtc_td_hack = 0;
221
#endif
222
int usb_enabled = 0;
223
int singlestep = 0;
224
int smp_cpus = 1;
225
const char *vnc_display;
226
int acpi_enabled = 1;
227
int no_hpet = 0;
228
int virtio_balloon = 1;
229
const char *virtio_balloon_devaddr;
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
#ifndef _WIN32
236
int daemonize = 0;
237
#endif
238
WatchdogTimerModel *watchdog = NULL;
239
int watchdog_action = WDT_RESET;
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 nb_drives_opt;
253
struct drive_opt drives_opt[MAX_DRIVES];
254
int boot_menu;
255

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

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

    
273
uint8_t qemu_uuid[16];
274

    
275
static QEMUBootSetHandler *boot_set_handler;
276
static void *boot_set_opaque;
277

    
278
/***********************************************************/
279
/* x86 ISA bus support */
280

    
281
target_phys_addr_t isa_mem_base = 0;
282
PicState2 *isa_pic;
283

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

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

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

    
323
static QEMUBalloonEvent *qemu_balloon_event;
324
void *qemu_balloon_event_opaque;
325

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

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

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

    
345
/***********************************************************/
346
/* keyboard/mouse */
347

    
348
static QEMUPutKBDEvent *qemu_put_kbd_event;
349
static void *qemu_put_kbd_event_opaque;
350
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
351
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
352

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

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

    
365
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
366

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

    
373
    if (!qemu_put_mouse_event_head) {
374
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
375
        return s;
376
    }
377

    
378
    cursor = qemu_put_mouse_event_head;
379
    while (cursor->next != NULL)
380
        cursor = cursor->next;
381

    
382
    cursor->next = s;
383
    qemu_put_mouse_event_current = s;
384

    
385
    return s;
386
}
387

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

    
392
    if (!qemu_put_mouse_event_head || entry == NULL)
393
        return;
394

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

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

    
412
    prev->next = entry->next;
413

    
414
    if (qemu_put_mouse_event_current == entry)
415
        qemu_put_mouse_event_current = prev;
416

    
417
    qemu_free(entry->qemu_put_mouse_event_name);
418
    qemu_free(entry);
419
}
420

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

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

    
434
    if (!qemu_put_mouse_event_current) {
435
        return;
436
    }
437

    
438
    mouse_event =
439
        qemu_put_mouse_event_current->qemu_put_mouse_event;
440
    mouse_event_opaque =
441
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
442

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

    
457
int kbd_mouse_is_absolute(void)
458
{
459
    if (!qemu_put_mouse_event_current)
460
        return 0;
461

    
462
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
463
}
464

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

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

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

    
486
void do_mouse_set(Monitor *mon, int index)
487
{
488
    QEMUPutMouseEntry *cursor;
489
    int i = 0;
490

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

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

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

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

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

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

    
535
#define QEMU_TIMER_BASE 1000000000LL
536

    
537
#ifdef WIN32
538

    
539
static int64_t clock_freq;
540

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

    
553
static int64_t get_clock(void)
554
{
555
    LARGE_INTEGER ti;
556
    QueryPerformanceCounter(&ti);
557
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
558
}
559

    
560
#else
561

    
562
static int use_rt_clock;
563

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

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

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

    
612
/***********************************************************/
613
/* guest cycle counter */
614

    
615
static int64_t cpu_ticks_prev;
616
static int64_t cpu_ticks_offset;
617
static int64_t cpu_clock_offset;
618
static int cpu_ticks_enabled;
619

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

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

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

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

    
674
/***********************************************************/
675
/* timers */
676

    
677
#define QEMU_TIMER_REALTIME 0
678
#define QEMU_TIMER_VIRTUAL  1
679

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

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

    
693
struct qemu_alarm_timer {
694
    char const *name;
695
    unsigned int flags;
696

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

    
703
#define ALARM_FLAG_DYNTICKS  0x1
704
#define ALARM_FLAG_EXPIRED   0x2
705

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

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

    
716
    t->rearm(t);
717
}
718

    
719
/* TODO: MIN_TIMER_REARM_US should be optimized */
720
#define MIN_TIMER_REARM_US 250
721

    
722
static struct qemu_alarm_timer *alarm_timer;
723

    
724
#ifdef _WIN32
725

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

    
731
static int win32_start_timer(struct qemu_alarm_timer *t);
732
static void win32_stop_timer(struct qemu_alarm_timer *t);
733
static void win32_rearm_timer(struct qemu_alarm_timer *t);
734

    
735
#else
736

    
737
static int unix_start_timer(struct qemu_alarm_timer *t);
738
static void unix_stop_timer(struct qemu_alarm_timer *t);
739

    
740
#ifdef __linux__
741

    
742
static int dynticks_start_timer(struct qemu_alarm_timer *t);
743
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
744
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
745

    
746
static int hpet_start_timer(struct qemu_alarm_timer *t);
747
static void hpet_stop_timer(struct qemu_alarm_timer *t);
748

    
749
static int rtc_start_timer(struct qemu_alarm_timer *t);
750
static void rtc_stop_timer(struct qemu_alarm_timer *t);
751

    
752
#endif /* __linux__ */
753

    
754
#endif /* _WIN32 */
755

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

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

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

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

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

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

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

    
841
static void show_available_alarms(void)
842
{
843
    int i;
844

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

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

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

    
864
    arg = strdup(opt);
865

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

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

    
879
        if (i < cur)
880
            /* Ignore */
881
            goto next;
882

    
883
        /* Swap */
884
        tmp = alarm_timers[i];
885
        alarm_timers[i] = alarm_timers[cur];
886
        alarm_timers[cur] = tmp;
887

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

    
893
    free(arg);
894

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

    
905
QEMUClock *rt_clock;
906
QEMUClock *vm_clock;
907

    
908
static QEMUTimer *active_timers[2];
909

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

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

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

    
929
void qemu_free_timer(QEMUTimer *ts)
930
{
931
    qemu_free(ts);
932
}
933

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

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

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

    
960
    qemu_del_timer(ts);
961

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

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

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

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

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

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

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

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

    
1038
static void init_timers(void)
1039
{
1040
    init_get_clock();
1041
    ticks_per_sec = QEMU_TIMER_BASE;
1042
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1043
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1044
}
1045

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

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

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

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

    
1071
static void timer_save(QEMUFile *f, void *opaque)
1072
{
1073
    if (cpu_ticks_enabled) {
1074
        hw_error("cannot save state if virtual timers are running");
1075
    }
1076
    qemu_put_be64(f, cpu_ticks_offset);
1077
    qemu_put_be64(f, ticks_per_sec);
1078
    qemu_put_be64(f, cpu_clock_offset);
1079
}
1080

    
1081
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1082
{
1083
    if (version_id != 1 && version_id != 2)
1084
        return -EINVAL;
1085
    if (cpu_ticks_enabled) {
1086
        return -EINVAL;
1087
    }
1088
    cpu_ticks_offset=qemu_get_be64(f);
1089
    ticks_per_sec=qemu_get_be64(f);
1090
    if (version_id == 2) {
1091
        cpu_clock_offset=qemu_get_be64(f);
1092
    }
1093
    return 0;
1094
}
1095

    
1096
static void qemu_event_increment(void);
1097

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

    
1144
#ifndef CONFIG_IOTHREAD
1145
        if (next_cpu) {
1146
            /* stop the currently executing cpu because a timer occured */
1147
            cpu_exit(next_cpu);
1148
#ifdef CONFIG_KQEMU
1149
            if (next_cpu->kqemu_enabled) {
1150
                kqemu_cpu_interrupt(next_cpu);
1151
            }
1152
#endif
1153
        }
1154
#endif
1155
        timer_alarm_pending = 1;
1156
        qemu_notify_event();
1157
    }
1158
}
1159

    
1160
static int64_t qemu_next_deadline(void)
1161
{
1162
    int64_t delta;
1163

    
1164
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1165
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1166
                     qemu_get_clock(vm_clock);
1167
    } else {
1168
        /* To avoid problems with overflow limit this to 2^32.  */
1169
        delta = INT32_MAX;
1170
    }
1171

    
1172
    if (delta < 0)
1173
        delta = 0;
1174

    
1175
    return delta;
1176
}
1177

    
1178
#if defined(__linux__) || defined(_WIN32)
1179
static uint64_t qemu_next_deadline_dyntick(void)
1180
{
1181
    int64_t delta;
1182
    int64_t rtdelta;
1183

    
1184
    if (use_icount)
1185
        delta = INT32_MAX;
1186
    else
1187
        delta = (qemu_next_deadline() + 999) / 1000;
1188

    
1189
    if (active_timers[QEMU_TIMER_REALTIME]) {
1190
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1191
                 qemu_get_clock(rt_clock))*1000;
1192
        if (rtdelta < delta)
1193
            delta = rtdelta;
1194
    }
1195

    
1196
    if (delta < MIN_TIMER_REARM_US)
1197
        delta = MIN_TIMER_REARM_US;
1198

    
1199
    return delta;
1200
}
1201
#endif
1202

    
1203
#ifndef _WIN32
1204

    
1205
/* Sets a specific flag */
1206
static int fcntl_setfl(int fd, int flag)
1207
{
1208
    int flags;
1209

    
1210
    flags = fcntl(fd, F_GETFL);
1211
    if (flags == -1)
1212
        return -errno;
1213

    
1214
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1215
        return -errno;
1216

    
1217
    return 0;
1218
}
1219

    
1220
#if defined(__linux__)
1221

    
1222
#define RTC_FREQ 1024
1223

    
1224
static void enable_sigio_timer(int fd)
1225
{
1226
    struct sigaction act;
1227

    
1228
    /* timer signal */
1229
    sigfillset(&act.sa_mask);
1230
    act.sa_flags = 0;
1231
    act.sa_handler = host_alarm_handler;
1232

    
1233
    sigaction(SIGIO, &act, NULL);
1234
    fcntl_setfl(fd, O_ASYNC);
1235
    fcntl(fd, F_SETOWN, getpid());
1236
}
1237

    
1238
static int hpet_start_timer(struct qemu_alarm_timer *t)
1239
{
1240
    struct hpet_info info;
1241
    int r, fd;
1242

    
1243
    fd = open("/dev/hpet", O_RDONLY);
1244
    if (fd < 0)
1245
        return -1;
1246

    
1247
    /* Set frequency */
1248
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1249
    if (r < 0) {
1250
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1251
                "error, but for better emulation accuracy type:\n"
1252
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1253
        goto fail;
1254
    }
1255

    
1256
    /* Check capabilities */
1257
    r = ioctl(fd, HPET_INFO, &info);
1258
    if (r < 0)
1259
        goto fail;
1260

    
1261
    /* Enable periodic mode */
1262
    r = ioctl(fd, HPET_EPI, 0);
1263
    if (info.hi_flags && (r < 0))
1264
        goto fail;
1265

    
1266
    /* Enable interrupt */
1267
    r = ioctl(fd, HPET_IE_ON, 0);
1268
    if (r < 0)
1269
        goto fail;
1270

    
1271
    enable_sigio_timer(fd);
1272
    t->priv = (void *)(long)fd;
1273

    
1274
    return 0;
1275
fail:
1276
    close(fd);
1277
    return -1;
1278
}
1279

    
1280
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1281
{
1282
    int fd = (long)t->priv;
1283

    
1284
    close(fd);
1285
}
1286

    
1287
static int rtc_start_timer(struct qemu_alarm_timer *t)
1288
{
1289
    int rtc_fd;
1290
    unsigned long current_rtc_freq = 0;
1291

    
1292
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1293
    if (rtc_fd < 0)
1294
        return -1;
1295
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1296
    if (current_rtc_freq != RTC_FREQ &&
1297
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1298
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1299
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1300
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1301
        goto fail;
1302
    }
1303
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1304
    fail:
1305
        close(rtc_fd);
1306
        return -1;
1307
    }
1308

    
1309
    enable_sigio_timer(rtc_fd);
1310

    
1311
    t->priv = (void *)(long)rtc_fd;
1312

    
1313
    return 0;
1314
}
1315

    
1316
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1317
{
1318
    int rtc_fd = (long)t->priv;
1319

    
1320
    close(rtc_fd);
1321
}
1322

    
1323
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1324
{
1325
    struct sigevent ev;
1326
    timer_t host_timer;
1327
    struct sigaction act;
1328

    
1329
    sigfillset(&act.sa_mask);
1330
    act.sa_flags = 0;
1331
    act.sa_handler = host_alarm_handler;
1332

    
1333
    sigaction(SIGALRM, &act, NULL);
1334

    
1335
    /* 
1336
     * Initialize ev struct to 0 to avoid valgrind complaining
1337
     * about uninitialized data in timer_create call
1338
     */
1339
    memset(&ev, 0, sizeof(ev));
1340
    ev.sigev_value.sival_int = 0;
1341
    ev.sigev_notify = SIGEV_SIGNAL;
1342
    ev.sigev_signo = SIGALRM;
1343

    
1344
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1345
        perror("timer_create");
1346

    
1347
        /* disable dynticks */
1348
        fprintf(stderr, "Dynamic Ticks disabled\n");
1349

    
1350
        return -1;
1351
    }
1352

    
1353
    t->priv = (void *)(long)host_timer;
1354

    
1355
    return 0;
1356
}
1357

    
1358
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1359
{
1360
    timer_t host_timer = (timer_t)(long)t->priv;
1361

    
1362
    timer_delete(host_timer);
1363
}
1364

    
1365
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1366
{
1367
    timer_t host_timer = (timer_t)(long)t->priv;
1368
    struct itimerspec timeout;
1369
    int64_t nearest_delta_us = INT64_MAX;
1370
    int64_t current_us;
1371

    
1372
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1373
                !active_timers[QEMU_TIMER_VIRTUAL])
1374
        return;
1375

    
1376
    nearest_delta_us = qemu_next_deadline_dyntick();
1377

    
1378
    /* check whether a timer is already running */
1379
    if (timer_gettime(host_timer, &timeout)) {
1380
        perror("gettime");
1381
        fprintf(stderr, "Internal timer error: aborting\n");
1382
        exit(1);
1383
    }
1384
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1385
    if (current_us && current_us <= nearest_delta_us)
1386
        return;
1387

    
1388
    timeout.it_interval.tv_sec = 0;
1389
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1390
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1391
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1392
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1393
        perror("settime");
1394
        fprintf(stderr, "Internal timer error: aborting\n");
1395
        exit(1);
1396
    }
1397
}
1398

    
1399
#endif /* defined(__linux__) */
1400

    
1401
static int unix_start_timer(struct qemu_alarm_timer *t)
1402
{
1403
    struct sigaction act;
1404
    struct itimerval itv;
1405
    int err;
1406

    
1407
    /* timer signal */
1408
    sigfillset(&act.sa_mask);
1409
    act.sa_flags = 0;
1410
    act.sa_handler = host_alarm_handler;
1411

    
1412
    sigaction(SIGALRM, &act, NULL);
1413

    
1414
    itv.it_interval.tv_sec = 0;
1415
    /* for i386 kernel 2.6 to get 1 ms */
1416
    itv.it_interval.tv_usec = 999;
1417
    itv.it_value.tv_sec = 0;
1418
    itv.it_value.tv_usec = 10 * 1000;
1419

    
1420
    err = setitimer(ITIMER_REAL, &itv, NULL);
1421
    if (err)
1422
        return -1;
1423

    
1424
    return 0;
1425
}
1426

    
1427
static void unix_stop_timer(struct qemu_alarm_timer *t)
1428
{
1429
    struct itimerval itv;
1430

    
1431
    memset(&itv, 0, sizeof(itv));
1432
    setitimer(ITIMER_REAL, &itv, NULL);
1433
}
1434

    
1435
#endif /* !defined(_WIN32) */
1436

    
1437

    
1438
#ifdef _WIN32
1439

    
1440
static int win32_start_timer(struct qemu_alarm_timer *t)
1441
{
1442
    TIMECAPS tc;
1443
    struct qemu_alarm_win32 *data = t->priv;
1444
    UINT flags;
1445

    
1446
    memset(&tc, 0, sizeof(tc));
1447
    timeGetDevCaps(&tc, sizeof(tc));
1448

    
1449
    if (data->period < tc.wPeriodMin)
1450
        data->period = tc.wPeriodMin;
1451

    
1452
    timeBeginPeriod(data->period);
1453

    
1454
    flags = TIME_CALLBACK_FUNCTION;
1455
    if (alarm_has_dynticks(t))
1456
        flags |= TIME_ONESHOT;
1457
    else
1458
        flags |= TIME_PERIODIC;
1459

    
1460
    data->timerId = timeSetEvent(1,         // interval (ms)
1461
                        data->period,       // resolution
1462
                        host_alarm_handler, // function
1463
                        (DWORD)t,           // parameter
1464
                        flags);
1465

    
1466
    if (!data->timerId) {
1467
        perror("Failed to initialize win32 alarm timer");
1468
        timeEndPeriod(data->period);
1469
        return -1;
1470
    }
1471

    
1472
    return 0;
1473
}
1474

    
1475
static void win32_stop_timer(struct qemu_alarm_timer *t)
1476
{
1477
    struct qemu_alarm_win32 *data = t->priv;
1478

    
1479
    timeKillEvent(data->timerId);
1480
    timeEndPeriod(data->period);
1481
}
1482

    
1483
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1484
{
1485
    struct qemu_alarm_win32 *data = t->priv;
1486
    uint64_t nearest_delta_us;
1487

    
1488
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1489
                !active_timers[QEMU_TIMER_VIRTUAL])
1490
        return;
1491

    
1492
    nearest_delta_us = qemu_next_deadline_dyntick();
1493
    nearest_delta_us /= 1000;
1494

    
1495
    timeKillEvent(data->timerId);
1496

    
1497
    data->timerId = timeSetEvent(1,
1498
                        data->period,
1499
                        host_alarm_handler,
1500
                        (DWORD)t,
1501
                        TIME_ONESHOT | TIME_PERIODIC);
1502

    
1503
    if (!data->timerId) {
1504
        perror("Failed to re-arm win32 alarm timer");
1505

    
1506
        timeEndPeriod(data->period);
1507
        exit(1);
1508
    }
1509
}
1510

    
1511
#endif /* _WIN32 */
1512

    
1513
static int init_timer_alarm(void)
1514
{
1515
    struct qemu_alarm_timer *t = NULL;
1516
    int i, err = -1;
1517

    
1518
    for (i = 0; alarm_timers[i].name; i++) {
1519
        t = &alarm_timers[i];
1520

    
1521
        err = t->start(t);
1522
        if (!err)
1523
            break;
1524
    }
1525

    
1526
    if (err) {
1527
        err = -ENOENT;
1528
        goto fail;
1529
    }
1530

    
1531
    alarm_timer = t;
1532

    
1533
    return 0;
1534

    
1535
fail:
1536
    return err;
1537
}
1538

    
1539
static void quit_timers(void)
1540
{
1541
    alarm_timer->stop(alarm_timer);
1542
    alarm_timer = NULL;
1543
}
1544

    
1545
/***********************************************************/
1546
/* host time/date access */
1547
void qemu_get_timedate(struct tm *tm, int offset)
1548
{
1549
    time_t ti;
1550
    struct tm *ret;
1551

    
1552
    time(&ti);
1553
    ti += offset;
1554
    if (rtc_date_offset == -1) {
1555
        if (rtc_utc)
1556
            ret = gmtime(&ti);
1557
        else
1558
            ret = localtime(&ti);
1559
    } else {
1560
        ti -= rtc_date_offset;
1561
        ret = gmtime(&ti);
1562
    }
1563

    
1564
    memcpy(tm, ret, sizeof(struct tm));
1565
}
1566

    
1567
int qemu_timedate_diff(struct tm *tm)
1568
{
1569
    time_t seconds;
1570

    
1571
    if (rtc_date_offset == -1)
1572
        if (rtc_utc)
1573
            seconds = mktimegm(tm);
1574
        else
1575
            seconds = mktime(tm);
1576
    else
1577
        seconds = mktimegm(tm) + rtc_date_offset;
1578

    
1579
    return seconds - time(NULL);
1580
}
1581

    
1582
#ifdef _WIN32
1583
static void socket_cleanup(void)
1584
{
1585
    WSACleanup();
1586
}
1587

    
1588
static int socket_init(void)
1589
{
1590
    WSADATA Data;
1591
    int ret, err;
1592

    
1593
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1594
    if (ret != 0) {
1595
        err = WSAGetLastError();
1596
        fprintf(stderr, "WSAStartup: %d\n", err);
1597
        return -1;
1598
    }
1599
    atexit(socket_cleanup);
1600
    return 0;
1601
}
1602
#endif
1603

    
1604
int get_next_param_value(char *buf, int buf_size,
1605
                         const char *tag, const char **pstr)
1606
{
1607
    const char *p;
1608
    char option[128];
1609

    
1610
    p = *pstr;
1611
    for(;;) {
1612
        p = get_opt_name(option, sizeof(option), p, '=');
1613
        if (*p != '=')
1614
            break;
1615
        p++;
1616
        if (!strcmp(tag, option)) {
1617
            *pstr = get_opt_value(buf, buf_size, p);
1618
            if (**pstr == ',') {
1619
                (*pstr)++;
1620
            }
1621
            return strlen(buf);
1622
        } else {
1623
            p = get_opt_value(NULL, 0, p);
1624
        }
1625
        if (*p != ',')
1626
            break;
1627
        p++;
1628
    }
1629
    return 0;
1630
}
1631

    
1632
int get_param_value(char *buf, int buf_size,
1633
                    const char *tag, const char *str)
1634
{
1635
    return get_next_param_value(buf, buf_size, tag, &str);
1636
}
1637

    
1638
int check_params(char *buf, int buf_size,
1639
                 const char * const *params, const char *str)
1640
{
1641
    const char *p;
1642
    int i;
1643

    
1644
    p = str;
1645
    while (*p != '\0') {
1646
        p = get_opt_name(buf, buf_size, p, '=');
1647
        if (*p != '=') {
1648
            return -1;
1649
        }
1650
        p++;
1651
        for (i = 0; params[i] != NULL; i++) {
1652
            if (!strcmp(params[i], buf)) {
1653
                break;
1654
            }
1655
        }
1656
        if (params[i] == NULL) {
1657
            return -1;
1658
        }
1659
        p = get_opt_value(NULL, 0, p);
1660
        if (*p != ',') {
1661
            break;
1662
        }
1663
        p++;
1664
    }
1665
    return 0;
1666
}
1667

    
1668
/***********************************************************/
1669
/* Bluetooth support */
1670
static int nb_hcis;
1671
static int cur_hci;
1672
static struct HCIInfo *hci_table[MAX_NICS];
1673

    
1674
static struct bt_vlan_s {
1675
    struct bt_scatternet_s net;
1676
    int id;
1677
    struct bt_vlan_s *next;
1678
} *first_bt_vlan;
1679

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

    
1697
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1698
{
1699
}
1700

    
1701
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1702
{
1703
    return -ENOTSUP;
1704
}
1705

    
1706
static struct HCIInfo null_hci = {
1707
    .cmd_send = null_hci_send,
1708
    .sco_send = null_hci_send,
1709
    .acl_send = null_hci_send,
1710
    .bdaddr_set = null_hci_addr_set,
1711
};
1712

    
1713
struct HCIInfo *qemu_next_hci(void)
1714
{
1715
    if (cur_hci == nb_hcis)
1716
        return &null_hci;
1717

    
1718
    return hci_table[cur_hci++];
1719
}
1720

    
1721
static struct HCIInfo *hci_init(const char *str)
1722
{
1723
    char *endp;
1724
    struct bt_scatternet_s *vlan = 0;
1725

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

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

    
1748
    return 0;
1749
}
1750

    
1751
static int bt_hci_parse(const char *str)
1752
{
1753
    struct HCIInfo *hci;
1754
    bdaddr_t bdaddr;
1755

    
1756
    if (nb_hcis >= MAX_NICS) {
1757
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1758
        return -1;
1759
    }
1760

    
1761
    hci = hci_init(str);
1762
    if (!hci)
1763
        return -1;
1764

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

    
1773
    hci_table[nb_hcis++] = hci;
1774

    
1775
    return 0;
1776
}
1777

    
1778
static void bt_vhci_add(int vlan_id)
1779
{
1780
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1781

    
1782
    if (!vlan->slave)
1783
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1784
                        "an empty scatternet %i\n", vlan_id);
1785

    
1786
    bt_vhci_init(bt_new_hci(vlan));
1787
}
1788

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

    
1797
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1798

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

    
1807
    vlan = qemu_find_bt_vlan(vlan_id);
1808

    
1809
    if (!vlan->slave)
1810
        fprintf(stderr, "qemu: warning: adding a slave device to "
1811
                        "an empty scatternet %i\n", vlan_id);
1812

    
1813
    if (!strcmp(devname, "keyboard"))
1814
        return bt_keyboard_init(vlan);
1815

    
1816
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1817
    return 0;
1818
}
1819

    
1820
static int bt_parse(const char *opt)
1821
{
1822
    const char *endp, *p;
1823
    int vlan;
1824

    
1825
    if (strstart(opt, "hci", &endp)) {
1826
        if (!*endp || *endp == ',') {
1827
            if (*endp)
1828
                if (!strstart(endp, ",vlan=", 0))
1829
                    opt = endp + 1;
1830

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

    
1849
            bt_vhci_add(vlan);
1850
            return 0;
1851
        }
1852
    } else if (strstart(opt, "device:", &endp))
1853
        return !bt_device_add(endp);
1854

    
1855
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1856
    return 1;
1857
}
1858

    
1859
/***********************************************************/
1860
/* QEMU Block devices */
1861

    
1862
#define HD_ALIAS "index=%d,media=disk"
1863
#define CDROM_ALIAS "index=2,media=cdrom"
1864
#define FD_ALIAS "index=%d,if=floppy"
1865
#define PFLASH_ALIAS "if=pflash"
1866
#define MTD_ALIAS "if=mtd"
1867
#define SD_ALIAS "index=0,if=sd"
1868

    
1869
static int drive_opt_get_free_idx(void)
1870
{
1871
    int index;
1872

    
1873
    for (index = 0; index < MAX_DRIVES; index++)
1874
        if (!drives_opt[index].used) {
1875
            drives_opt[index].used = 1;
1876
            return index;
1877
        }
1878

    
1879
    return -1;
1880
}
1881

    
1882
static int drive_get_free_idx(void)
1883
{
1884
    int index;
1885

    
1886
    for (index = 0; index < MAX_DRIVES; index++)
1887
        if (!drives_table[index].used) {
1888
            drives_table[index].used = 1;
1889
            return index;
1890
        }
1891

    
1892
    return -1;
1893
}
1894

    
1895
int drive_add(const char *file, const char *fmt, ...)
1896
{
1897
    va_list ap;
1898
    int index = drive_opt_get_free_idx();
1899

    
1900
    if (nb_drives_opt >= MAX_DRIVES || index == -1) {
1901
        fprintf(stderr, "qemu: too many drives\n");
1902
        return -1;
1903
    }
1904

    
1905
    drives_opt[index].file = file;
1906
    va_start(ap, fmt);
1907
    vsnprintf(drives_opt[index].opt,
1908
              sizeof(drives_opt[0].opt), fmt, ap);
1909
    va_end(ap);
1910

    
1911
    nb_drives_opt++;
1912
    return index;
1913
}
1914

    
1915
void drive_remove(int index)
1916
{
1917
    drives_opt[index].used = 0;
1918
    nb_drives_opt--;
1919
}
1920

    
1921
int drive_get_index(BlockInterfaceType type, int bus, int unit)
1922
{
1923
    int index;
1924

    
1925
    /* seek interface, bus and unit */
1926

    
1927
    for (index = 0; index < MAX_DRIVES; index++)
1928
        if (drives_table[index].type == type &&
1929
            drives_table[index].bus == bus &&
1930
            drives_table[index].unit == unit &&
1931
            drives_table[index].used)
1932
        return index;
1933

    
1934
    return -1;
1935
}
1936

    
1937
int drive_get_max_bus(BlockInterfaceType type)
1938
{
1939
    int max_bus;
1940
    int index;
1941

    
1942
    max_bus = -1;
1943
    for (index = 0; index < nb_drives; index++) {
1944
        if(drives_table[index].type == type &&
1945
           drives_table[index].bus > max_bus)
1946
            max_bus = drives_table[index].bus;
1947
    }
1948
    return max_bus;
1949
}
1950

    
1951
const char *drive_get_serial(BlockDriverState *bdrv)
1952
{
1953
    int index;
1954

    
1955
    for (index = 0; index < nb_drives; index++)
1956
        if (drives_table[index].bdrv == bdrv)
1957
            return drives_table[index].serial;
1958

    
1959
    return "\0";
1960
}
1961

    
1962
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1963
{
1964
    int index;
1965

    
1966
    for (index = 0; index < nb_drives; index++)
1967
        if (drives_table[index].bdrv == bdrv)
1968
            return drives_table[index].onerror;
1969

    
1970
    return BLOCK_ERR_STOP_ENOSPC;
1971
}
1972

    
1973
static void bdrv_format_print(void *opaque, const char *name)
1974
{
1975
    fprintf(stderr, " %s", name);
1976
}
1977

    
1978
void drive_uninit(BlockDriverState *bdrv)
1979
{
1980
    int i;
1981

    
1982
    for (i = 0; i < MAX_DRIVES; i++)
1983
        if (drives_table[i].bdrv == bdrv) {
1984
            drives_table[i].bdrv = NULL;
1985
            drives_table[i].used = 0;
1986
            drive_remove(drives_table[i].drive_opt_idx);
1987
            nb_drives--;
1988
            break;
1989
        }
1990
}
1991

    
1992
int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
1993
{
1994
    char buf[128];
1995
    char file[1024];
1996
    char devname[128];
1997
    char serial[21];
1998
    const char *mediastr = "";
1999
    BlockInterfaceType type;
2000
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2001
    int bus_id, unit_id;
2002
    int cyls, heads, secs, translation;
2003
    BlockDriverState *bdrv;
2004
    BlockDriver *drv = NULL;
2005
    QEMUMachine *machine = opaque;
2006
    int max_devs;
2007
    int index;
2008
    int cache;
2009
    int bdrv_flags, onerror;
2010
    const char *devaddr;
2011
    int drives_table_idx;
2012
    char *str = arg->opt;
2013
    static const char * const params[] = { "bus", "unit", "if", "index",
2014
                                           "cyls", "heads", "secs", "trans",
2015
                                           "media", "snapshot", "file",
2016
                                           "cache", "format", "serial",
2017
                                           "werror", "addr",
2018
                                           NULL };
2019

    
2020
    if (check_params(buf, sizeof(buf), params, str) < 0) {
2021
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2022
                         buf, str);
2023
         return -1;
2024
    }
2025

    
2026
    file[0] = 0;
2027
    cyls = heads = secs = 0;
2028
    bus_id = 0;
2029
    unit_id = -1;
2030
    translation = BIOS_ATA_TRANSLATION_AUTO;
2031
    index = -1;
2032
    cache = 1;
2033

    
2034
    if (machine->use_scsi) {
2035
        type = IF_SCSI;
2036
        max_devs = MAX_SCSI_DEVS;
2037
        pstrcpy(devname, sizeof(devname), "scsi");
2038
    } else {
2039
        type = IF_IDE;
2040
        max_devs = MAX_IDE_DEVS;
2041
        pstrcpy(devname, sizeof(devname), "ide");
2042
    }
2043
    media = MEDIA_DISK;
2044

    
2045
    /* extract parameters */
2046

    
2047
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2048
        bus_id = strtol(buf, NULL, 0);
2049
        if (bus_id < 0) {
2050
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2051
            return -1;
2052
        }
2053
    }
2054

    
2055
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2056
        unit_id = strtol(buf, NULL, 0);
2057
        if (unit_id < 0) {
2058
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2059
            return -1;
2060
        }
2061
    }
2062

    
2063
    if (get_param_value(buf, sizeof(buf), "if", str)) {
2064
        pstrcpy(devname, sizeof(devname), buf);
2065
        if (!strcmp(buf, "ide")) {
2066
            type = IF_IDE;
2067
            max_devs = MAX_IDE_DEVS;
2068
        } else if (!strcmp(buf, "scsi")) {
2069
            type = IF_SCSI;
2070
            max_devs = MAX_SCSI_DEVS;
2071
        } else if (!strcmp(buf, "floppy")) {
2072
            type = IF_FLOPPY;
2073
            max_devs = 0;
2074
        } else if (!strcmp(buf, "pflash")) {
2075
            type = IF_PFLASH;
2076
            max_devs = 0;
2077
        } else if (!strcmp(buf, "mtd")) {
2078
            type = IF_MTD;
2079
            max_devs = 0;
2080
        } else if (!strcmp(buf, "sd")) {
2081
            type = IF_SD;
2082
            max_devs = 0;
2083
        } else if (!strcmp(buf, "virtio")) {
2084
            type = IF_VIRTIO;
2085
            max_devs = 0;
2086
        } else if (!strcmp(buf, "xen")) {
2087
            type = IF_XEN;
2088
            max_devs = 0;
2089
        } else {
2090
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2091
            return -1;
2092
        }
2093
    }
2094

    
2095
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2096
        index = strtol(buf, NULL, 0);
2097
        if (index < 0) {
2098
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2099
            return -1;
2100
        }
2101
    }
2102

    
2103
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2104
        cyls = strtol(buf, NULL, 0);
2105
    }
2106

    
2107
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2108
        heads = strtol(buf, NULL, 0);
2109
    }
2110

    
2111
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2112
        secs = strtol(buf, NULL, 0);
2113
    }
2114

    
2115
    if (cyls || heads || secs) {
2116
        if (cyls < 1 || cyls > 16383) {
2117
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2118
            return -1;
2119
        }
2120
        if (heads < 1 || heads > 16) {
2121
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2122
            return -1;
2123
        }
2124
        if (secs < 1 || secs > 63) {
2125
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2126
            return -1;
2127
        }
2128
    }
2129

    
2130
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2131
        if (!cyls) {
2132
            fprintf(stderr,
2133
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2134
                    str);
2135
            return -1;
2136
        }
2137
        if (!strcmp(buf, "none"))
2138
            translation = BIOS_ATA_TRANSLATION_NONE;
2139
        else if (!strcmp(buf, "lba"))
2140
            translation = BIOS_ATA_TRANSLATION_LBA;
2141
        else if (!strcmp(buf, "auto"))
2142
            translation = BIOS_ATA_TRANSLATION_AUTO;
2143
        else {
2144
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2145
            return -1;
2146
        }
2147
    }
2148

    
2149
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2150
        if (!strcmp(buf, "disk")) {
2151
            media = MEDIA_DISK;
2152
        } else if (!strcmp(buf, "cdrom")) {
2153
            if (cyls || secs || heads) {
2154
                fprintf(stderr,
2155
                        "qemu: '%s' invalid physical CHS format\n", str);
2156
                return -1;
2157
            }
2158
            media = MEDIA_CDROM;
2159
        } else {
2160
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2161
            return -1;
2162
        }
2163
    }
2164

    
2165
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2166
        if (!strcmp(buf, "on"))
2167
            snapshot = 1;
2168
        else if (!strcmp(buf, "off"))
2169
            snapshot = 0;
2170
        else {
2171
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2172
            return -1;
2173
        }
2174
    }
2175

    
2176
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2177
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2178
            cache = 0;
2179
        else if (!strcmp(buf, "writethrough"))
2180
            cache = 1;
2181
        else if (!strcmp(buf, "writeback"))
2182
            cache = 2;
2183
        else {
2184
           fprintf(stderr, "qemu: invalid cache option\n");
2185
           return -1;
2186
        }
2187
    }
2188

    
2189
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2190
       if (strcmp(buf, "?") == 0) {
2191
            fprintf(stderr, "qemu: Supported formats:");
2192
            bdrv_iterate_format(bdrv_format_print, NULL);
2193
            fprintf(stderr, "\n");
2194
            return -1;
2195
        }
2196
        drv = bdrv_find_format(buf);
2197
        if (!drv) {
2198
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2199
            return -1;
2200
        }
2201
    }
2202

    
2203
    if (arg->file == NULL)
2204
        get_param_value(file, sizeof(file), "file", str);
2205
    else
2206
        pstrcpy(file, sizeof(file), arg->file);
2207

    
2208
    if (!get_param_value(serial, sizeof(serial), "serial", str))
2209
            memset(serial, 0,  sizeof(serial));
2210

    
2211
    onerror = BLOCK_ERR_STOP_ENOSPC;
2212
    if (get_param_value(buf, sizeof(serial), "werror", str)) {
2213
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2214
            fprintf(stderr, "werror is no supported by this format\n");
2215
            return -1;
2216
        }
2217
        if (!strcmp(buf, "ignore"))
2218
            onerror = BLOCK_ERR_IGNORE;
2219
        else if (!strcmp(buf, "enospc"))
2220
            onerror = BLOCK_ERR_STOP_ENOSPC;
2221
        else if (!strcmp(buf, "stop"))
2222
            onerror = BLOCK_ERR_STOP_ANY;
2223
        else if (!strcmp(buf, "report"))
2224
            onerror = BLOCK_ERR_REPORT;
2225
        else {
2226
            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2227
            return -1;
2228
        }
2229
    }
2230

    
2231
    devaddr = NULL;
2232
    if (get_param_value(buf, sizeof(buf), "addr", str)) {
2233
        if (type != IF_VIRTIO) {
2234
            fprintf(stderr, "addr is not supported by in '%s'\n", str);
2235
            return -1;
2236
        }
2237
        devaddr = strdup(buf);
2238
    }
2239

    
2240
    /* compute bus and unit according index */
2241

    
2242
    if (index != -1) {
2243
        if (bus_id != 0 || unit_id != -1) {
2244
            fprintf(stderr,
2245
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2246
            return -1;
2247
        }
2248
        if (max_devs == 0)
2249
        {
2250
            unit_id = index;
2251
            bus_id = 0;
2252
        } else {
2253
            unit_id = index % max_devs;
2254
            bus_id = index / max_devs;
2255
        }
2256
    }
2257

    
2258
    /* if user doesn't specify a unit_id,
2259
     * try to find the first free
2260
     */
2261

    
2262
    if (unit_id == -1) {
2263
       unit_id = 0;
2264
       while (drive_get_index(type, bus_id, unit_id) != -1) {
2265
           unit_id++;
2266
           if (max_devs && unit_id >= max_devs) {
2267
               unit_id -= max_devs;
2268
               bus_id++;
2269
           }
2270
       }
2271
    }
2272

    
2273
    /* check unit id */
2274

    
2275
    if (max_devs && unit_id >= max_devs) {
2276
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2277
                        str, unit_id, max_devs - 1);
2278
        return -1;
2279
    }
2280

    
2281
    /*
2282
     * ignore multiple definitions
2283
     */
2284

    
2285
    if (drive_get_index(type, bus_id, unit_id) != -1)
2286
        return -2;
2287

    
2288
    /* init */
2289

    
2290
    if (type == IF_IDE || type == IF_SCSI)
2291
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2292
    if (max_devs)
2293
        snprintf(buf, sizeof(buf), "%s%i%s%i",
2294
                 devname, bus_id, mediastr, unit_id);
2295
    else
2296
        snprintf(buf, sizeof(buf), "%s%s%i",
2297
                 devname, mediastr, unit_id);
2298
    bdrv = bdrv_new(buf);
2299
    drives_table_idx = drive_get_free_idx();
2300
    drives_table[drives_table_idx].bdrv = bdrv;
2301
    drives_table[drives_table_idx].devaddr = devaddr;
2302
    drives_table[drives_table_idx].type = type;
2303
    drives_table[drives_table_idx].bus = bus_id;
2304
    drives_table[drives_table_idx].unit = unit_id;
2305
    drives_table[drives_table_idx].onerror = onerror;
2306
    drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2307
    strncpy(drives_table[drives_table_idx].serial, serial, sizeof(serial));
2308
    nb_drives++;
2309

    
2310
    switch(type) {
2311
    case IF_IDE:
2312
    case IF_SCSI:
2313
    case IF_XEN:
2314
        switch(media) {
2315
        case MEDIA_DISK:
2316
            if (cyls != 0) {
2317
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2318
                bdrv_set_translation_hint(bdrv, translation);
2319
            }
2320
            break;
2321
        case MEDIA_CDROM:
2322
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2323
            break;
2324
        }
2325
        break;
2326
    case IF_SD:
2327
        /* FIXME: This isn't really a floppy, but it's a reasonable
2328
           approximation.  */
2329
    case IF_FLOPPY:
2330
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2331
        break;
2332
    case IF_PFLASH:
2333
    case IF_MTD:
2334
    case IF_VIRTIO:
2335
        break;
2336
    case IF_COUNT:
2337
        abort();
2338
    }
2339
    if (!file[0])
2340
        return -2;
2341
    bdrv_flags = 0;
2342
    if (snapshot) {
2343
        bdrv_flags |= BDRV_O_SNAPSHOT;
2344
        cache = 2; /* always use write-back with snapshot */
2345
    }
2346
    if (cache == 0) /* no caching */
2347
        bdrv_flags |= BDRV_O_NOCACHE;
2348
    else if (cache == 2) /* write-back */
2349
        bdrv_flags |= BDRV_O_CACHE_WB;
2350
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2351
        fprintf(stderr, "qemu: could not open disk image %s\n",
2352
                        file);
2353
        return -1;
2354
    }
2355
    if (bdrv_key_required(bdrv))
2356
        autostart = 0;
2357
    return drives_table_idx;
2358
}
2359

    
2360
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2361
{
2362
    boot_set_handler = func;
2363
    boot_set_opaque = opaque;
2364
}
2365

    
2366
int qemu_boot_set(const char *boot_devices)
2367
{
2368
    if (!boot_set_handler) {
2369
        return -EINVAL;
2370
    }
2371
    return boot_set_handler(boot_set_opaque, boot_devices);
2372
}
2373

    
2374
static int parse_bootdevices(char *devices)
2375
{
2376
    /* We just do some generic consistency checks */
2377
    const char *p;
2378
    int bitmap = 0;
2379

    
2380
    for (p = devices; *p != '\0'; p++) {
2381
        /* Allowed boot devices are:
2382
         * a-b: floppy disk drives
2383
         * c-f: IDE disk drives
2384
         * g-m: machine implementation dependant drives
2385
         * n-p: network devices
2386
         * It's up to each machine implementation to check if the given boot
2387
         * devices match the actual hardware implementation and firmware
2388
         * features.
2389
         */
2390
        if (*p < 'a' || *p > 'p') {
2391
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2392
            exit(1);
2393
        }
2394
        if (bitmap & (1 << (*p - 'a'))) {
2395
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2396
            exit(1);
2397
        }
2398
        bitmap |= 1 << (*p - 'a');
2399
    }
2400
    return bitmap;
2401
}
2402

    
2403
static void restore_boot_devices(void *opaque)
2404
{
2405
    char *standard_boot_devices = opaque;
2406

    
2407
    qemu_boot_set(standard_boot_devices);
2408

    
2409
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2410
    qemu_free(standard_boot_devices);
2411
}
2412

    
2413
static void numa_add(const char *optarg)
2414
{
2415
    char option[128];
2416
    char *endptr;
2417
    unsigned long long value, endvalue;
2418
    int nodenr;
2419

    
2420
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2421
    if (!strcmp(option, "node")) {
2422
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2423
            nodenr = nb_numa_nodes;
2424
        } else {
2425
            nodenr = strtoull(option, NULL, 10);
2426
        }
2427

    
2428
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2429
            node_mem[nodenr] = 0;
2430
        } else {
2431
            value = strtoull(option, &endptr, 0);
2432
            switch (*endptr) {
2433
            case 0: case 'M': case 'm':
2434
                value <<= 20;
2435
                break;
2436
            case 'G': case 'g':
2437
                value <<= 30;
2438
                break;
2439
            }
2440
            node_mem[nodenr] = value;
2441
        }
2442
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2443
            node_cpumask[nodenr] = 0;
2444
        } else {
2445
            value = strtoull(option, &endptr, 10);
2446
            if (value >= 64) {
2447
                value = 63;
2448
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2449
            } else {
2450
                if (*endptr == '-') {
2451
                    endvalue = strtoull(endptr+1, &endptr, 10);
2452
                    if (endvalue >= 63) {
2453
                        endvalue = 62;
2454
                        fprintf(stderr,
2455
                            "only 63 CPUs in NUMA mode supported.\n");
2456
                    }
2457
                    value = (1 << (endvalue + 1)) - (1 << value);
2458
                } else {
2459
                    value = 1 << value;
2460
                }
2461
            }
2462
            node_cpumask[nodenr] = value;
2463
        }
2464
        nb_numa_nodes++;
2465
    }
2466
    return;
2467
}
2468

    
2469
/***********************************************************/
2470
/* USB devices */
2471

    
2472
static USBPort *used_usb_ports;
2473
static USBPort *free_usb_ports;
2474

    
2475
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2476
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2477
                            usb_attachfn attach)
2478
{
2479
    port->opaque = opaque;
2480
    port->index = index;
2481
    port->attach = attach;
2482
    port->next = free_usb_ports;
2483
    free_usb_ports = port;
2484
}
2485

    
2486
int usb_device_add_dev(USBDevice *dev)
2487
{
2488
    USBPort *port;
2489

    
2490
    /* Find a USB port to add the device to.  */
2491
    port = free_usb_ports;
2492
    if (!port->next) {
2493
        USBDevice *hub;
2494

    
2495
        /* Create a new hub and chain it on.  */
2496
        free_usb_ports = NULL;
2497
        port->next = used_usb_ports;
2498
        used_usb_ports = port;
2499

    
2500
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2501
        usb_attach(port, hub);
2502
        port = free_usb_ports;
2503
    }
2504

    
2505
    free_usb_ports = port->next;
2506
    port->next = used_usb_ports;
2507
    used_usb_ports = port;
2508
    usb_attach(port, dev);
2509
    return 0;
2510
}
2511

    
2512
static void usb_msd_password_cb(void *opaque, int err)
2513
{
2514
    USBDevice *dev = opaque;
2515

    
2516
    if (!err)
2517
        usb_device_add_dev(dev);
2518
    else
2519
        dev->handle_destroy(dev);
2520
}
2521

    
2522
static int usb_device_add(const char *devname, int is_hotplug)
2523
{
2524
    const char *p;
2525
    USBDevice *dev;
2526

    
2527
    if (!free_usb_ports)
2528
        return -1;
2529

    
2530
    if (strstart(devname, "host:", &p)) {
2531
        dev = usb_host_device_open(p);
2532
    } else if (!strcmp(devname, "mouse")) {
2533
        dev = usb_mouse_init();
2534
    } else if (!strcmp(devname, "tablet")) {
2535
        dev = usb_tablet_init();
2536
    } else if (!strcmp(devname, "keyboard")) {
2537
        dev = usb_keyboard_init();
2538
    } else if (strstart(devname, "disk:", &p)) {
2539
        BlockDriverState *bs;
2540

    
2541
        dev = usb_msd_init(p);
2542
        if (!dev)
2543
            return -1;
2544
        bs = usb_msd_get_bdrv(dev);
2545
        if (bdrv_key_required(bs)) {
2546
            autostart = 0;
2547
            if (is_hotplug) {
2548
                monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2549
                                            dev);
2550
                return 0;
2551
            }
2552
        }
2553
    } else if (!strcmp(devname, "wacom-tablet")) {
2554
        dev = usb_wacom_init();
2555
    } else if (strstart(devname, "serial:", &p)) {
2556
        dev = usb_serial_init(p);
2557
#ifdef CONFIG_BRLAPI
2558
    } else if (!strcmp(devname, "braille")) {
2559
        dev = usb_baum_init();
2560
#endif
2561
    } else if (strstart(devname, "net:", &p)) {
2562
        int nic = nb_nics;
2563

    
2564
        if (net_client_init(NULL, "nic", p) < 0)
2565
            return -1;
2566
        nd_table[nic].model = "usb";
2567
        dev = usb_net_init(&nd_table[nic]);
2568
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2569
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2570
                        bt_new_hci(qemu_find_bt_vlan(0)));
2571
    } else {
2572
        return -1;
2573
    }
2574
    if (!dev)
2575
        return -1;
2576

    
2577
    return usb_device_add_dev(dev);
2578
}
2579

    
2580
int usb_device_del_addr(int bus_num, int addr)
2581
{
2582
    USBPort *port;
2583
    USBPort **lastp;
2584
    USBDevice *dev;
2585

    
2586
    if (!used_usb_ports)
2587
        return -1;
2588

    
2589
    if (bus_num != 0)
2590
        return -1;
2591

    
2592
    lastp = &used_usb_ports;
2593
    port = used_usb_ports;
2594
    while (port && port->dev->addr != addr) {
2595
        lastp = &port->next;
2596
        port = port->next;
2597
    }
2598

    
2599
    if (!port)
2600
        return -1;
2601

    
2602
    dev = port->dev;
2603
    *lastp = port->next;
2604
    usb_attach(port, NULL);
2605
    dev->handle_destroy(dev);
2606
    port->next = free_usb_ports;
2607
    free_usb_ports = port;
2608
    return 0;
2609
}
2610

    
2611
static int usb_device_del(const char *devname)
2612
{
2613
    int bus_num, addr;
2614
    const char *p;
2615

    
2616
    if (strstart(devname, "host:", &p))
2617
        return usb_host_device_close(p);
2618

    
2619
    if (!used_usb_ports)
2620
        return -1;
2621

    
2622
    p = strchr(devname, '.');
2623
    if (!p)
2624
        return -1;
2625
    bus_num = strtoul(devname, NULL, 0);
2626
    addr = strtoul(p + 1, NULL, 0);
2627

    
2628
    return usb_device_del_addr(bus_num, addr);
2629
}
2630

    
2631
static int usb_parse(const char *cmdline)
2632
{
2633
    return usb_device_add(cmdline, 0);
2634
}
2635

    
2636
void do_usb_add(Monitor *mon, const char *devname)
2637
{
2638
    usb_device_add(devname, 1);
2639
}
2640

    
2641
void do_usb_del(Monitor *mon, const char *devname)
2642
{
2643
    usb_device_del(devname);
2644
}
2645

    
2646
void usb_info(Monitor *mon)
2647
{
2648
    USBDevice *dev;
2649
    USBPort *port;
2650
    const char *speed_str;
2651

    
2652
    if (!usb_enabled) {
2653
        monitor_printf(mon, "USB support not enabled\n");
2654
        return;
2655
    }
2656

    
2657
    for (port = used_usb_ports; port; port = port->next) {
2658
        dev = port->dev;
2659
        if (!dev)
2660
            continue;
2661
        switch(dev->speed) {
2662
        case USB_SPEED_LOW:
2663
            speed_str = "1.5";
2664
            break;
2665
        case USB_SPEED_FULL:
2666
            speed_str = "12";
2667
            break;
2668
        case USB_SPEED_HIGH:
2669
            speed_str = "480";
2670
            break;
2671
        default:
2672
            speed_str = "?";
2673
            break;
2674
        }
2675
        monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
2676
                       0, dev->addr, speed_str, dev->devname);
2677
    }
2678
}
2679

    
2680
/***********************************************************/
2681
/* PCMCIA/Cardbus */
2682

    
2683
static struct pcmcia_socket_entry_s {
2684
    PCMCIASocket *socket;
2685
    struct pcmcia_socket_entry_s *next;
2686
} *pcmcia_sockets = 0;
2687

    
2688
void pcmcia_socket_register(PCMCIASocket *socket)
2689
{
2690
    struct pcmcia_socket_entry_s *entry;
2691

    
2692
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2693
    entry->socket = socket;
2694
    entry->next = pcmcia_sockets;
2695
    pcmcia_sockets = entry;
2696
}
2697

    
2698
void pcmcia_socket_unregister(PCMCIASocket *socket)
2699
{
2700
    struct pcmcia_socket_entry_s *entry, **ptr;
2701

    
2702
    ptr = &pcmcia_sockets;
2703
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2704
        if (entry->socket == socket) {
2705
            *ptr = entry->next;
2706
            qemu_free(entry);
2707
        }
2708
}
2709

    
2710
void pcmcia_info(Monitor *mon)
2711
{
2712
    struct pcmcia_socket_entry_s *iter;
2713

    
2714
    if (!pcmcia_sockets)
2715
        monitor_printf(mon, "No PCMCIA sockets\n");
2716

    
2717
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2718
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2719
                       iter->socket->attached ? iter->socket->card_string :
2720
                       "Empty");
2721
}
2722

    
2723
/***********************************************************/
2724
/* register display */
2725

    
2726
struct DisplayAllocator default_allocator = {
2727
    defaultallocator_create_displaysurface,
2728
    defaultallocator_resize_displaysurface,
2729
    defaultallocator_free_displaysurface
2730
};
2731

    
2732
void register_displaystate(DisplayState *ds)
2733
{
2734
    DisplayState **s;
2735
    s = &display_state;
2736
    while (*s != NULL)
2737
        s = &(*s)->next;
2738
    ds->next = NULL;
2739
    *s = ds;
2740
}
2741

    
2742
DisplayState *get_displaystate(void)
2743
{
2744
    return display_state;
2745
}
2746

    
2747
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2748
{
2749
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2750
    return ds->allocator;
2751
}
2752

    
2753
/* dumb display */
2754

    
2755
static void dumb_display_init(void)
2756
{
2757
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2758
    ds->allocator = &default_allocator;
2759
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2760
    register_displaystate(ds);
2761
}
2762

    
2763
/***********************************************************/
2764
/* I/O handling */
2765

    
2766
typedef struct IOHandlerRecord {
2767
    int fd;
2768
    IOCanRWHandler *fd_read_poll;
2769
    IOHandler *fd_read;
2770
    IOHandler *fd_write;
2771
    int deleted;
2772
    void *opaque;
2773
    /* temporary data */
2774
    struct pollfd *ufd;
2775
    struct IOHandlerRecord *next;
2776
} IOHandlerRecord;
2777

    
2778
static IOHandlerRecord *first_io_handler;
2779

    
2780
/* XXX: fd_read_poll should be suppressed, but an API change is
2781
   necessary in the character devices to suppress fd_can_read(). */
2782
int qemu_set_fd_handler2(int fd,
2783
                         IOCanRWHandler *fd_read_poll,
2784
                         IOHandler *fd_read,
2785
                         IOHandler *fd_write,
2786
                         void *opaque)
2787
{
2788
    IOHandlerRecord **pioh, *ioh;
2789

    
2790
    if (!fd_read && !fd_write) {
2791
        pioh = &first_io_handler;
2792
        for(;;) {
2793
            ioh = *pioh;
2794
            if (ioh == NULL)
2795
                break;
2796
            if (ioh->fd == fd) {
2797
                ioh->deleted = 1;
2798
                break;
2799
            }
2800
            pioh = &ioh->next;
2801
        }
2802
    } else {
2803
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2804
            if (ioh->fd == fd)
2805
                goto found;
2806
        }
2807
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2808
        ioh->next = first_io_handler;
2809
        first_io_handler = ioh;
2810
    found:
2811
        ioh->fd = fd;
2812
        ioh->fd_read_poll = fd_read_poll;
2813
        ioh->fd_read = fd_read;
2814
        ioh->fd_write = fd_write;
2815
        ioh->opaque = opaque;
2816
        ioh->deleted = 0;
2817
    }
2818
    return 0;
2819
}
2820

    
2821
int qemu_set_fd_handler(int fd,
2822
                        IOHandler *fd_read,
2823
                        IOHandler *fd_write,
2824
                        void *opaque)
2825
{
2826
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2827
}
2828

    
2829
#ifdef _WIN32
2830
/***********************************************************/
2831
/* Polling handling */
2832

    
2833
typedef struct PollingEntry {
2834
    PollingFunc *func;
2835
    void *opaque;
2836
    struct PollingEntry *next;
2837
} PollingEntry;
2838

    
2839
static PollingEntry *first_polling_entry;
2840

    
2841
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2842
{
2843
    PollingEntry **ppe, *pe;
2844
    pe = qemu_mallocz(sizeof(PollingEntry));
2845
    pe->func = func;
2846
    pe->opaque = opaque;
2847
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2848
    *ppe = pe;
2849
    return 0;
2850
}
2851

    
2852
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2853
{
2854
    PollingEntry **ppe, *pe;
2855
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2856
        pe = *ppe;
2857
        if (pe->func == func && pe->opaque == opaque) {
2858
            *ppe = pe->next;
2859
            qemu_free(pe);
2860
            break;
2861
        }
2862
    }
2863
}
2864

    
2865
/***********************************************************/
2866
/* Wait objects support */
2867
typedef struct WaitObjects {
2868
    int num;
2869
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2870
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2871
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2872
} WaitObjects;
2873

    
2874
static WaitObjects wait_objects = {0};
2875

    
2876
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2877
{
2878
    WaitObjects *w = &wait_objects;
2879

    
2880
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2881
        return -1;
2882
    w->events[w->num] = handle;
2883
    w->func[w->num] = func;
2884
    w->opaque[w->num] = opaque;
2885
    w->num++;
2886
    return 0;
2887
}
2888

    
2889
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2890
{
2891
    int i, found;
2892
    WaitObjects *w = &wait_objects;
2893

    
2894
    found = 0;
2895
    for (i = 0; i < w->num; i++) {
2896
        if (w->events[i] == handle)
2897
            found = 1;
2898
        if (found) {
2899
            w->events[i] = w->events[i + 1];
2900
            w->func[i] = w->func[i + 1];
2901
            w->opaque[i] = w->opaque[i + 1];
2902
        }
2903
    }
2904
    if (found)
2905
        w->num--;
2906
}
2907
#endif
2908

    
2909
/***********************************************************/
2910
/* ram save/restore */
2911

    
2912
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2913
{
2914
    int v;
2915

    
2916
    v = qemu_get_byte(f);
2917
    switch(v) {
2918
    case 0:
2919
        if (qemu_get_buffer(f, buf, len) != len)
2920
            return -EIO;
2921
        break;
2922
    case 1:
2923
        v = qemu_get_byte(f);
2924
        memset(buf, v, len);
2925
        break;
2926
    default:
2927
        return -EINVAL;
2928
    }
2929

    
2930
    if (qemu_file_has_error(f))
2931
        return -EIO;
2932

    
2933
    return 0;
2934
}
2935

    
2936
static int ram_load_v1(QEMUFile *f, void *opaque)
2937
{
2938
    int ret;
2939
    ram_addr_t i;
2940

    
2941
    if (qemu_get_be32(f) != last_ram_offset)
2942
        return -EINVAL;
2943
    for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2944
        ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2945
        if (ret)
2946
            return ret;
2947
    }
2948
    return 0;
2949
}
2950

    
2951
#define BDRV_HASH_BLOCK_SIZE 1024
2952
#define IOBUF_SIZE 4096
2953
#define RAM_CBLOCK_MAGIC 0xfabe
2954

    
2955
typedef struct RamDecompressState {
2956
    z_stream zstream;
2957
    QEMUFile *f;
2958
    uint8_t buf[IOBUF_SIZE];
2959
} RamDecompressState;
2960

    
2961
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2962
{
2963
    int ret;
2964
    memset(s, 0, sizeof(*s));
2965
    s->f = f;
2966
    ret = inflateInit(&s->zstream);
2967
    if (ret != Z_OK)
2968
        return -1;
2969
    return 0;
2970
}
2971

    
2972
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2973
{
2974
    int ret, clen;
2975

    
2976
    s->zstream.avail_out = len;
2977
    s->zstream.next_out = buf;
2978
    while (s->zstream.avail_out > 0) {
2979
        if (s->zstream.avail_in == 0) {
2980
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2981
                return -1;
2982
            clen = qemu_get_be16(s->f);
2983
            if (clen > IOBUF_SIZE)
2984
                return -1;
2985
            qemu_get_buffer(s->f, s->buf, clen);
2986
            s->zstream.avail_in = clen;
2987
            s->zstream.next_in = s->buf;
2988
        }
2989
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2990
        if (ret != Z_OK && ret != Z_STREAM_END) {
2991
            return -1;
2992
        }
2993
    }
2994
    return 0;
2995
}
2996

    
2997
static void ram_decompress_close(RamDecompressState *s)
2998
{
2999
    inflateEnd(&s->zstream);
3000
}
3001

    
3002
#define RAM_SAVE_FLAG_FULL        0x01
3003
#define RAM_SAVE_FLAG_COMPRESS        0x02
3004
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
3005
#define RAM_SAVE_FLAG_PAGE        0x08
3006
#define RAM_SAVE_FLAG_EOS        0x10
3007

    
3008
static int is_dup_page(uint8_t *page, uint8_t ch)
3009
{
3010
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3011
    uint32_t *array = (uint32_t *)page;
3012
    int i;
3013

    
3014
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3015
        if (array[i] != val)
3016
            return 0;
3017
    }
3018

    
3019
    return 1;
3020
}
3021

    
3022
static int ram_save_block(QEMUFile *f)
3023
{
3024
    static ram_addr_t current_addr = 0;
3025
    ram_addr_t saved_addr = current_addr;
3026
    ram_addr_t addr = 0;
3027
    int found = 0;
3028

    
3029
    while (addr < last_ram_offset) {
3030
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3031
            uint8_t *p;
3032

    
3033
            cpu_physical_memory_reset_dirty(current_addr,
3034
                                            current_addr + TARGET_PAGE_SIZE,
3035
                                            MIGRATION_DIRTY_FLAG);
3036

    
3037
            p = qemu_get_ram_ptr(current_addr);
3038

    
3039
            if (is_dup_page(p, *p)) {
3040
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3041
                qemu_put_byte(f, *p);
3042
            } else {
3043
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3044
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3045
            }
3046

    
3047
            found = 1;
3048
            break;
3049
        }
3050
        addr += TARGET_PAGE_SIZE;
3051
        current_addr = (saved_addr + addr) % last_ram_offset;
3052
    }
3053

    
3054
    return found;
3055
}
3056

    
3057
static uint64_t bytes_transferred = 0;
3058

    
3059
static ram_addr_t ram_save_remaining(void)
3060
{
3061
    ram_addr_t addr;
3062
    ram_addr_t count = 0;
3063

    
3064
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3065
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3066
            count++;
3067
    }
3068

    
3069
    return count;
3070
}
3071

    
3072
uint64_t ram_bytes_remaining(void)
3073
{
3074
    return ram_save_remaining() * TARGET_PAGE_SIZE;
3075
}
3076

    
3077
uint64_t ram_bytes_transferred(void)
3078
{
3079
    return bytes_transferred;
3080
}
3081

    
3082
uint64_t ram_bytes_total(void)
3083
{
3084
    return last_ram_offset;
3085
}
3086

    
3087
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3088
{
3089
    ram_addr_t addr;
3090
    uint64_t bytes_transferred_last;
3091
    double bwidth = 0;
3092
    uint64_t expected_time = 0;
3093

    
3094
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3095
        qemu_file_set_error(f);
3096
        return 0;
3097
    }
3098

    
3099
    if (stage == 1) {
3100
        /* Make sure all dirty bits are set */
3101
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3102
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3103
                cpu_physical_memory_set_dirty(addr);
3104
        }
3105

    
3106
        /* Enable dirty memory tracking */
3107
        cpu_physical_memory_set_dirty_tracking(1);
3108

    
3109
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3110
    }
3111

    
3112
    bytes_transferred_last = bytes_transferred;
3113
    bwidth = get_clock();
3114

    
3115
    while (!qemu_file_rate_limit(f)) {
3116
        int ret;
3117

    
3118
        ret = ram_save_block(f);
3119
        bytes_transferred += ret * TARGET_PAGE_SIZE;
3120
        if (ret == 0) /* no more blocks */
3121
            break;
3122
    }
3123

    
3124
    bwidth = get_clock() - bwidth;
3125
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3126

    
3127
    /* if we haven't transferred anything this round, force expected_time to a
3128
     * a very high value, but without crashing */
3129
    if (bwidth == 0)
3130
        bwidth = 0.000001;
3131

    
3132
    /* try transferring iterative blocks of memory */
3133

    
3134
    if (stage == 3) {
3135

    
3136
        /* flush all remaining blocks regardless of rate limiting */
3137
        while (ram_save_block(f) != 0) {
3138
            bytes_transferred += TARGET_PAGE_SIZE;
3139
        }
3140
        cpu_physical_memory_set_dirty_tracking(0);
3141
    }
3142

    
3143
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3144

    
3145
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3146

    
3147
    return (stage == 2) && (expected_time <= migrate_max_downtime());
3148
}
3149

    
3150
static int ram_load_dead(QEMUFile *f, void *opaque)
3151
{
3152
    RamDecompressState s1, *s = &s1;
3153
    uint8_t buf[10];
3154
    ram_addr_t i;
3155

    
3156
    if (ram_decompress_open(s, f) < 0)
3157
        return -EINVAL;
3158
    for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3159
        if (ram_decompress_buf(s, buf, 1) < 0) {
3160
            fprintf(stderr, "Error while reading ram block header\n");
3161
            goto error;
3162
        }
3163
        if (buf[0] == 0) {
3164
            if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3165
                                   BDRV_HASH_BLOCK_SIZE) < 0) {
3166
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3167
                goto error;
3168
            }
3169
        } else {
3170
        error:
3171
            printf("Error block header\n");
3172
            return -EINVAL;
3173
        }
3174
    }
3175
    ram_decompress_close(s);
3176

    
3177
    return 0;
3178
}
3179

    
3180
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3181
{
3182
    ram_addr_t addr;
3183
    int flags;
3184

    
3185
    if (version_id == 1)
3186
        return ram_load_v1(f, opaque);
3187

    
3188
    if (version_id == 2) {
3189
        if (qemu_get_be32(f) != last_ram_offset)
3190
            return -EINVAL;
3191
        return ram_load_dead(f, opaque);
3192
    }
3193

    
3194
    if (version_id != 3)
3195
        return -EINVAL;
3196

    
3197
    do {
3198
        addr = qemu_get_be64(f);
3199

    
3200
        flags = addr & ~TARGET_PAGE_MASK;
3201
        addr &= TARGET_PAGE_MASK;
3202

    
3203
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3204
            if (addr != last_ram_offset)
3205
                return -EINVAL;
3206
        }
3207

    
3208
        if (flags & RAM_SAVE_FLAG_FULL) {
3209
            if (ram_load_dead(f, opaque) < 0)
3210
                return -EINVAL;
3211
        }
3212
        
3213
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3214
            uint8_t ch = qemu_get_byte(f);
3215
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3216
#ifndef _WIN32
3217
            if (ch == 0 &&
3218
                (!kvm_enabled() || kvm_has_sync_mmu())) {
3219
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3220
            }
3221
#endif
3222
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3223
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3224
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3225

    
3226
    return 0;
3227
}
3228

    
3229
void qemu_service_io(void)
3230
{
3231
    qemu_notify_event();
3232
}
3233

    
3234
/***********************************************************/
3235
/* bottom halves (can be seen as timers which expire ASAP) */
3236

    
3237
struct QEMUBH {
3238
    QEMUBHFunc *cb;
3239
    void *opaque;
3240
    int scheduled;
3241
    int idle;
3242
    int deleted;
3243
    QEMUBH *next;
3244
};
3245

    
3246
static QEMUBH *first_bh = NULL;
3247

    
3248
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3249
{
3250
    QEMUBH *bh;
3251
    bh = qemu_mallocz(sizeof(QEMUBH));
3252
    bh->cb = cb;
3253
    bh->opaque = opaque;
3254
    bh->next = first_bh;
3255
    first_bh = bh;
3256
    return bh;
3257
}
3258

    
3259
int qemu_bh_poll(void)
3260
{
3261
    QEMUBH *bh, **bhp;
3262
    int ret;
3263

    
3264
    ret = 0;
3265
    for (bh = first_bh; bh; bh = bh->next) {
3266
        if (!bh->deleted && bh->scheduled) {
3267
            bh->scheduled = 0;
3268
            if (!bh->idle)
3269
                ret = 1;
3270
            bh->idle = 0;
3271
            bh->cb(bh->opaque);
3272
        }
3273
    }
3274

    
3275
    /* remove deleted bhs */
3276
    bhp = &first_bh;
3277
    while (*bhp) {
3278
        bh = *bhp;
3279
        if (bh->deleted) {
3280
            *bhp = bh->next;
3281
            qemu_free(bh);
3282
        } else
3283
            bhp = &bh->next;
3284
    }
3285

    
3286
    return ret;
3287
}
3288

    
3289
void qemu_bh_schedule_idle(QEMUBH *bh)
3290
{
3291
    if (bh->scheduled)
3292
        return;
3293
    bh->scheduled = 1;
3294
    bh->idle = 1;
3295
}
3296

    
3297
void qemu_bh_schedule(QEMUBH *bh)
3298
{
3299
    if (bh->scheduled)
3300
        return;
3301
    bh->scheduled = 1;
3302
    bh->idle = 0;
3303
    /* stop the currently executing CPU to execute the BH ASAP */
3304
    qemu_notify_event();
3305
}
3306

    
3307
void qemu_bh_cancel(QEMUBH *bh)
3308
{
3309
    bh->scheduled = 0;
3310
}
3311

    
3312
void qemu_bh_delete(QEMUBH *bh)
3313
{
3314
    bh->scheduled = 0;
3315
    bh->deleted = 1;
3316
}
3317

    
3318
static void qemu_bh_update_timeout(int *timeout)
3319
{
3320
    QEMUBH *bh;
3321

    
3322
    for (bh = first_bh; bh; bh = bh->next) {
3323
        if (!bh->deleted && bh->scheduled) {
3324
            if (bh->idle) {
3325
                /* idle bottom halves will be polled at least
3326
                 * every 10ms */
3327
                *timeout = MIN(10, *timeout);
3328
            } else {
3329
                /* non-idle bottom halves will be executed
3330
                 * immediately */
3331
                *timeout = 0;
3332
                break;
3333
            }
3334
        }
3335
    }
3336
}
3337

    
3338
/***********************************************************/
3339
/* machine registration */
3340

    
3341
static QEMUMachine *first_machine = NULL;
3342
QEMUMachine *current_machine = NULL;
3343

    
3344
int qemu_register_machine(QEMUMachine *m)
3345
{
3346
    QEMUMachine **pm;
3347
    pm = &first_machine;
3348
    while (*pm != NULL)
3349
        pm = &(*pm)->next;
3350
    m->next = NULL;
3351
    *pm = m;
3352
    return 0;
3353
}
3354

    
3355
static QEMUMachine *find_machine(const char *name)
3356
{
3357
    QEMUMachine *m;
3358

    
3359
    for(m = first_machine; m != NULL; m = m->next) {
3360
        if (!strcmp(m->name, name))
3361
            return m;
3362
        if (m->alias && !strcmp(m->alias, name))
3363
            return m;
3364
    }
3365
    return NULL;
3366
}
3367

    
3368
static QEMUMachine *find_default_machine(void)
3369
{
3370
    QEMUMachine *m;
3371

    
3372
    for(m = first_machine; m != NULL; m = m->next) {
3373
        if (m->is_default) {
3374
            return m;
3375
        }
3376
    }
3377
    return NULL;
3378
}
3379

    
3380
/***********************************************************/
3381
/* main execution loop */
3382

    
3383
static void gui_update(void *opaque)
3384
{
3385
    uint64_t interval = GUI_REFRESH_INTERVAL;
3386
    DisplayState *ds = opaque;
3387
    DisplayChangeListener *dcl = ds->listeners;
3388

    
3389
    dpy_refresh(ds);
3390

    
3391
    while (dcl != NULL) {
3392
        if (dcl->gui_timer_interval &&
3393
            dcl->gui_timer_interval < interval)
3394
            interval = dcl->gui_timer_interval;
3395
        dcl = dcl->next;
3396
    }
3397
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3398
}
3399

    
3400
static void nographic_update(void *opaque)
3401
{
3402
    uint64_t interval = GUI_REFRESH_INTERVAL;
3403

    
3404
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3405
}
3406

    
3407
struct vm_change_state_entry {
3408
    VMChangeStateHandler *cb;
3409
    void *opaque;
3410
    LIST_ENTRY (vm_change_state_entry) entries;
3411
};
3412

    
3413
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3414

    
3415
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3416
                                                     void *opaque)
3417
{
3418
    VMChangeStateEntry *e;
3419

    
3420
    e = qemu_mallocz(sizeof (*e));
3421

    
3422
    e->cb = cb;
3423
    e->opaque = opaque;
3424
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3425
    return e;
3426
}
3427

    
3428
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3429
{
3430
    LIST_REMOVE (e, entries);
3431
    qemu_free (e);
3432
}
3433

    
3434
static void vm_state_notify(int running, int reason)
3435
{
3436
    VMChangeStateEntry *e;
3437

    
3438
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3439
        e->cb(e->opaque, running, reason);
3440
    }
3441
}
3442

    
3443
static void resume_all_vcpus(void);
3444
static void pause_all_vcpus(void);
3445

    
3446
void vm_start(void)
3447
{
3448
    if (!vm_running) {
3449
        cpu_enable_ticks();
3450
        vm_running = 1;
3451
        vm_state_notify(1, 0);
3452
        qemu_rearm_alarm_timer(alarm_timer);
3453
        resume_all_vcpus();
3454
    }
3455
}
3456

    
3457
/* reset/shutdown handler */
3458

    
3459
typedef struct QEMUResetEntry {
3460
    TAILQ_ENTRY(QEMUResetEntry) entry;
3461
    QEMUResetHandler *func;
3462
    void *opaque;
3463
} QEMUResetEntry;
3464

    
3465
static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3466
    TAILQ_HEAD_INITIALIZER(reset_handlers);
3467
static int reset_requested;
3468
static int shutdown_requested;
3469
static int powerdown_requested;
3470
static int debug_requested;
3471
static int vmstop_requested;
3472

    
3473
int qemu_shutdown_requested(void)
3474
{
3475
    int r = shutdown_requested;
3476
    shutdown_requested = 0;
3477
    return r;
3478
}
3479

    
3480
int qemu_reset_requested(void)
3481
{
3482
    int r = reset_requested;
3483
    reset_requested = 0;
3484
    return r;
3485
}
3486

    
3487
int qemu_powerdown_requested(void)
3488
{
3489
    int r = powerdown_requested;
3490
    powerdown_requested = 0;
3491
    return r;
3492
}
3493

    
3494
static int qemu_debug_requested(void)
3495
{
3496
    int r = debug_requested;
3497
    debug_requested = 0;
3498
    return r;
3499
}
3500

    
3501
static int qemu_vmstop_requested(void)
3502
{
3503
    int r = vmstop_requested;
3504
    vmstop_requested = 0;
3505
    return r;
3506
}
3507

    
3508
static void do_vm_stop(int reason)
3509
{
3510
    if (vm_running) {
3511
        cpu_disable_ticks();
3512
        vm_running = 0;
3513
        pause_all_vcpus();
3514
        vm_state_notify(0, reason);
3515
    }
3516
}
3517

    
3518
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3519
{
3520
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3521

    
3522
    re->func = func;
3523
    re->opaque = opaque;
3524
    TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3525
}
3526

    
3527
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3528
{
3529
    QEMUResetEntry *re;
3530

    
3531
    TAILQ_FOREACH(re, &reset_handlers, entry) {
3532
        if (re->func == func && re->opaque == opaque) {
3533
            TAILQ_REMOVE(&reset_handlers, re, entry);
3534
            qemu_free(re);
3535
            return;
3536
        }
3537
    }
3538
}
3539

    
3540
void qemu_system_reset(void)
3541
{
3542
    QEMUResetEntry *re, *nre;
3543

    
3544
    /* reset all devices */
3545
    TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3546
        re->func(re->opaque);
3547
    }
3548
}
3549

    
3550
void qemu_system_reset_request(void)
3551
{
3552
    if (no_reboot) {
3553
        shutdown_requested = 1;
3554
    } else {
3555
        reset_requested = 1;
3556
    }
3557
    qemu_notify_event();
3558
}
3559

    
3560
void qemu_system_shutdown_request(void)
3561
{
3562
    shutdown_requested = 1;
3563
    qemu_notify_event();
3564
}
3565

    
3566
void qemu_system_powerdown_request(void)
3567
{
3568
    powerdown_requested = 1;
3569
    qemu_notify_event();
3570
}
3571

    
3572
#ifdef CONFIG_IOTHREAD
3573
static void qemu_system_vmstop_request(int reason)
3574
{
3575
    vmstop_requested = reason;
3576
    qemu_notify_event();
3577
}
3578
#endif
3579

    
3580
#ifndef _WIN32
3581
static int io_thread_fd = -1;
3582

    
3583
static void qemu_event_increment(void)
3584
{
3585
    static const char byte = 0;
3586

    
3587
    if (io_thread_fd == -1)
3588
        return;
3589

    
3590
    write(io_thread_fd, &byte, sizeof(byte));
3591
}
3592

    
3593
static void qemu_event_read(void *opaque)
3594
{
3595
    int fd = (unsigned long)opaque;
3596
    ssize_t len;
3597

    
3598
    /* Drain the notify pipe */
3599
    do {
3600
        char buffer[512];
3601
        len = read(fd, buffer, sizeof(buffer));
3602
    } while ((len == -1 && errno == EINTR) || len > 0);
3603
}
3604

    
3605
static int qemu_event_init(void)
3606
{
3607
    int err;
3608
    int fds[2];
3609

    
3610
    err = pipe(fds);
3611
    if (err == -1)
3612
        return -errno;
3613

    
3614
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3615
    if (err < 0)
3616
        goto fail;
3617

    
3618
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3619
    if (err < 0)
3620
        goto fail;
3621

    
3622
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3623
                         (void *)(unsigned long)fds[0]);
3624

    
3625
    io_thread_fd = fds[1];
3626
    return 0;
3627

    
3628
fail:
3629
    close(fds[0]);
3630
    close(fds[1]);
3631
    return err;
3632
}
3633
#else
3634
HANDLE qemu_event_handle;
3635

    
3636
static void dummy_event_handler(void *opaque)
3637
{
3638
}
3639

    
3640
static int qemu_event_init(void)
3641
{
3642
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3643
    if (!qemu_event_handle) {
3644
        perror("Failed CreateEvent");
3645
        return -1;
3646
    }
3647
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3648
    return 0;
3649
}
3650

    
3651
static void qemu_event_increment(void)
3652
{
3653
    SetEvent(qemu_event_handle);
3654
}
3655
#endif
3656

    
3657
static int cpu_can_run(CPUState *env)
3658
{
3659
    if (env->stop)
3660
        return 0;
3661
    if (env->stopped)
3662
        return 0;
3663
    return 1;
3664
}
3665

    
3666
#ifndef CONFIG_IOTHREAD
3667
static int qemu_init_main_loop(void)
3668
{
3669
    return qemu_event_init();
3670
}
3671

    
3672
void qemu_init_vcpu(void *_env)
3673
{
3674
    CPUState *env = _env;
3675

    
3676
    if (kvm_enabled())
3677
        kvm_init_vcpu(env);
3678
    return;
3679
}
3680

    
3681
int qemu_cpu_self(void *env)
3682
{
3683
    return 1;
3684
}
3685

    
3686
static void resume_all_vcpus(void)
3687
{
3688
}
3689

    
3690
static void pause_all_vcpus(void)
3691
{
3692
}
3693

    
3694
void qemu_cpu_kick(void *env)
3695
{
3696
    return;
3697
}
3698

    
3699
void qemu_notify_event(void)
3700
{
3701
    CPUState *env = cpu_single_env;
3702

    
3703
    if (env) {
3704
        cpu_exit(env);
3705
#ifdef USE_KQEMU
3706
        if (env->kqemu_enabled)
3707
            kqemu_cpu_interrupt(env);
3708
#endif
3709
     }
3710
}
3711

    
3712
#define qemu_mutex_lock_iothread() do { } while (0)
3713
#define qemu_mutex_unlock_iothread() do { } while (0)
3714

    
3715
void vm_stop(int reason)
3716
{
3717
    do_vm_stop(reason);
3718
}
3719

    
3720
#else /* CONFIG_IOTHREAD */
3721

    
3722
#include "qemu-thread.h"
3723

    
3724
QemuMutex qemu_global_mutex;
3725
static QemuMutex qemu_fair_mutex;
3726

    
3727
static QemuThread io_thread;
3728

    
3729
static QemuThread *tcg_cpu_thread;
3730
static QemuCond *tcg_halt_cond;
3731

    
3732
static int qemu_system_ready;
3733
/* cpu creation */
3734
static QemuCond qemu_cpu_cond;
3735
/* system init */
3736
static QemuCond qemu_system_cond;
3737
static QemuCond qemu_pause_cond;
3738

    
3739
static void block_io_signals(void);
3740
static void unblock_io_signals(void);
3741
static int tcg_has_work(void);
3742

    
3743
static int qemu_init_main_loop(void)
3744
{
3745
    int ret;
3746

    
3747
    ret = qemu_event_init();
3748
    if (ret)
3749
        return ret;
3750

    
3751
    qemu_cond_init(&qemu_pause_cond);
3752
    qemu_mutex_init(&qemu_fair_mutex);
3753
    qemu_mutex_init(&qemu_global_mutex);
3754
    qemu_mutex_lock(&qemu_global_mutex);
3755

    
3756
    unblock_io_signals();
3757
    qemu_thread_self(&io_thread);
3758

    
3759
    return 0;
3760
}
3761

    
3762
static void qemu_wait_io_event(CPUState *env)
3763
{
3764
    while (!tcg_has_work())
3765
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3766

    
3767
    qemu_mutex_unlock(&qemu_global_mutex);
3768

    
3769
    /*
3770
     * Users of qemu_global_mutex can be starved, having no chance
3771
     * to acquire it since this path will get to it first.
3772
     * So use another lock to provide fairness.
3773
     */
3774
    qemu_mutex_lock(&qemu_fair_mutex);
3775
    qemu_mutex_unlock(&qemu_fair_mutex);
3776

    
3777
    qemu_mutex_lock(&qemu_global_mutex);
3778
    if (env->stop) {
3779
        env->stop = 0;
3780
        env->stopped = 1;
3781
        qemu_cond_signal(&qemu_pause_cond);
3782
    }
3783
}
3784

    
3785
static int qemu_cpu_exec(CPUState *env);
3786

    
3787
static void *kvm_cpu_thread_fn(void *arg)
3788
{
3789
    CPUState *env = arg;
3790

    
3791
    block_io_signals();
3792
    qemu_thread_self(env->thread);
3793

    
3794
    /* signal CPU creation */
3795
    qemu_mutex_lock(&qemu_global_mutex);
3796
    env->created = 1;
3797
    qemu_cond_signal(&qemu_cpu_cond);
3798

    
3799
    /* and wait for machine initialization */
3800
    while (!qemu_system_ready)
3801
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3802

    
3803
    while (1) {
3804
        if (cpu_can_run(env))
3805
            qemu_cpu_exec(env);
3806
        qemu_wait_io_event(env);
3807
    }
3808

    
3809
    return NULL;
3810
}
3811

    
3812
static void tcg_cpu_exec(void);
3813

    
3814
static void *tcg_cpu_thread_fn(void *arg)
3815
{
3816
    CPUState *env = arg;
3817

    
3818
    block_io_signals();
3819
    qemu_thread_self(env->thread);
3820

    
3821
    /* signal CPU creation */
3822
    qemu_mutex_lock(&qemu_global_mutex);
3823
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3824
        env->created = 1;
3825
    qemu_cond_signal(&qemu_cpu_cond);
3826

    
3827
    /* and wait for machine initialization */
3828
    while (!qemu_system_ready)
3829
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3830

    
3831
    while (1) {
3832
        tcg_cpu_exec();
3833
        qemu_wait_io_event(cur_cpu);
3834
    }
3835

    
3836
    return NULL;
3837
}
3838

    
3839
void qemu_cpu_kick(void *_env)
3840
{
3841
    CPUState *env = _env;
3842
    qemu_cond_broadcast(env->halt_cond);
3843
    if (kvm_enabled())
3844
        qemu_thread_signal(env->thread, SIGUSR1);
3845
}
3846

    
3847
int qemu_cpu_self(void *env)
3848
{
3849
    return (cpu_single_env != NULL);
3850
}
3851

    
3852
static void cpu_signal(int sig)
3853
{
3854
    if (cpu_single_env)
3855
        cpu_exit(cpu_single_env);
3856
}
3857

    
3858
static void block_io_signals(void)
3859
{
3860
    sigset_t set;
3861
    struct sigaction sigact;
3862

    
3863
    sigemptyset(&set);
3864
    sigaddset(&set, SIGUSR2);
3865
    sigaddset(&set, SIGIO);
3866
    sigaddset(&set, SIGALRM);
3867
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3868

    
3869
    sigemptyset(&set);
3870
    sigaddset(&set, SIGUSR1);
3871
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3872

    
3873
    memset(&sigact, 0, sizeof(sigact));
3874
    sigact.sa_handler = cpu_signal;
3875
    sigaction(SIGUSR1, &sigact, NULL);
3876
}
3877

    
3878
static void unblock_io_signals(void)
3879
{
3880
    sigset_t set;
3881

    
3882
    sigemptyset(&set);
3883
    sigaddset(&set, SIGUSR2);
3884
    sigaddset(&set, SIGIO);
3885
    sigaddset(&set, SIGALRM);
3886
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3887

    
3888
    sigemptyset(&set);
3889
    sigaddset(&set, SIGUSR1);
3890
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3891
}
3892

    
3893
static void qemu_signal_lock(unsigned int msecs)
3894
{
3895
    qemu_mutex_lock(&qemu_fair_mutex);
3896

    
3897
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3898
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3899
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3900
            break;
3901
    }
3902
    qemu_mutex_unlock(&qemu_fair_mutex);
3903
}
3904

    
3905
static void qemu_mutex_lock_iothread(void)
3906
{
3907
    if (kvm_enabled()) {
3908
        qemu_mutex_lock(&qemu_fair_mutex);
3909
        qemu_mutex_lock(&qemu_global_mutex);
3910
        qemu_mutex_unlock(&qemu_fair_mutex);
3911
    } else
3912
        qemu_signal_lock(100);
3913
}
3914

    
3915
static void qemu_mutex_unlock_iothread(void)
3916
{
3917
    qemu_mutex_unlock(&qemu_global_mutex);
3918
}
3919

    
3920
static int all_vcpus_paused(void)
3921
{
3922
    CPUState *penv = first_cpu;
3923

    
3924
    while (penv) {
3925
        if (!penv->stopped)
3926
            return 0;
3927
        penv = (CPUState *)penv->next_cpu;
3928
    }
3929

    
3930
    return 1;
3931
}
3932

    
3933
static void pause_all_vcpus(void)
3934
{
3935
    CPUState *penv = first_cpu;
3936

    
3937
    while (penv) {
3938
        penv->stop = 1;
3939
        qemu_thread_signal(penv->thread, SIGUSR1);
3940
        qemu_cpu_kick(penv);
3941
        penv = (CPUState *)penv->next_cpu;
3942
    }
3943

    
3944
    while (!all_vcpus_paused()) {
3945
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3946
        penv = first_cpu;
3947
        while (penv) {
3948
            qemu_thread_signal(penv->thread, SIGUSR1);
3949
            penv = (CPUState *)penv->next_cpu;
3950
        }
3951
    }
3952
}
3953

    
3954
static void resume_all_vcpus(void)
3955
{
3956
    CPUState *penv = first_cpu;
3957

    
3958
    while (penv) {
3959
        penv->stop = 0;
3960
        penv->stopped = 0;
3961
        qemu_thread_signal(penv->thread, SIGUSR1);
3962
        qemu_cpu_kick(penv);
3963
        penv = (CPUState *)penv->next_cpu;
3964
    }
3965
}
3966

    
3967
static void tcg_init_vcpu(void *_env)
3968
{
3969
    CPUState *env = _env;
3970
    /* share a single thread for all cpus with TCG */
3971
    if (!tcg_cpu_thread) {
3972
        env->thread = qemu_mallocz(sizeof(QemuThread));
3973
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3974
        qemu_cond_init(env->halt_cond);
3975
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3976
        while (env->created == 0)
3977
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3978
        tcg_cpu_thread = env->thread;
3979
        tcg_halt_cond = env->halt_cond;
3980
    } else {
3981
        env->thread = tcg_cpu_thread;
3982
        env->halt_cond = tcg_halt_cond;
3983
    }
3984
}
3985

    
3986
static void kvm_start_vcpu(CPUState *env)
3987
{
3988
    kvm_init_vcpu(env);
3989
    env->thread = qemu_mallocz(sizeof(QemuThread));
3990
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3991
    qemu_cond_init(env->halt_cond);
3992
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3993
    while (env->created == 0)
3994
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3995
}
3996

    
3997
void qemu_init_vcpu(void *_env)
3998
{
3999
    CPUState *env = _env;
4000

    
4001
    if (kvm_enabled())
4002
        kvm_start_vcpu(env);
4003
    else
4004
        tcg_init_vcpu(env);
4005
}
4006

    
4007
void qemu_notify_event(void)
4008
{
4009
    qemu_event_increment();
4010
}
4011

    
4012
void vm_stop(int reason)
4013
{
4014
    QemuThread me;
4015
    qemu_thread_self(&me);
4016

    
4017
    if (!qemu_thread_equal(&me, &io_thread)) {
4018
        qemu_system_vmstop_request(reason);
4019
        /*
4020
         * FIXME: should not return to device code in case
4021
         * vm_stop() has been requested.
4022
         */
4023
        if (cpu_single_env) {
4024
            cpu_exit(cpu_single_env);
4025
            cpu_single_env->stop = 1;
4026
        }
4027
        return;
4028
    }
4029
    do_vm_stop(reason);
4030
}
4031

    
4032
#endif
4033

    
4034

    
4035
#ifdef _WIN32
4036
static void host_main_loop_wait(int *timeout)
4037
{
4038
    int ret, ret2, i;
4039
    PollingEntry *pe;
4040

    
4041

    
4042
    /* XXX: need to suppress polling by better using win32 events */
4043
    ret = 0;
4044
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4045
        ret |= pe->func(pe->opaque);
4046
    }
4047
    if (ret == 0) {
4048
        int err;
4049
        WaitObjects *w = &wait_objects;
4050

    
4051
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4052
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4053
            if (w->func[ret - WAIT_OBJECT_0])
4054
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4055

    
4056
            /* Check for additional signaled events */
4057
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4058

    
4059
                /* Check if event is signaled */
4060
                ret2 = WaitForSingleObject(w->events[i], 0);
4061
                if(ret2 == WAIT_OBJECT_0) {
4062
                    if (w->func[i])
4063
                        w->func[i](w->opaque[i]);
4064
                } else if (ret2 == WAIT_TIMEOUT) {
4065
                } else {
4066
                    err = GetLastError();
4067
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4068
                }
4069
            }
4070
        } else if (ret == WAIT_TIMEOUT) {
4071
        } else {
4072
            err = GetLastError();
4073
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4074
        }
4075
    }
4076

    
4077
    *timeout = 0;
4078
}
4079
#else
4080
static void host_main_loop_wait(int *timeout)
4081
{
4082
}
4083
#endif
4084

    
4085
void main_loop_wait(int timeout)
4086
{
4087
    IOHandlerRecord *ioh;
4088
    fd_set rfds, wfds, xfds;
4089
    int ret, nfds;
4090
    struct timeval tv;
4091

    
4092
    qemu_bh_update_timeout(&timeout);
4093

    
4094
    host_main_loop_wait(&timeout);
4095

    
4096
    /* poll any events */
4097
    /* XXX: separate device handlers from system ones */
4098
    nfds = -1;
4099
    FD_ZERO(&rfds);
4100
    FD_ZERO(&wfds);
4101
    FD_ZERO(&xfds);
4102
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4103
        if (ioh->deleted)
4104
            continue;
4105
        if (ioh->fd_read &&
4106
            (!ioh->fd_read_poll ||
4107
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4108
            FD_SET(ioh->fd, &rfds);
4109
            if (ioh->fd > nfds)
4110
                nfds = ioh->fd;
4111
        }
4112
        if (ioh->fd_write) {
4113
            FD_SET(ioh->fd, &wfds);
4114
            if (ioh->fd > nfds)
4115
                nfds = ioh->fd;
4116
        }
4117
    }
4118

    
4119
    tv.tv_sec = timeout / 1000;
4120
    tv.tv_usec = (timeout % 1000) * 1000;
4121

    
4122
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4123

    
4124
    qemu_mutex_unlock_iothread();
4125
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4126
    qemu_mutex_lock_iothread();
4127
    if (ret > 0) {
4128
        IOHandlerRecord **pioh;
4129

    
4130
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4131
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4132
                ioh->fd_read(ioh->opaque);
4133
            }
4134
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4135
                ioh->fd_write(ioh->opaque);
4136
            }
4137
        }
4138

    
4139
        /* remove deleted IO handlers */
4140
        pioh = &first_io_handler;
4141
        while (*pioh) {
4142
            ioh = *pioh;
4143
            if (ioh->deleted) {
4144
                *pioh = ioh->next;
4145
                qemu_free(ioh);
4146
            } else
4147
                pioh = &ioh->next;
4148
        }
4149
    }
4150

    
4151
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4152

    
4153
    /* rearm timer, if not periodic */
4154
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4155
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4156
        qemu_rearm_alarm_timer(alarm_timer);
4157
    }
4158

    
4159
    /* vm time timers */
4160
    if (vm_running) {
4161
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4162
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4163
                qemu_get_clock(vm_clock));
4164
    }
4165

    
4166
    /* real time timers */
4167
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4168
                    qemu_get_clock(rt_clock));
4169

    
4170
    /* Check bottom-halves last in case any of the earlier events triggered
4171
       them.  */
4172
    qemu_bh_poll();
4173

    
4174
}
4175

    
4176
static int qemu_cpu_exec(CPUState *env)
4177
{
4178
    int ret;
4179
#ifdef CONFIG_PROFILER
4180
    int64_t ti;
4181
#endif
4182

    
4183
#ifdef CONFIG_PROFILER
4184
    ti = profile_getclock();
4185
#endif
4186
    if (use_icount) {
4187
        int64_t count;
4188
        int decr;
4189
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4190
        env->icount_decr.u16.low = 0;
4191
        env->icount_extra = 0;
4192
        count = qemu_next_deadline();
4193
        count = (count + (1 << icount_time_shift) - 1)
4194
                >> icount_time_shift;
4195
        qemu_icount += count;
4196
        decr = (count > 0xffff) ? 0xffff : count;
4197
        count -= decr;
4198
        env->icount_decr.u16.low = decr;
4199
        env->icount_extra = count;
4200
    }
4201
    ret = cpu_exec(env);
4202
#ifdef CONFIG_PROFILER
4203
    qemu_time += profile_getclock() - ti;
4204
#endif
4205
    if (use_icount) {
4206
        /* Fold pending instructions back into the
4207
           instruction counter, and clear the interrupt flag.  */
4208
        qemu_icount -= (env->icount_decr.u16.low
4209
                        + env->icount_extra);
4210
        env->icount_decr.u32 = 0;
4211
        env->icount_extra = 0;
4212
    }
4213
    return ret;
4214
}
4215

    
4216
static void tcg_cpu_exec(void)
4217
{
4218
    int ret = 0;
4219

    
4220
    if (next_cpu == NULL)
4221
        next_cpu = first_cpu;
4222
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4223
        CPUState *env = cur_cpu = next_cpu;
4224

    
4225
        if (!vm_running)
4226
            break;
4227
        if (timer_alarm_pending) {
4228
            timer_alarm_pending = 0;
4229
            break;
4230
        }
4231
        if (cpu_can_run(env))
4232
            ret = qemu_cpu_exec(env);
4233
        if (ret == EXCP_DEBUG) {
4234
            gdb_set_stop_cpu(env);
4235
            debug_requested = 1;
4236
            break;
4237
        }
4238
    }
4239
}
4240

    
4241
static int cpu_has_work(CPUState *env)
4242
{
4243
    if (env->stop)
4244
        return 1;
4245
    if (env->stopped)
4246
        return 0;
4247
    if (!env->halted)
4248
        return 1;
4249
    if (qemu_cpu_has_work(env))
4250
        return 1;
4251
    return 0;
4252
}
4253

    
4254
static int tcg_has_work(void)
4255
{
4256
    CPUState *env;
4257

    
4258
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4259
        if (cpu_has_work(env))
4260
            return 1;
4261
    return 0;
4262
}
4263

    
4264
static int qemu_calculate_timeout(void)
4265
{
4266
#ifndef CONFIG_IOTHREAD
4267
    int timeout;
4268

    
4269
    if (!vm_running)
4270
        timeout = 5000;
4271
    else if (tcg_has_work())
4272
        timeout = 0;
4273
    else if (!use_icount)
4274
        timeout = 5000;
4275
    else {
4276
     /* XXX: use timeout computed from timers */
4277
        int64_t add;
4278
        int64_t delta;
4279
        /* Advance virtual time to the next event.  */
4280
        if (use_icount == 1) {
4281
            /* When not using an adaptive execution frequency
4282
               we tend to get badly out of sync with real time,
4283
               so just delay for a reasonable amount of time.  */
4284
            delta = 0;
4285
        } else {
4286
            delta = cpu_get_icount() - cpu_get_clock();
4287
        }
4288
        if (delta > 0) {
4289
            /* If virtual time is ahead of real time then just
4290
               wait for IO.  */
4291
            timeout = (delta / 1000000) + 1;
4292
        } else {
4293
            /* Wait for either IO to occur or the next
4294
               timer event.  */
4295
            add = qemu_next_deadline();
4296
            /* We advance the timer before checking for IO.
4297
               Limit the amount we advance so that early IO
4298
               activity won't get the guest too far ahead.  */
4299
            if (add > 10000000)
4300
                add = 10000000;
4301
            delta += add;
4302
            add = (add + (1 << icount_time_shift) - 1)
4303
                  >> icount_time_shift;
4304
            qemu_icount += add;
4305
            timeout = delta / 1000000;
4306
            if (timeout < 0)
4307
                timeout = 0;
4308
        }
4309
    }
4310

    
4311
    return timeout;
4312
#else /* CONFIG_IOTHREAD */
4313
    return 1000;
4314
#endif
4315
}
4316

    
4317
static int vm_can_run(void)
4318
{
4319
    if (powerdown_requested)
4320
        return 0;
4321
    if (reset_requested)
4322
        return 0;
4323
    if (shutdown_requested)
4324
        return 0;
4325
    if (debug_requested)
4326
        return 0;
4327
    return 1;
4328
}
4329

    
4330
static void main_loop(void)
4331
{
4332
    int r;
4333

    
4334
#ifdef CONFIG_IOTHREAD
4335
    qemu_system_ready = 1;
4336
    qemu_cond_broadcast(&qemu_system_cond);
4337
#endif
4338

    
4339
    for (;;) {
4340
        do {
4341
#ifdef CONFIG_PROFILER
4342
            int64_t ti;
4343
#endif
4344
#ifndef CONFIG_IOTHREAD
4345
            tcg_cpu_exec();
4346
#endif
4347
#ifdef CONFIG_PROFILER
4348
            ti = profile_getclock();
4349
#endif
4350
            main_loop_wait(qemu_calculate_timeout());
4351
#ifdef CONFIG_PROFILER
4352
            dev_time += profile_getclock() - ti;
4353
#endif
4354
        } while (vm_can_run());
4355

    
4356
        if (qemu_debug_requested())
4357
            vm_stop(EXCP_DEBUG);
4358
        if (qemu_shutdown_requested()) {
4359
            if (no_shutdown) {
4360
                vm_stop(0);
4361
                no_shutdown = 0;
4362
            } else
4363
                break;
4364
        }
4365
        if (qemu_reset_requested()) {
4366
            pause_all_vcpus();
4367
            qemu_system_reset();
4368
            resume_all_vcpus();
4369
        }
4370
        if (qemu_powerdown_requested())
4371
            qemu_system_powerdown();
4372
        if ((r = qemu_vmstop_requested()))
4373
            vm_stop(r);
4374
    }
4375
    pause_all_vcpus();
4376
}
4377

    
4378
static void version(void)
4379
{
4380
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4381
}
4382

    
4383
static void help(int exitcode)
4384
{
4385
    version();
4386
    printf("usage: %s [options] [disk_image]\n"
4387
           "\n"
4388
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4389
           "\n"
4390
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4391
           opt_help
4392
#define DEFHEADING(text) stringify(text) "\n"
4393
#include "qemu-options.h"
4394
#undef DEF
4395
#undef DEFHEADING
4396
#undef GEN_DOCS
4397
           "\n"
4398
           "During emulation, the following keys are useful:\n"
4399
           "ctrl-alt-f      toggle full screen\n"
4400
           "ctrl-alt-n      switch to virtual console 'n'\n"
4401
           "ctrl-alt        toggle mouse and keyboard grab\n"
4402
           "\n"
4403
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4404
           ,
4405
           "qemu",
4406
           DEFAULT_RAM_SIZE,
4407
#ifndef _WIN32
4408
           DEFAULT_NETWORK_SCRIPT,
4409
           DEFAULT_NETWORK_DOWN_SCRIPT,
4410
#endif
4411
           DEFAULT_GDBSTUB_PORT,
4412
           "/tmp/qemu.log");
4413
    exit(exitcode);
4414
}
4415

    
4416
#define HAS_ARG 0x0001
4417

    
4418
enum {
4419
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4420
    opt_enum,
4421
#define DEFHEADING(text)
4422
#include "qemu-options.h"
4423
#undef DEF
4424
#undef DEFHEADING
4425
#undef GEN_DOCS
4426
};
4427

    
4428
typedef struct QEMUOption {
4429
    const char *name;
4430
    int flags;
4431
    int index;
4432
} QEMUOption;
4433

    
4434
static const QEMUOption qemu_options[] = {
4435
    { "h", 0, QEMU_OPTION_h },
4436
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4437
    { option, opt_arg, opt_enum },
4438
#define DEFHEADING(text)
4439
#include "qemu-options.h"
4440
#undef DEF
4441
#undef DEFHEADING
4442
#undef GEN_DOCS
4443
    { NULL },
4444
};
4445

    
4446
#ifdef HAS_AUDIO
4447
struct soundhw soundhw[] = {
4448
#ifdef HAS_AUDIO_CHOICE
4449
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4450
    {
4451
        "pcspk",
4452
        "PC speaker",
4453
        0,
4454
        1,
4455
        { .init_isa = pcspk_audio_init }
4456
    },
4457
#endif
4458

    
4459
#ifdef CONFIG_SB16
4460
    {
4461
        "sb16",
4462
        "Creative Sound Blaster 16",
4463
        0,
4464
        1,
4465
        { .init_isa = SB16_init }
4466
    },
4467
#endif
4468

    
4469
#ifdef CONFIG_CS4231A
4470
    {
4471
        "cs4231a",
4472
        "CS4231A",
4473
        0,
4474
        1,
4475
        { .init_isa = cs4231a_init }
4476
    },
4477
#endif
4478

    
4479
#ifdef CONFIG_ADLIB
4480
    {
4481
        "adlib",
4482
#ifdef HAS_YMF262
4483
        "Yamaha YMF262 (OPL3)",
4484
#else
4485
        "Yamaha YM3812 (OPL2)",
4486
#endif
4487
        0,
4488
        1,
4489
        { .init_isa = Adlib_init }
4490
    },
4491
#endif
4492

    
4493
#ifdef CONFIG_GUS
4494
    {
4495
        "gus",
4496
        "Gravis Ultrasound GF1",
4497
        0,
4498
        1,
4499
        { .init_isa = GUS_init }
4500
    },
4501
#endif
4502

    
4503
#ifdef CONFIG_AC97
4504
    {
4505
        "ac97",
4506
        "Intel 82801AA AC97 Audio",
4507
        0,
4508
        0,
4509
        { .init_pci = ac97_init }
4510
    },
4511
#endif
4512

    
4513
#ifdef CONFIG_ES1370
4514
    {
4515
        "es1370",
4516
        "ENSONIQ AudioPCI ES1370",
4517
        0,
4518
        0,
4519
        { .init_pci = es1370_init }
4520
    },
4521
#endif
4522

    
4523
#endif /* HAS_AUDIO_CHOICE */
4524

    
4525
    { NULL, NULL, 0, 0, { NULL } }
4526
};
4527

    
4528
static void select_soundhw (const char *optarg)
4529
{
4530
    struct soundhw *c;
4531

    
4532
    if (*optarg == '?') {
4533
    show_valid_cards:
4534

    
4535
        printf ("Valid sound card names (comma separated):\n");
4536
        for (c = soundhw; c->name; ++c) {
4537
            printf ("%-11s %s\n", c->name, c->descr);
4538
        }
4539
        printf ("\n-soundhw all will enable all of the above\n");
4540
        exit (*optarg != '?');
4541
    }
4542
    else {
4543
        size_t l;
4544
        const char *p;
4545
        char *e;
4546
        int bad_card = 0;
4547

    
4548
        if (!strcmp (optarg, "all")) {
4549
            for (c = soundhw; c->name; ++c) {
4550
                c->enabled = 1;
4551
            }
4552
            return;
4553
        }
4554

    
4555
        p = optarg;
4556
        while (*p) {
4557
            e = strchr (p, ',');
4558
            l = !e ? strlen (p) : (size_t) (e - p);
4559

    
4560
            for (c = soundhw; c->name; ++c) {
4561
                if (!strncmp (c->name, p, l)) {
4562
                    c->enabled = 1;
4563
                    break;
4564
                }
4565
            }
4566

    
4567
            if (!c->name) {
4568
                if (l > 80) {
4569
                    fprintf (stderr,
4570
                             "Unknown sound card name (too big to show)\n");
4571
                }
4572
                else {
4573
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4574
                             (int) l, p);
4575
                }
4576
                bad_card = 1;
4577
            }
4578
            p += l + (e != NULL);
4579
        }
4580

    
4581
        if (bad_card)
4582
            goto show_valid_cards;
4583
    }
4584
}
4585
#endif
4586

    
4587
static void select_vgahw (const char *p)
4588
{
4589
    const char *opts;
4590

    
4591
    cirrus_vga_enabled = 0;
4592
    std_vga_enabled = 0;
4593
    vmsvga_enabled = 0;
4594
    xenfb_enabled = 0;
4595
    if (strstart(p, "std", &opts)) {
4596
        std_vga_enabled = 1;
4597
    } else if (strstart(p, "cirrus", &opts)) {
4598
        cirrus_vga_enabled = 1;
4599
    } else if (strstart(p, "vmware", &opts)) {
4600
        vmsvga_enabled = 1;
4601
    } else if (strstart(p, "xenfb", &opts)) {
4602
        xenfb_enabled = 1;
4603
    } else if (!strstart(p, "none", &opts)) {
4604
    invalid_vga:
4605
        fprintf(stderr, "Unknown vga type: %s\n", p);
4606
        exit(1);
4607
    }
4608
    while (*opts) {
4609
        const char *nextopt;
4610

    
4611
        if (strstart(opts, ",retrace=", &nextopt)) {
4612
            opts = nextopt;
4613
            if (strstart(opts, "dumb", &nextopt))
4614
                vga_retrace_method = VGA_RETRACE_DUMB;
4615
            else if (strstart(opts, "precise", &nextopt))
4616
                vga_retrace_method = VGA_RETRACE_PRECISE;
4617
            else goto invalid_vga;
4618
        } else goto invalid_vga;
4619
        opts = nextopt;
4620
    }
4621
}
4622

    
4623
#ifdef TARGET_I386
4624
static int balloon_parse(const char *arg)
4625
{
4626
    char buf[128];
4627
    const char *p;
4628

    
4629
    if (!strcmp(arg, "none")) {
4630
        virtio_balloon = 0;
4631
    } else if (!strncmp(arg, "virtio", 6)) {
4632
        virtio_balloon = 1;
4633
        if (arg[6] == ',')  {
4634
            p = arg + 7;
4635
            if (get_param_value(buf, sizeof(buf), "addr", p)) {
4636
                virtio_balloon_devaddr = strdup(buf);
4637
            }
4638
        }
4639
    } else {
4640
        return -1;
4641
    }
4642
    return 0;
4643
}
4644
#endif
4645

    
4646
#ifdef _WIN32
4647
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4648
{
4649
    exit(STATUS_CONTROL_C_EXIT);
4650
    return TRUE;
4651
}
4652
#endif
4653

    
4654
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4655
{
4656
    int ret;
4657

    
4658
    if(strlen(str) != 36)
4659
        return -1;
4660

    
4661
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4662
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4663
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4664

    
4665
    if(ret != 16)
4666
        return -1;
4667

    
4668
#ifdef TARGET_I386
4669
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4670
#endif
4671

    
4672
    return 0;
4673
}
4674

    
4675
#define MAX_NET_CLIENTS 32
4676

    
4677
#ifndef _WIN32
4678

    
4679
static void termsig_handler(int signal)
4680
{
4681
    qemu_system_shutdown_request();
4682
}
4683

    
4684
static void sigchld_handler(int signal)
4685
{
4686
    waitpid(-1, NULL, WNOHANG);
4687
}
4688

    
4689
static void sighandler_setup(void)
4690
{
4691
    struct sigaction act;
4692

    
4693
    memset(&act, 0, sizeof(act));
4694
    act.sa_handler = termsig_handler;
4695
    sigaction(SIGINT,  &act, NULL);
4696
    sigaction(SIGHUP,  &act, NULL);
4697
    sigaction(SIGTERM, &act, NULL);
4698

    
4699
    act.sa_handler = sigchld_handler;
4700
    act.sa_flags = SA_NOCLDSTOP;
4701
    sigaction(SIGCHLD, &act, NULL);
4702
}
4703

    
4704
#endif
4705

    
4706
#ifdef _WIN32
4707
/* Look for support files in the same directory as the executable.  */
4708
static char *find_datadir(const char *argv0)
4709
{
4710
    char *p;
4711
    char buf[MAX_PATH];
4712
    DWORD len;
4713

    
4714
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4715
    if (len == 0) {
4716
        return NULL;
4717
    }
4718

    
4719
    buf[len] = 0;
4720
    p = buf + len - 1;
4721
    while (p != buf && *p != '\\')
4722
        p--;
4723
    *p = 0;
4724
    if (access(buf, R_OK) == 0) {
4725
        return qemu_strdup(buf);
4726
    }
4727
    return NULL;
4728
}
4729
#else /* !_WIN32 */
4730

    
4731
/* Find a likely location for support files using the location of the binary.
4732
   For installed binaries this will be "$bindir/../share/qemu".  When
4733
   running from the build tree this will be "$bindir/../pc-bios".  */
4734
#define SHARE_SUFFIX "/share/qemu"
4735
#define BUILD_SUFFIX "/pc-bios"
4736
static char *find_datadir(const char *argv0)
4737
{
4738
    char *dir;
4739
    char *p = NULL;
4740
    char *res;
4741
#ifdef PATH_MAX
4742
    char buf[PATH_MAX];
4743
#endif
4744
    size_t max_len;
4745

    
4746
#if defined(__linux__)
4747
    {
4748
        int len;
4749
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4750
        if (len > 0) {
4751
            buf[len] = 0;
4752
            p = buf;
4753
        }
4754
    }
4755
#elif defined(__FreeBSD__)
4756
    {
4757
        int len;
4758
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4759
        if (len > 0) {
4760
            buf[len] = 0;
4761
            p = buf;
4762
        }
4763
    }
4764
#endif
4765
    /* If we don't have any way of figuring out the actual executable
4766
       location then try argv[0].  */
4767
    if (!p) {
4768
#ifdef PATH_MAX
4769
        p = buf;
4770
#endif
4771
        p = realpath(argv0, p);
4772
        if (!p) {
4773
            return NULL;
4774
        }
4775
    }
4776
    dir = dirname(p);
4777
    dir = dirname(dir);
4778

    
4779
    max_len = strlen(dir) +
4780
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4781
    res = qemu_mallocz(max_len);
4782
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4783
    if (access(res, R_OK)) {
4784
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4785
        if (access(res, R_OK)) {
4786
            qemu_free(res);
4787
            res = NULL;
4788
        }
4789
    }
4790
#ifndef PATH_MAX
4791
    free(p);
4792
#endif
4793
    return res;
4794
}
4795
#undef SHARE_SUFFIX
4796
#undef BUILD_SUFFIX
4797
#endif
4798

    
4799
char *qemu_find_file(int type, const char *name)
4800
{
4801
    int len;
4802
    const char *subdir;
4803
    char *buf;
4804

    
4805
    /* If name contains path separators then try it as a straight path.  */
4806
    if ((strchr(name, '/') || strchr(name, '\\'))
4807
        && access(name, R_OK) == 0) {
4808
        return strdup(name);
4809
    }
4810
    switch (type) {
4811
    case QEMU_FILE_TYPE_BIOS:
4812
        subdir = "";
4813
        break;
4814
    case QEMU_FILE_TYPE_KEYMAP:
4815
        subdir = "keymaps/";
4816
        break;
4817
    default:
4818
        abort();
4819
    }
4820
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4821
    buf = qemu_mallocz(len);
4822
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4823
    if (access(buf, R_OK)) {
4824
        qemu_free(buf);
4825
        return NULL;
4826
    }
4827
    return buf;
4828
}
4829

    
4830
struct device_config {
4831
    enum {
4832
        DEV_GENERIC,   /* -device      */
4833
        DEV_USB,       /* -usbdevice   */
4834
        DEV_BT,        /* -bt          */
4835
    } type;
4836
    const char *cmdline;
4837
    TAILQ_ENTRY(device_config) next;
4838
};
4839
TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4840

    
4841
static void add_device_config(int type, const char *cmdline)
4842
{
4843
    struct device_config *conf;
4844

    
4845
    conf = qemu_mallocz(sizeof(*conf));
4846
    conf->type = type;
4847
    conf->cmdline = cmdline;
4848
    TAILQ_INSERT_TAIL(&device_configs, conf, next);
4849
}
4850

    
4851
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4852
{
4853
    struct device_config *conf;
4854
    int rc;
4855

    
4856
    TAILQ_FOREACH(conf, &device_configs, next) {
4857
        if (conf->type != type)
4858
            continue;
4859
        rc = func(conf->cmdline);
4860
        if (0 != rc)
4861
            return rc;
4862
    }
4863
    return 0;
4864
}
4865

    
4866
static int generic_parse(const char *cmdline)
4867
{
4868
    DeviceState *dev;
4869

    
4870
    dev = qdev_device_add(cmdline);
4871
    if (!dev)
4872
        return -1;
4873
    return 0;
4874
}
4875

    
4876
int main(int argc, char **argv, char **envp)
4877
{
4878
    const char *gdbstub_dev = NULL;
4879
    uint32_t boot_devices_bitmap = 0;
4880
    int i;
4881
    int snapshot, linux_boot, net_boot;
4882
    const char *initrd_filename;
4883
    const char *kernel_filename, *kernel_cmdline;
4884
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4885
    DisplayState *ds;
4886
    DisplayChangeListener *dcl;
4887
    int cyls, heads, secs, translation;
4888
    const char *net_clients[MAX_NET_CLIENTS];
4889
    int nb_net_clients;
4890
    int hda_index;
4891
    int optind;
4892
    const char *r, *optarg;
4893
    CharDriverState *monitor_hd = NULL;
4894
    const char *monitor_device;
4895
    const char *serial_devices[MAX_SERIAL_PORTS];
4896
    int serial_device_index;
4897
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4898
    int parallel_device_index;
4899
    const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4900
    int virtio_console_index;
4901
    const char *loadvm = NULL;
4902
    QEMUMachine *machine;
4903
    const char *cpu_model;
4904
#ifndef _WIN32
4905
    int fds[2];
4906
#endif
4907
    int tb_size;
4908
    const char *pid_file = NULL;
4909
    const char *incoming = NULL;
4910
#ifndef _WIN32
4911
    int fd = 0;
4912
    struct passwd *pwd = NULL;
4913
    const char *chroot_dir = NULL;
4914
    const char *run_as = NULL;
4915
#endif
4916
    CPUState *env;
4917
    int show_vnc_port = 0;
4918

    
4919
    qemu_cache_utils_init(envp);
4920

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

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

    
4964
    serial_devices[0] = "vc:80Cx24C";
4965
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4966
        serial_devices[i] = NULL;
4967
    serial_device_index = 0;
4968

    
4969
    parallel_devices[0] = "vc:80Cx24C";
4970
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4971
        parallel_devices[i] = NULL;
4972
    parallel_device_index = 0;
4973

    
4974
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4975
        virtio_consoles[i] = NULL;
4976
    virtio_console_index = 0;
4977

    
4978
    for (i = 0; i < MAX_NODES; i++) {
4979
        node_mem[i] = 0;
4980
        node_cpumask[i] = 0;
4981
    }
4982

    
4983
    nb_net_clients = 0;
4984
    nb_drives = 0;
4985
    nb_drives_opt = 0;
4986
    nb_numa_nodes = 0;
4987
    hda_index = -1;
4988

    
4989
    nb_nics = 0;
4990

    
4991
    tb_size = 0;
4992
    autostart= 1;
4993

    
4994
    register_watchdogs();
4995

    
4996
    optind = 1;
4997
    for(;;) {
4998
        if (optind >= argc)
4999
            break;
5000
        r = argv[optind];
5001
        if (r[0] != '-') {
5002
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5003
        } else {
5004
            const QEMUOption *popt;
5005

    
5006
            optind++;
5007
            /* Treat --foo the same as -foo.  */
5008
            if (r[1] == '-')
5009
                r++;
5010
            popt = qemu_options;
5011
            for(;;) {
5012
                if (!popt->name) {
5013
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
5014
                            argv[0], r);
5015
                    exit(1);
5016
                }
5017
                if (!strcmp(popt->name, r + 1))
5018
                    break;
5019
                popt++;
5020
            }
5021
            if (popt->flags & HAS_ARG) {
5022
                if (optind >= argc) {
5023
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
5024
                            argv[0], r);
5025
                    exit(1);
5026
                }
5027
                optarg = argv[optind++];
5028
            } else {
5029
                optarg = NULL;
5030
            }
5031

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

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

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

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

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

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

    
5377
                    graphic_width = w;
5378
                    graphic_height = h;
5379
                    graphic_depth = depth;
5380
                }
5381
                break;
5382
#endif
5383
            case QEMU_OPTION_echr:
5384
                {
5385
                    char *r;
5386
                    term_escape_char = strtol(optarg, &r, 0);
5387
                    if (r == optarg)
5388
                        printf("Bad argument to echr\n");
5389
                    break;
5390
                }
5391
            case QEMU_OPTION_monitor:
5392
                monitor_device = optarg;
5393
                break;
5394
            case QEMU_OPTION_serial:
5395
                if (serial_device_index >= MAX_SERIAL_PORTS) {
5396
                    fprintf(stderr, "qemu: too many serial ports\n");
5397
                    exit(1);
5398
                }
5399
                serial_devices[serial_device_index] = optarg;
5400
                serial_device_index++;
5401
                break;
5402
            case QEMU_OPTION_watchdog:
5403
                i = select_watchdog(optarg);
5404
                if (i > 0)
5405
                    exit (i == 1 ? 1 : 0);
5406
                break;
5407
            case QEMU_OPTION_watchdog_action:
5408
                if (select_watchdog_action(optarg) == -1) {
5409
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
5410
                    exit(1);
5411
                }
5412
                break;
5413
            case QEMU_OPTION_virtiocon:
5414
                if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
5415
                    fprintf(stderr, "qemu: too many virtio consoles\n");
5416
                    exit(1);
5417
                }
5418
                virtio_consoles[virtio_console_index] = optarg;
5419
                virtio_console_index++;
5420
                break;
5421
            case QEMU_OPTION_parallel:
5422
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5423
                    fprintf(stderr, "qemu: too many parallel ports\n");
5424
                    exit(1);
5425
                }
5426
                parallel_devices[parallel_device_index] = optarg;
5427
                parallel_device_index++;
5428
                break;
5429
            case QEMU_OPTION_loadvm:
5430
                loadvm = optarg;
5431
                break;
5432
            case QEMU_OPTION_full_screen:
5433
                full_screen = 1;
5434
                break;
5435
#ifdef CONFIG_SDL
5436
            case QEMU_OPTION_no_frame:
5437
                no_frame = 1;
5438
                break;
5439
            case QEMU_OPTION_alt_grab:
5440
                alt_grab = 1;
5441
                break;
5442
            case QEMU_OPTION_no_quit:
5443
                no_quit = 1;
5444
                break;
5445
            case QEMU_OPTION_sdl:
5446
                display_type = DT_SDL;
5447
                break;
5448
#endif
5449
            case QEMU_OPTION_pidfile:
5450
                pid_file = optarg;
5451
                break;
5452
#ifdef TARGET_I386
5453
            case QEMU_OPTION_win2k_hack:
5454
                win2k_install_hack = 1;
5455
                break;
5456
            case QEMU_OPTION_rtc_td_hack:
5457
                rtc_td_hack = 1;
5458
                break;
5459
            case QEMU_OPTION_acpitable:
5460
                if(acpi_table_add(optarg) < 0) {
5461
                    fprintf(stderr, "Wrong acpi table provided\n");
5462
                    exit(1);
5463
                }
5464
                break;
5465
            case QEMU_OPTION_smbios:
5466
                if(smbios_entry_add(optarg) < 0) {
5467
                    fprintf(stderr, "Wrong smbios provided\n");
5468
                    exit(1);
5469
                }
5470
                break;
5471
#endif
5472
#ifdef CONFIG_KQEMU
5473
            case QEMU_OPTION_enable_kqemu:
5474
                kqemu_allowed = 1;
5475
                break;
5476
            case QEMU_OPTION_kernel_kqemu:
5477
                kqemu_allowed = 2;
5478
                break;
5479
#endif
5480
#ifdef CONFIG_KVM
5481
            case QEMU_OPTION_enable_kvm:
5482
                kvm_allowed = 1;
5483
#ifdef CONFIG_KQEMU
5484
                kqemu_allowed = 0;
5485
#endif
5486
                break;
5487
#endif
5488
            case QEMU_OPTION_usb:
5489
                usb_enabled = 1;
5490
                break;
5491
            case QEMU_OPTION_usbdevice:
5492
                usb_enabled = 1;
5493
                add_device_config(DEV_USB, optarg);
5494
                break;
5495
            case QEMU_OPTION_device:
5496
                add_device_config(DEV_GENERIC, optarg);
5497
                break;
5498
            case QEMU_OPTION_smp:
5499
                smp_cpus = atoi(optarg);
5500
                if (smp_cpus < 1) {
5501
                    fprintf(stderr, "Invalid number of CPUs\n");
5502
                    exit(1);
5503
                }
5504
                break;
5505
            case QEMU_OPTION_vnc:
5506
                display_type = DT_VNC;
5507
                vnc_display = optarg;
5508
                break;
5509
#ifdef TARGET_I386
5510
            case QEMU_OPTION_no_acpi:
5511
                acpi_enabled = 0;
5512
                break;
5513
            case QEMU_OPTION_no_hpet:
5514
                no_hpet = 1;
5515
                break;
5516
            case QEMU_OPTION_balloon:
5517
                if (balloon_parse(optarg) < 0) {
5518
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5519
                    exit(1);
5520
                }
5521
                break;
5522
#endif
5523
            case QEMU_OPTION_no_reboot:
5524
                no_reboot = 1;
5525
                break;
5526
            case QEMU_OPTION_no_shutdown:
5527
                no_shutdown = 1;
5528
                break;
5529
            case QEMU_OPTION_show_cursor:
5530
                cursor_hide = 0;
5531
                break;
5532
            case QEMU_OPTION_uuid:
5533
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5534
                    fprintf(stderr, "Fail to parse UUID string."
5535
                            " Wrong format.\n");
5536
                    exit(1);
5537
                }
5538
                break;
5539
#ifndef _WIN32
5540
            case QEMU_OPTION_daemonize:
5541
                daemonize = 1;
5542
                break;
5543
#endif
5544
            case QEMU_OPTION_option_rom:
5545
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5546
                    fprintf(stderr, "Too many option ROMs\n");
5547
                    exit(1);
5548
                }
5549
                option_rom[nb_option_roms] = optarg;
5550
                nb_option_roms++;
5551
                break;
5552
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5553
            case QEMU_OPTION_semihosting:
5554
                semihosting_enabled = 1;
5555
                break;
5556
#endif
5557
            case QEMU_OPTION_name:
5558
                qemu_name = qemu_strdup(optarg);
5559
                 {
5560
                     char *p = strchr(qemu_name, ',');
5561
                     if (p != NULL) {
5562
                        *p++ = 0;
5563
                        if (strncmp(p, "process=", 8)) {
5564
                            fprintf(stderr, "Unknown subargument %s to -name", p);
5565
                            exit(1);
5566
                        }
5567
                        p += 8;
5568
                        set_proc_name(p);
5569
                     }        
5570
                 }        
5571
                break;
5572
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5573
            case QEMU_OPTION_prom_env:
5574
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5575
                    fprintf(stderr, "Too many prom variables\n");
5576
                    exit(1);
5577
                }
5578
                prom_envs[nb_prom_envs] = optarg;
5579
                nb_prom_envs++;
5580
                break;
5581
#endif
5582
#ifdef TARGET_ARM
5583
            case QEMU_OPTION_old_param:
5584
                old_param = 1;
5585
                break;
5586
#endif
5587
            case QEMU_OPTION_clock:
5588
                configure_alarms(optarg);
5589
                break;
5590
            case QEMU_OPTION_startdate:
5591
                {
5592
                    struct tm tm;
5593
                    time_t rtc_start_date;
5594
                    if (!strcmp(optarg, "now")) {
5595
                        rtc_date_offset = -1;
5596
                    } else {
5597
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5598
                               &tm.tm_year,
5599
                               &tm.tm_mon,
5600
                               &tm.tm_mday,
5601
                               &tm.tm_hour,
5602
                               &tm.tm_min,
5603
                               &tm.tm_sec) == 6) {
5604
                            /* OK */
5605
                        } else if (sscanf(optarg, "%d-%d-%d",
5606
                                          &tm.tm_year,
5607
                                          &tm.tm_mon,
5608
                                          &tm.tm_mday) == 3) {
5609
                            tm.tm_hour = 0;
5610
                            tm.tm_min = 0;
5611
                            tm.tm_sec = 0;
5612
                        } else {
5613
                            goto date_fail;
5614
                        }
5615
                        tm.tm_year -= 1900;
5616
                        tm.tm_mon--;
5617
                        rtc_start_date = mktimegm(&tm);
5618
                        if (rtc_start_date == -1) {
5619
                        date_fail:
5620
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
5621
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5622
                            exit(1);
5623
                        }
5624
                        rtc_date_offset = time(NULL) - rtc_start_date;
5625
                    }
5626
                }
5627
                break;
5628
            case QEMU_OPTION_tb_size:
5629
                tb_size = strtol(optarg, NULL, 0);
5630
                if (tb_size < 0)
5631
                    tb_size = 0;
5632
                break;
5633
            case QEMU_OPTION_icount:
5634
                use_icount = 1;
5635
                if (strcmp(optarg, "auto") == 0) {
5636
                    icount_time_shift = -1;
5637
                } else {
5638
                    icount_time_shift = strtol(optarg, NULL, 0);
5639
                }
5640
                break;
5641
            case QEMU_OPTION_incoming:
5642
                incoming = optarg;
5643
                break;
5644
#ifndef _WIN32
5645
            case QEMU_OPTION_chroot:
5646
                chroot_dir = optarg;
5647
                break;
5648
            case QEMU_OPTION_runas:
5649
                run_as = optarg;
5650
                break;
5651
#endif
5652
#ifdef CONFIG_XEN
5653
            case QEMU_OPTION_xen_domid:
5654
                xen_domid = atoi(optarg);
5655
                break;
5656
            case QEMU_OPTION_xen_create:
5657
                xen_mode = XEN_CREATE;
5658
                break;
5659
            case QEMU_OPTION_xen_attach:
5660
                xen_mode = XEN_ATTACH;
5661
                break;
5662
#endif
5663
            }
5664
        }
5665
    }
5666

    
5667
    /* If no data_dir is specified then try to find it relative to the
5668
       executable path.  */
5669
    if (!data_dir) {
5670
        data_dir = find_datadir(argv[0]);
5671
    }
5672
    /* If all else fails use the install patch specified when building.  */
5673
    if (!data_dir) {
5674
        data_dir = CONFIG_QEMU_SHAREDIR;
5675
    }
5676

    
5677
#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5678
    if (kvm_allowed && kqemu_allowed) {
5679
        fprintf(stderr,
5680
                "You can not enable both KVM and kqemu at the same time\n");
5681
        exit(1);
5682
    }
5683
#endif
5684

    
5685
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5686
    if (smp_cpus > machine->max_cpus) {
5687
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5688
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5689
                machine->max_cpus);
5690
        exit(1);
5691
    }
5692

    
5693
    if (display_type == DT_NOGRAPHIC) {
5694
       if (serial_device_index == 0)
5695
           serial_devices[0] = "stdio";
5696
       if (parallel_device_index == 0)
5697
           parallel_devices[0] = "null";
5698
       if (strncmp(monitor_device, "vc", 2) == 0)
5699
           monitor_device = "stdio";
5700
    }
5701

    
5702
#ifndef _WIN32
5703
    if (daemonize) {
5704
        pid_t pid;
5705

    
5706
        if (pipe(fds) == -1)
5707
            exit(1);
5708

    
5709
        pid = fork();
5710
        if (pid > 0) {
5711
            uint8_t status;
5712
            ssize_t len;
5713

    
5714
            close(fds[1]);
5715

    
5716
        again:
5717
            len = read(fds[0], &status, 1);
5718
            if (len == -1 && (errno == EINTR))
5719
                goto again;
5720

    
5721
            if (len != 1)
5722
                exit(1);
5723
            else if (status == 1) {
5724
                fprintf(stderr, "Could not acquire pidfile\n");
5725
                exit(1);
5726
            } else
5727
                exit(0);
5728
        } else if (pid < 0)
5729
            exit(1);
5730

    
5731
        setsid();
5732

    
5733
        pid = fork();
5734
        if (pid > 0)
5735
            exit(0);
5736
        else if (pid < 0)
5737
            exit(1);
5738

    
5739
        umask(027);
5740

    
5741
        signal(SIGTSTP, SIG_IGN);
5742
        signal(SIGTTOU, SIG_IGN);
5743
        signal(SIGTTIN, SIG_IGN);
5744
    }
5745

    
5746
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5747
        if (daemonize) {
5748
            uint8_t status = 1;
5749
            write(fds[1], &status, 1);
5750
        } else
5751
            fprintf(stderr, "Could not acquire pid file\n");
5752
        exit(1);
5753
    }
5754
#endif
5755

    
5756
#ifdef CONFIG_KQEMU
5757
    if (smp_cpus > 1)
5758
        kqemu_allowed = 0;
5759
#endif
5760
    if (qemu_init_main_loop()) {
5761
        fprintf(stderr, "qemu_init_main_loop failed\n");
5762
        exit(1);
5763
    }
5764
    linux_boot = (kernel_filename != NULL);
5765

    
5766
    if (!linux_boot && *kernel_cmdline != '\0') {
5767
        fprintf(stderr, "-append only allowed with -kernel option\n");
5768
        exit(1);
5769
    }
5770

    
5771
    if (!linux_boot && initrd_filename != NULL) {
5772
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5773
        exit(1);
5774
    }
5775

    
5776
    setvbuf(stdout, NULL, _IOLBF, 0);
5777

    
5778
    init_timers();
5779
    if (init_timer_alarm() < 0) {
5780
        fprintf(stderr, "could not initialize alarm timer\n");
5781
        exit(1);
5782
    }
5783
    if (use_icount && icount_time_shift < 0) {
5784
        use_icount = 2;
5785
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5786
           It will be corrected fairly quickly anyway.  */
5787
        icount_time_shift = 3;
5788
        init_icount_adjust();
5789
    }
5790

    
5791
#ifdef _WIN32
5792
    socket_init();
5793
#endif
5794

    
5795
    /* init network clients */
5796
    if (nb_net_clients == 0) {
5797
        /* if no clients, we use a default config */
5798
        net_clients[nb_net_clients++] = "nic";
5799
#ifdef CONFIG_SLIRP
5800
        net_clients[nb_net_clients++] = "user";
5801
#endif
5802
    }
5803

    
5804
    for(i = 0;i < nb_net_clients; i++) {
5805
        if (net_client_parse(net_clients[i]) < 0)
5806
            exit(1);
5807
    }
5808

    
5809
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5810
    net_set_boot_mask(net_boot);
5811

    
5812
    net_client_check();
5813

    
5814
    /* init the bluetooth world */
5815
    if (foreach_device_config(DEV_BT, bt_parse))
5816
        exit(1);
5817

    
5818
    /* init the memory */
5819
    if (ram_size == 0)
5820
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5821

    
5822
#ifdef CONFIG_KQEMU
5823
    /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5824
       guest ram allocation.  It needs to go away.  */
5825
    if (kqemu_allowed) {
5826
        kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5827
        kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5828
        if (!kqemu_phys_ram_base) {
5829
            fprintf(stderr, "Could not allocate physical memory\n");
5830
            exit(1);
5831
        }
5832
    }
5833
#endif
5834

    
5835
    /* init the dynamic translator */
5836
    cpu_exec_init_all(tb_size * 1024 * 1024);
5837

    
5838
    bdrv_init();
5839

    
5840
    /* we always create the cdrom drive, even if no disk is there */
5841

    
5842
    if (nb_drives_opt < MAX_DRIVES)
5843
        drive_add(NULL, CDROM_ALIAS);
5844

    
5845
    /* we always create at least one floppy */
5846

    
5847
    if (nb_drives_opt < MAX_DRIVES)
5848
        drive_add(NULL, FD_ALIAS, 0);
5849

    
5850
    /* we always create one sd slot, even if no card is in it */
5851

    
5852
    if (nb_drives_opt < MAX_DRIVES)
5853
        drive_add(NULL, SD_ALIAS);
5854

    
5855
    /* open the virtual block devices */
5856

    
5857
    for(i = 0; i < nb_drives_opt; i++)
5858
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5859
            exit(1);
5860

    
5861
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5862
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5863

    
5864
#ifndef _WIN32
5865
    /* must be after terminal init, SDL library changes signal handlers */
5866
    sighandler_setup();
5867
#endif
5868

    
5869
    /* Maintain compatibility with multiple stdio monitors */
5870
    if (!strcmp(monitor_device,"stdio")) {
5871
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5872
            const char *devname = serial_devices[i];
5873
            if (devname && !strcmp(devname,"mon:stdio")) {
5874
                monitor_device = NULL;
5875
                break;
5876
            } else if (devname && !strcmp(devname,"stdio")) {
5877
                monitor_device = NULL;
5878
                serial_devices[i] = "mon:stdio";
5879
                break;
5880
            }
5881
        }
5882
    }
5883

    
5884
    if (nb_numa_nodes > 0) {
5885
        int i;
5886

    
5887
        if (nb_numa_nodes > smp_cpus) {
5888
            nb_numa_nodes = smp_cpus;
5889
        }
5890

    
5891
        /* If no memory size if given for any node, assume the default case
5892
         * and distribute the available memory equally across all nodes
5893
         */
5894
        for (i = 0; i < nb_numa_nodes; i++) {
5895
            if (node_mem[i] != 0)
5896
                break;
5897
        }
5898
        if (i == nb_numa_nodes) {
5899
            uint64_t usedmem = 0;
5900

    
5901
            /* On Linux, the each node's border has to be 8MB aligned,
5902
             * the final node gets the rest.
5903
             */
5904
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5905
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5906
                usedmem += node_mem[i];
5907
            }
5908
            node_mem[i] = ram_size - usedmem;
5909
        }
5910

    
5911
        for (i = 0; i < nb_numa_nodes; i++) {
5912
            if (node_cpumask[i] != 0)
5913
                break;
5914
        }
5915
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5916
         * must cope with this anyway, because there are BIOSes out there in
5917
         * real machines which also use this scheme.
5918
         */
5919
        if (i == nb_numa_nodes) {
5920
            for (i = 0; i < smp_cpus; i++) {
5921
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5922
            }
5923
        }
5924
    }
5925

    
5926
    if (kvm_enabled()) {
5927
        int ret;
5928

    
5929
        ret = kvm_init(smp_cpus);
5930
        if (ret < 0) {
5931
            fprintf(stderr, "failed to initialize KVM\n");
5932
            exit(1);
5933
        }
5934
    }
5935

    
5936
    if (monitor_device) {
5937
        monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5938
        if (!monitor_hd) {
5939
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5940
            exit(1);
5941
        }
5942
    }
5943

    
5944
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5945
        const char *devname = serial_devices[i];
5946
        if (devname && strcmp(devname, "none")) {
5947
            char label[32];
5948
            snprintf(label, sizeof(label), "serial%d", i);
5949
            serial_hds[i] = qemu_chr_open(label, devname, NULL);
5950
            if (!serial_hds[i]) {
5951
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5952
                        devname);
5953
                exit(1);
5954
            }
5955
        }
5956
    }
5957

    
5958
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5959
        const char *devname = parallel_devices[i];
5960
        if (devname && strcmp(devname, "none")) {
5961
            char label[32];
5962
            snprintf(label, sizeof(label), "parallel%d", i);
5963
            parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5964
            if (!parallel_hds[i]) {
5965
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5966
                        devname);
5967
                exit(1);
5968
            }
5969
        }
5970
    }
5971

    
5972
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5973
        const char *devname = virtio_consoles[i];
5974
        if (devname && strcmp(devname, "none")) {
5975
            char label[32];
5976
            snprintf(label, sizeof(label), "virtcon%d", i);
5977
            virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5978
            if (!virtcon_hds[i]) {
5979
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5980
                        devname);
5981
                exit(1);
5982
            }
5983
        }
5984
    }
5985

    
5986
    module_call_init(MODULE_INIT_DEVICE);
5987

    
5988
    if (machine->compat_props) {
5989
        qdev_prop_register_compat(machine->compat_props);
5990
    }
5991
    machine->init(ram_size, boot_devices,
5992
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5993

    
5994

    
5995
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5996
        for (i = 0; i < nb_numa_nodes; i++) {
5997
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5998
                env->numa_node = i;
5999
            }
6000
        }
6001
    }
6002

    
6003
    current_machine = machine;
6004

    
6005
    /* init USB devices */
6006
    if (usb_enabled) {
6007
        foreach_device_config(DEV_USB, usb_parse);
6008
    }
6009

    
6010
    /* init generic devices */
6011
    if (foreach_device_config(DEV_GENERIC, generic_parse))
6012
        exit(1);
6013

    
6014
    if (!display_state)
6015
        dumb_display_init();
6016
    /* just use the first displaystate for the moment */
6017
    ds = display_state;
6018

    
6019
    if (display_type == DT_DEFAULT) {
6020
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6021
        display_type = DT_SDL;
6022
#else
6023
        display_type = DT_VNC;
6024
        vnc_display = "localhost:0,to=99";
6025
        show_vnc_port = 1;
6026
#endif
6027
    }
6028
        
6029

    
6030
    switch (display_type) {
6031
    case DT_NOGRAPHIC:
6032
        break;
6033
#if defined(CONFIG_CURSES)
6034
    case DT_CURSES:
6035
        curses_display_init(ds, full_screen);
6036
        break;
6037
#endif
6038
#if defined(CONFIG_SDL)
6039
    case DT_SDL:
6040
        sdl_display_init(ds, full_screen, no_frame);
6041
        break;
6042
#elif defined(CONFIG_COCOA)
6043
    case DT_SDL:
6044
        cocoa_display_init(ds, full_screen);
6045
        break;
6046
#endif
6047
    case DT_VNC:
6048
        vnc_display_init(ds);
6049
        if (vnc_display_open(ds, vnc_display) < 0)
6050
            exit(1);
6051

    
6052
        if (show_vnc_port) {
6053
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6054
        }
6055
        break;
6056
    default:
6057
        break;
6058
    }
6059
    dpy_resize(ds);
6060

    
6061
    dcl = ds->listeners;
6062
    while (dcl != NULL) {
6063
        if (dcl->dpy_refresh != NULL) {
6064
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6065
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6066
        }
6067
        dcl = dcl->next;
6068
    }
6069

    
6070
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6071
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6072
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6073
    }
6074

    
6075
    text_consoles_set_display(display_state);
6076
    qemu_chr_initial_reset();
6077

    
6078
    if (monitor_device && monitor_hd)
6079
        monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6080

    
6081
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6082
        const char *devname = serial_devices[i];
6083
        if (devname && strcmp(devname, "none")) {
6084
            if (strstart(devname, "vc", 0))
6085
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6086
        }
6087
    }
6088

    
6089
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6090
        const char *devname = parallel_devices[i];
6091
        if (devname && strcmp(devname, "none")) {
6092
            if (strstart(devname, "vc", 0))
6093
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6094
        }
6095
    }
6096

    
6097
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6098
        const char *devname = virtio_consoles[i];
6099
        if (virtcon_hds[i] && devname) {
6100
            if (strstart(devname, "vc", 0))
6101
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6102
        }
6103
    }
6104

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

    
6111
    if (loadvm)
6112
        do_loadvm(cur_mon, loadvm);
6113

    
6114
    if (incoming)
6115
        qemu_start_incoming_migration(incoming);
6116

    
6117
    if (autostart)
6118
        vm_start();
6119

    
6120
#ifndef _WIN32
6121
    if (daemonize) {
6122
        uint8_t status = 0;
6123
        ssize_t len;
6124

    
6125
    again1:
6126
        len = write(fds[1], &status, 1);
6127
        if (len == -1 && (errno == EINTR))
6128
            goto again1;
6129

    
6130
        if (len != 1)
6131
            exit(1);
6132

    
6133
        chdir("/");
6134
        TFR(fd = open("/dev/null", O_RDWR));
6135
        if (fd == -1)
6136
            exit(1);
6137
    }
6138

    
6139
    if (run_as) {
6140
        pwd = getpwnam(run_as);
6141
        if (!pwd) {
6142
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6143
            exit(1);
6144
        }
6145
    }
6146

    
6147
    if (chroot_dir) {
6148
        if (chroot(chroot_dir) < 0) {
6149
            fprintf(stderr, "chroot failed\n");
6150
            exit(1);
6151
        }
6152
        chdir("/");
6153
    }
6154

    
6155
    if (run_as) {
6156
        if (setgid(pwd->pw_gid) < 0) {
6157
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6158
            exit(1);
6159
        }
6160
        if (setuid(pwd->pw_uid) < 0) {
6161
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6162
            exit(1);
6163
        }
6164
        if (setuid(0) != -1) {
6165
            fprintf(stderr, "Dropping privileges failed\n");
6166
            exit(1);
6167
        }
6168
    }
6169

    
6170
    if (daemonize) {
6171
        dup2(fd, 0);
6172
        dup2(fd, 1);
6173
        dup2(fd, 2);
6174

    
6175
        close(fd);
6176
    }
6177
#endif
6178

    
6179
    main_loop();
6180
    quit_timers();
6181
    net_cleanup();
6182

    
6183
    return 0;
6184
}