Statistics
| Branch: | Revision:

root / vl.c @ 3b0ba927

History | View | Annotate | Download (155.4 kB)

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

    
32
/* Needed early for 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
struct drivelist drives = TAILQ_HEAD_INITIALIZER(drives);
184
struct driveoptlist driveopts = TAILQ_HEAD_INITIALIZER(driveopts);
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 boot_menu;
253

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

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

    
271
uint8_t qemu_uuid[16];
272

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
383
    return s;
384
}
385

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

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

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

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

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

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

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

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

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

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

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

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

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

    
460
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
461
}
462

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

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

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

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

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

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

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

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

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

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

    
533
#define QEMU_TIMER_BASE 1000000000LL
534

    
535
#ifdef WIN32
536

    
537
static int64_t clock_freq;
538

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

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

    
558
#else
559

    
560
static int use_rt_clock;
561

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

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

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

    
610
/***********************************************************/
611
/* guest cycle counter */
612

    
613
static int64_t cpu_ticks_prev;
614
static int64_t cpu_ticks_offset;
615
static int64_t cpu_clock_offset;
616
static int cpu_ticks_enabled;
617

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

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

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

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

    
672
/***********************************************************/
673
/* timers */
674

    
675
#define QEMU_TIMER_REALTIME 0
676
#define QEMU_TIMER_VIRTUAL  1
677

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

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

    
691
struct qemu_alarm_timer {
692
    char const *name;
693
    unsigned int flags;
694

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

    
701
#define ALARM_FLAG_DYNTICKS  0x1
702
#define ALARM_FLAG_EXPIRED   0x2
703

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

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

    
714
    t->rearm(t);
715
}
716

    
717
/* TODO: MIN_TIMER_REARM_US should be optimized */
718
#define MIN_TIMER_REARM_US 250
719

    
720
static struct qemu_alarm_timer *alarm_timer;
721

    
722
#ifdef _WIN32
723

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

    
729
static int win32_start_timer(struct qemu_alarm_timer *t);
730
static void win32_stop_timer(struct qemu_alarm_timer *t);
731
static void win32_rearm_timer(struct qemu_alarm_timer *t);
732

    
733
#else
734

    
735
static int unix_start_timer(struct qemu_alarm_timer *t);
736
static void unix_stop_timer(struct qemu_alarm_timer *t);
737

    
738
#ifdef __linux__
739

    
740
static int dynticks_start_timer(struct qemu_alarm_timer *t);
741
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
742
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
743

    
744
static int hpet_start_timer(struct qemu_alarm_timer *t);
745
static void hpet_stop_timer(struct qemu_alarm_timer *t);
746

    
747
static int rtc_start_timer(struct qemu_alarm_timer *t);
748
static void rtc_stop_timer(struct qemu_alarm_timer *t);
749

    
750
#endif /* __linux__ */
751

    
752
#endif /* _WIN32 */
753

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

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

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

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

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

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

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

    
839
static void show_available_alarms(void)
840
{
841
    int i;
842

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

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

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

    
862
    arg = strdup(opt);
863

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

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

    
877
        if (i < cur)
878
            /* Ignore */
879
            goto next;
880

    
881
        /* Swap */
882
        tmp = alarm_timers[i];
883
        alarm_timers[i] = alarm_timers[cur];
884
        alarm_timers[cur] = tmp;
885

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

    
891
    free(arg);
892

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

    
903
QEMUClock *rt_clock;
904
QEMUClock *vm_clock;
905

    
906
static QEMUTimer *active_timers[2];
907

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

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

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

    
927
void qemu_free_timer(QEMUTimer *ts)
928
{
929
    qemu_free(ts);
930
}
931

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

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

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

    
958
    qemu_del_timer(ts);
959

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1094
static void qemu_event_increment(void);
1095

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

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

    
1158
static int64_t qemu_next_deadline(void)
1159
{
1160
    int64_t delta;
1161

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

    
1170
    if (delta < 0)
1171
        delta = 0;
1172

    
1173
    return delta;
1174
}
1175

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

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

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

    
1194
    if (delta < MIN_TIMER_REARM_US)
1195
        delta = MIN_TIMER_REARM_US;
1196

    
1197
    return delta;
1198
}
1199
#endif
1200

    
1201
#ifndef _WIN32
1202

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

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

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

    
1215
    return 0;
1216
}
1217

    
1218
#if defined(__linux__)
1219

    
1220
#define RTC_FREQ 1024
1221

    
1222
static void enable_sigio_timer(int fd)
1223
{
1224
    struct sigaction act;
1225

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

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

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

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

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

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

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

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

    
1269
    enable_sigio_timer(fd);
1270
    t->priv = (void *)(long)fd;
1271

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

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

    
1282
    close(fd);
1283
}
1284

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

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

    
1307
    enable_sigio_timer(rtc_fd);
1308

    
1309
    t->priv = (void *)(long)rtc_fd;
1310

    
1311
    return 0;
1312
}
1313

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

    
1318
    close(rtc_fd);
1319
}
1320

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

    
1327
    sigfillset(&act.sa_mask);
1328
    act.sa_flags = 0;
1329
    act.sa_handler = host_alarm_handler;
1330

    
1331
    sigaction(SIGALRM, &act, NULL);
1332

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

    
1342
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1343
        perror("timer_create");
1344

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

    
1348
        return -1;
1349
    }
1350

    
1351
    t->priv = (void *)(long)host_timer;
1352

    
1353
    return 0;
1354
}
1355

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

    
1360
    timer_delete(host_timer);
1361
}
1362

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

    
1370
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1371
                !active_timers[QEMU_TIMER_VIRTUAL])
1372
        return;
1373

    
1374
    nearest_delta_us = qemu_next_deadline_dyntick();
1375

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

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

    
1397
#endif /* defined(__linux__) */
1398

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

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

    
1410
    sigaction(SIGALRM, &act, NULL);
1411

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

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

    
1422
    return 0;
1423
}
1424

    
1425
static void unix_stop_timer(struct qemu_alarm_timer *t)
1426
{
1427
    struct itimerval itv;
1428

    
1429
    memset(&itv, 0, sizeof(itv));
1430
    setitimer(ITIMER_REAL, &itv, NULL);
1431
}
1432

    
1433
#endif /* !defined(_WIN32) */
1434

    
1435

    
1436
#ifdef _WIN32
1437

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

    
1444
    memset(&tc, 0, sizeof(tc));
1445
    timeGetDevCaps(&tc, sizeof(tc));
1446

    
1447
    if (data->period < tc.wPeriodMin)
1448
        data->period = tc.wPeriodMin;
1449

    
1450
    timeBeginPeriod(data->period);
1451

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

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

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

    
1470
    return 0;
1471
}
1472

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

    
1477
    timeKillEvent(data->timerId);
1478
    timeEndPeriod(data->period);
1479
}
1480

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

    
1486
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1487
                !active_timers[QEMU_TIMER_VIRTUAL])
1488
        return;
1489

    
1490
    nearest_delta_us = qemu_next_deadline_dyntick();
1491
    nearest_delta_us /= 1000;
1492

    
1493
    timeKillEvent(data->timerId);
1494

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

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

    
1504
        timeEndPeriod(data->period);
1505
        exit(1);
1506
    }
1507
}
1508

    
1509
#endif /* _WIN32 */
1510

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

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

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

    
1524
    if (err) {
1525
        err = -ENOENT;
1526
        goto fail;
1527
    }
1528

    
1529
    alarm_timer = t;
1530

    
1531
    return 0;
1532

    
1533
fail:
1534
    return err;
1535
}
1536

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

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

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

    
1562
    memcpy(tm, ret, sizeof(struct tm));
1563
}
1564

    
1565
int qemu_timedate_diff(struct tm *tm)
1566
{
1567
    time_t seconds;
1568

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

    
1577
    return seconds - time(NULL);
1578
}
1579

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1716
    return hci_table[cur_hci++];
1717
}
1718

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

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

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

    
1746
    return 0;
1747
}
1748

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

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

    
1759
    hci = hci_init(str);
1760
    if (!hci)
1761
        return -1;
1762

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

    
1771
    hci_table[nb_hcis++] = hci;
1772

    
1773
    return 0;
1774
}
1775

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

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

    
1784
    bt_vhci_init(bt_new_hci(vlan));
1785
}
1786

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

    
1795
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1796

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

    
1805
    vlan = qemu_find_bt_vlan(vlan_id);
1806

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

    
1811
    if (!strcmp(devname, "keyboard"))
1812
        return bt_keyboard_init(vlan);
1813

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

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

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

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

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

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

    
1857
/***********************************************************/
1858
/* QEMU Block devices */
1859

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

    
1867
DriveOpt *drive_add(const char *file, const char *fmt, ...)
1868
{
1869
    va_list ap;
1870
    DriveOpt *dopt;
1871

    
1872
    dopt = qemu_mallocz(sizeof(*dopt));
1873

    
1874
    dopt->file = file;
1875
    va_start(ap, fmt);
1876
    vsnprintf(dopt->opt,
1877
              sizeof(dopt->opt), fmt, ap);
1878
    va_end(ap);
1879

    
1880
    TAILQ_INSERT_TAIL(&driveopts, dopt, next);
1881
    return dopt;
1882
}
1883

    
1884
void drive_remove(DriveOpt *dopt)
1885
{
1886
    TAILQ_REMOVE(&driveopts, dopt, next);
1887
    qemu_free(dopt);
1888
}
1889

    
1890
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1891
{
1892
    DriveInfo *dinfo;
1893

    
1894
    /* seek interface, bus and unit */
1895

    
1896
    TAILQ_FOREACH(dinfo, &drives, next) {
1897
        if (dinfo->type == type &&
1898
            dinfo->bus == bus &&
1899
            dinfo->unit == unit)
1900
            return dinfo;
1901
    }
1902

    
1903
    return NULL;
1904
}
1905

    
1906
DriveInfo *drive_get_by_id(char *id)
1907
{
1908
    DriveInfo *dinfo;
1909

    
1910
    TAILQ_FOREACH(dinfo, &drives, next) {
1911
        if (strcmp(id, dinfo->id))
1912
            continue;
1913
        return dinfo;
1914
    }
1915
    return NULL;
1916
}
1917

    
1918
int drive_get_max_bus(BlockInterfaceType type)
1919
{
1920
    int max_bus;
1921
    DriveInfo *dinfo;
1922

    
1923
    max_bus = -1;
1924
    TAILQ_FOREACH(dinfo, &drives, next) {
1925
        if(dinfo->type == type &&
1926
           dinfo->bus > max_bus)
1927
            max_bus = dinfo->bus;
1928
    }
1929
    return max_bus;
1930
}
1931

    
1932
const char *drive_get_serial(BlockDriverState *bdrv)
1933
{
1934
    DriveInfo *dinfo;
1935

    
1936
    TAILQ_FOREACH(dinfo, &drives, next) {
1937
        if (dinfo->bdrv == bdrv)
1938
            return dinfo->serial;
1939
    }
1940

    
1941
    return "\0";
1942
}
1943

    
1944
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1945
{
1946
    DriveInfo *dinfo;
1947

    
1948
    TAILQ_FOREACH(dinfo, &drives, next) {
1949
        if (dinfo->bdrv == bdrv)
1950
            return dinfo->onerror;
1951
    }
1952

    
1953
    return BLOCK_ERR_STOP_ENOSPC;
1954
}
1955

    
1956
static void bdrv_format_print(void *opaque, const char *name)
1957
{
1958
    fprintf(stderr, " %s", name);
1959
}
1960

    
1961
void drive_uninit(BlockDriverState *bdrv)
1962
{
1963
    DriveInfo *dinfo;
1964

    
1965
    TAILQ_FOREACH(dinfo, &drives, next) {
1966
        if (dinfo->bdrv != bdrv)
1967
            continue;
1968
        drive_remove(dinfo->opt);
1969
        TAILQ_REMOVE(&drives, dinfo, next);
1970
        qemu_free(dinfo);
1971
        break;
1972
    }
1973
}
1974

    
1975
DriveInfo *drive_init(DriveOpt *arg, int snapshot, void *opaque,
1976
                      int *fatal_error)
1977
{
1978
    char buf[128];
1979
    char file[1024];
1980
    char devname[128];
1981
    char serial[21];
1982
    const char *mediastr = "";
1983
    BlockInterfaceType type;
1984
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1985
    int bus_id, unit_id;
1986
    int cyls, heads, secs, translation;
1987
    BlockDriver *drv = NULL;
1988
    QEMUMachine *machine = opaque;
1989
    int max_devs;
1990
    int index;
1991
    int cache;
1992
    int bdrv_flags, onerror;
1993
    const char *devaddr;
1994
    DriveInfo *dinfo;
1995
    char *str = arg->opt;
1996
    static const char * const params[] = { "bus", "unit", "if", "index",
1997
                                           "cyls", "heads", "secs", "trans",
1998
                                           "media", "snapshot", "file",
1999
                                           "cache", "format", "serial",
2000
                                           "werror", "addr", "id",
2001
                                           NULL };
2002
    *fatal_error = 1;
2003

    
2004
    if (check_params(buf, sizeof(buf), params, str) < 0) {
2005
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2006
                         buf, str);
2007
         return NULL;
2008
    }
2009

    
2010
    file[0] = 0;
2011
    cyls = heads = secs = 0;
2012
    bus_id = 0;
2013
    unit_id = -1;
2014
    translation = BIOS_ATA_TRANSLATION_AUTO;
2015
    index = -1;
2016
    cache = 1;
2017

    
2018
    if (machine->use_scsi) {
2019
        type = IF_SCSI;
2020
        max_devs = MAX_SCSI_DEVS;
2021
        pstrcpy(devname, sizeof(devname), "scsi");
2022
    } else {
2023
        type = IF_IDE;
2024
        max_devs = MAX_IDE_DEVS;
2025
        pstrcpy(devname, sizeof(devname), "ide");
2026
    }
2027
    media = MEDIA_DISK;
2028

    
2029
    /* extract parameters */
2030

    
2031
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2032
        bus_id = strtol(buf, NULL, 0);
2033
        if (bus_id < 0) {
2034
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2035
            return NULL;
2036
        }
2037
    }
2038

    
2039
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2040
        unit_id = strtol(buf, NULL, 0);
2041
        if (unit_id < 0) {
2042
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2043
            return NULL;
2044
        }
2045
    }
2046

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

    
2079
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2080
        index = strtol(buf, NULL, 0);
2081
        if (index < 0) {
2082
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2083
            return NULL;
2084
        }
2085
    }
2086

    
2087
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2088
        cyls = strtol(buf, NULL, 0);
2089
    }
2090

    
2091
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2092
        heads = strtol(buf, NULL, 0);
2093
    }
2094

    
2095
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2096
        secs = strtol(buf, NULL, 0);
2097
    }
2098

    
2099
    if (cyls || heads || secs) {
2100
        if (cyls < 1 || cyls > 16383) {
2101
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2102
            return NULL;
2103
        }
2104
        if (heads < 1 || heads > 16) {
2105
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2106
            return NULL;
2107
        }
2108
        if (secs < 1 || secs > 63) {
2109
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2110
            return NULL;
2111
        }
2112
    }
2113

    
2114
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2115
        if (!cyls) {
2116
            fprintf(stderr,
2117
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2118
                    str);
2119
            return NULL;
2120
        }
2121
        if (!strcmp(buf, "none"))
2122
            translation = BIOS_ATA_TRANSLATION_NONE;
2123
        else if (!strcmp(buf, "lba"))
2124
            translation = BIOS_ATA_TRANSLATION_LBA;
2125
        else if (!strcmp(buf, "auto"))
2126
            translation = BIOS_ATA_TRANSLATION_AUTO;
2127
        else {
2128
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2129
            return NULL;
2130
        }
2131
    }
2132

    
2133
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2134
        if (!strcmp(buf, "disk")) {
2135
            media = MEDIA_DISK;
2136
        } else if (!strcmp(buf, "cdrom")) {
2137
            if (cyls || secs || heads) {
2138
                fprintf(stderr,
2139
                        "qemu: '%s' invalid physical CHS format\n", str);
2140
                return NULL;
2141
            }
2142
            media = MEDIA_CDROM;
2143
        } else {
2144
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2145
            return NULL;
2146
        }
2147
    }
2148

    
2149
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2150
        if (!strcmp(buf, "on"))
2151
            snapshot = 1;
2152
        else if (!strcmp(buf, "off"))
2153
            snapshot = 0;
2154
        else {
2155
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2156
            return NULL;
2157
        }
2158
    }
2159

    
2160
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2161
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2162
            cache = 0;
2163
        else if (!strcmp(buf, "writethrough"))
2164
            cache = 1;
2165
        else if (!strcmp(buf, "writeback"))
2166
            cache = 2;
2167
        else {
2168
           fprintf(stderr, "qemu: invalid cache option\n");
2169
           return NULL;
2170
        }
2171
    }
2172

    
2173
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2174
       if (strcmp(buf, "?") == 0) {
2175
            fprintf(stderr, "qemu: Supported formats:");
2176
            bdrv_iterate_format(bdrv_format_print, NULL);
2177
            fprintf(stderr, "\n");
2178
            return NULL;
2179
        }
2180
        drv = bdrv_find_format(buf);
2181
        if (!drv) {
2182
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2183
            return NULL;
2184
        }
2185
    }
2186

    
2187
    if (arg->file == NULL)
2188
        get_param_value(file, sizeof(file), "file", str);
2189
    else
2190
        pstrcpy(file, sizeof(file), arg->file);
2191

    
2192
    if (!get_param_value(serial, sizeof(serial), "serial", str))
2193
            memset(serial, 0,  sizeof(serial));
2194

    
2195
    onerror = BLOCK_ERR_STOP_ENOSPC;
2196
    if (get_param_value(buf, sizeof(serial), "werror", str)) {
2197
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2198
            fprintf(stderr, "werror is no supported by this format\n");
2199
            return NULL;
2200
        }
2201
        if (!strcmp(buf, "ignore"))
2202
            onerror = BLOCK_ERR_IGNORE;
2203
        else if (!strcmp(buf, "enospc"))
2204
            onerror = BLOCK_ERR_STOP_ENOSPC;
2205
        else if (!strcmp(buf, "stop"))
2206
            onerror = BLOCK_ERR_STOP_ANY;
2207
        else if (!strcmp(buf, "report"))
2208
            onerror = BLOCK_ERR_REPORT;
2209
        else {
2210
            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2211
            return NULL;
2212
        }
2213
    }
2214

    
2215
    devaddr = NULL;
2216
    if (get_param_value(buf, sizeof(buf), "addr", str)) {
2217
        if (type != IF_VIRTIO) {
2218
            fprintf(stderr, "addr is not supported by in '%s'\n", str);
2219
            return NULL;
2220
        }
2221
        devaddr = strdup(buf);
2222
    }
2223

    
2224
    /* compute bus and unit according index */
2225

    
2226
    if (index != -1) {
2227
        if (bus_id != 0 || unit_id != -1) {
2228
            fprintf(stderr,
2229
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2230
            return NULL;
2231
        }
2232
        if (max_devs == 0)
2233
        {
2234
            unit_id = index;
2235
            bus_id = 0;
2236
        } else {
2237
            unit_id = index % max_devs;
2238
            bus_id = index / max_devs;
2239
        }
2240
    }
2241

    
2242
    /* if user doesn't specify a unit_id,
2243
     * try to find the first free
2244
     */
2245

    
2246
    if (unit_id == -1) {
2247
       unit_id = 0;
2248
       while (drive_get(type, bus_id, unit_id) != NULL) {
2249
           unit_id++;
2250
           if (max_devs && unit_id >= max_devs) {
2251
               unit_id -= max_devs;
2252
               bus_id++;
2253
           }
2254
       }
2255
    }
2256

    
2257
    /* check unit id */
2258

    
2259
    if (max_devs && unit_id >= max_devs) {
2260
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2261
                        str, unit_id, max_devs - 1);
2262
        return NULL;
2263
    }
2264

    
2265
    /*
2266
     * ignore multiple definitions
2267
     */
2268

    
2269
    if (drive_get(type, bus_id, unit_id) != NULL) {
2270
        *fatal_error = 0;
2271
        return NULL;
2272
    }
2273

    
2274
    /* init */
2275

    
2276
    dinfo = qemu_mallocz(sizeof(*dinfo));
2277
    if (!get_param_value(buf, sizeof(buf), "id", str)) {
2278
        /* no id supplied -> create one */
2279
        if (type == IF_IDE || type == IF_SCSI)
2280
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2281
        if (max_devs)
2282
            snprintf(buf, sizeof(buf), "%s%i%s%i",
2283
                     devname, bus_id, mediastr, unit_id);
2284
        else
2285
            snprintf(buf, sizeof(buf), "%s%s%i",
2286
                     devname, mediastr, unit_id);
2287
    }
2288
    dinfo->id = qemu_strdup(buf);
2289
    dinfo->bdrv = bdrv_new(dinfo->id);
2290
    dinfo->devaddr = devaddr;
2291
    dinfo->type = type;
2292
    dinfo->bus = bus_id;
2293
    dinfo->unit = unit_id;
2294
    dinfo->onerror = onerror;
2295
    dinfo->opt = arg;
2296
    strncpy(dinfo->serial, serial, sizeof(serial));
2297
    TAILQ_INSERT_TAIL(&drives, dinfo, next);
2298

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

    
2352
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2353
{
2354
    boot_set_handler = func;
2355
    boot_set_opaque = opaque;
2356
}
2357

    
2358
int qemu_boot_set(const char *boot_devices)
2359
{
2360
    if (!boot_set_handler) {
2361
        return -EINVAL;
2362
    }
2363
    return boot_set_handler(boot_set_opaque, boot_devices);
2364
}
2365

    
2366
static int parse_bootdevices(char *devices)
2367
{
2368
    /* We just do some generic consistency checks */
2369
    const char *p;
2370
    int bitmap = 0;
2371

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

    
2395
static void restore_boot_devices(void *opaque)
2396
{
2397
    char *standard_boot_devices = opaque;
2398

    
2399
    qemu_boot_set(standard_boot_devices);
2400

    
2401
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2402
    qemu_free(standard_boot_devices);
2403
}
2404

    
2405
static void numa_add(const char *optarg)
2406
{
2407
    char option[128];
2408
    char *endptr;
2409
    unsigned long long value, endvalue;
2410
    int nodenr;
2411

    
2412
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2413
    if (!strcmp(option, "node")) {
2414
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2415
            nodenr = nb_numa_nodes;
2416
        } else {
2417
            nodenr = strtoull(option, NULL, 10);
2418
        }
2419

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

    
2461
/***********************************************************/
2462
/* USB devices */
2463

    
2464
static USBPort *used_usb_ports;
2465
static USBPort *free_usb_ports;
2466

    
2467
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2468
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2469
                            usb_attachfn attach)
2470
{
2471
    port->opaque = opaque;
2472
    port->index = index;
2473
    port->attach = attach;
2474
    port->next = free_usb_ports;
2475
    free_usb_ports = port;
2476
}
2477

    
2478
int usb_device_add_dev(USBDevice *dev)
2479
{
2480
    USBPort *port;
2481

    
2482
    /* Find a USB port to add the device to.  */
2483
    port = free_usb_ports;
2484
    if (!port->next) {
2485
        USBDevice *hub;
2486

    
2487
        /* Create a new hub and chain it on.  */
2488
        free_usb_ports = NULL;
2489
        port->next = used_usb_ports;
2490
        used_usb_ports = port;
2491

    
2492
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2493
        usb_attach(port, hub);
2494
        port = free_usb_ports;
2495
    }
2496

    
2497
    free_usb_ports = port->next;
2498
    port->next = used_usb_ports;
2499
    used_usb_ports = port;
2500
    usb_attach(port, dev);
2501
    return 0;
2502
}
2503

    
2504
static void usb_msd_password_cb(void *opaque, int err)
2505
{
2506
    USBDevice *dev = opaque;
2507

    
2508
    if (!err)
2509
        usb_device_add_dev(dev);
2510
    else
2511
        dev->handle_destroy(dev);
2512
}
2513

    
2514
static int usb_device_add(const char *devname, int is_hotplug)
2515
{
2516
    const char *p;
2517
    USBDevice *dev;
2518

    
2519
    if (!free_usb_ports)
2520
        return -1;
2521

    
2522
    if (strstart(devname, "host:", &p)) {
2523
        dev = usb_host_device_open(p);
2524
    } else if (!strcmp(devname, "mouse")) {
2525
        dev = usb_mouse_init();
2526
    } else if (!strcmp(devname, "tablet")) {
2527
        dev = usb_tablet_init();
2528
    } else if (!strcmp(devname, "keyboard")) {
2529
        dev = usb_keyboard_init();
2530
    } else if (strstart(devname, "disk:", &p)) {
2531
        BlockDriverState *bs;
2532

    
2533
        dev = usb_msd_init(p);
2534
        if (!dev)
2535
            return -1;
2536
        bs = usb_msd_get_bdrv(dev);
2537
        if (bdrv_key_required(bs)) {
2538
            autostart = 0;
2539
            if (is_hotplug) {
2540
                monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2541
                                            dev);
2542
                return 0;
2543
            }
2544
        }
2545
    } else if (!strcmp(devname, "wacom-tablet")) {
2546
        dev = usb_wacom_init();
2547
    } else if (strstart(devname, "serial:", &p)) {
2548
        dev = usb_serial_init(p);
2549
#ifdef CONFIG_BRLAPI
2550
    } else if (!strcmp(devname, "braille")) {
2551
        dev = usb_baum_init();
2552
#endif
2553
    } else if (strstart(devname, "net:", &p)) {
2554
        int nic = nb_nics;
2555

    
2556
        if (net_client_init(NULL, "nic", p) < 0)
2557
            return -1;
2558
        nd_table[nic].model = "usb";
2559
        dev = usb_net_init(&nd_table[nic]);
2560
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2561
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2562
                        bt_new_hci(qemu_find_bt_vlan(0)));
2563
    } else {
2564
        return -1;
2565
    }
2566
    if (!dev)
2567
        return -1;
2568

    
2569
    return usb_device_add_dev(dev);
2570
}
2571

    
2572
int usb_device_del_addr(int bus_num, int addr)
2573
{
2574
    USBPort *port;
2575
    USBPort **lastp;
2576
    USBDevice *dev;
2577

    
2578
    if (!used_usb_ports)
2579
        return -1;
2580

    
2581
    if (bus_num != 0)
2582
        return -1;
2583

    
2584
    lastp = &used_usb_ports;
2585
    port = used_usb_ports;
2586
    while (port && port->dev->addr != addr) {
2587
        lastp = &port->next;
2588
        port = port->next;
2589
    }
2590

    
2591
    if (!port)
2592
        return -1;
2593

    
2594
    dev = port->dev;
2595
    *lastp = port->next;
2596
    usb_attach(port, NULL);
2597
    dev->handle_destroy(dev);
2598
    port->next = free_usb_ports;
2599
    free_usb_ports = port;
2600
    return 0;
2601
}
2602

    
2603
static int usb_device_del(const char *devname)
2604
{
2605
    int bus_num, addr;
2606
    const char *p;
2607

    
2608
    if (strstart(devname, "host:", &p))
2609
        return usb_host_device_close(p);
2610

    
2611
    if (!used_usb_ports)
2612
        return -1;
2613

    
2614
    p = strchr(devname, '.');
2615
    if (!p)
2616
        return -1;
2617
    bus_num = strtoul(devname, NULL, 0);
2618
    addr = strtoul(p + 1, NULL, 0);
2619

    
2620
    return usb_device_del_addr(bus_num, addr);
2621
}
2622

    
2623
static int usb_parse(const char *cmdline)
2624
{
2625
    return usb_device_add(cmdline, 0);
2626
}
2627

    
2628
void do_usb_add(Monitor *mon, const char *devname)
2629
{
2630
    usb_device_add(devname, 1);
2631
}
2632

    
2633
void do_usb_del(Monitor *mon, const char *devname)
2634
{
2635
    usb_device_del(devname);
2636
}
2637

    
2638
void usb_info(Monitor *mon)
2639
{
2640
    USBDevice *dev;
2641
    USBPort *port;
2642
    const char *speed_str;
2643

    
2644
    if (!usb_enabled) {
2645
        monitor_printf(mon, "USB support not enabled\n");
2646
        return;
2647
    }
2648

    
2649
    for (port = used_usb_ports; port; port = port->next) {
2650
        dev = port->dev;
2651
        if (!dev)
2652
            continue;
2653
        switch(dev->speed) {
2654
        case USB_SPEED_LOW:
2655
            speed_str = "1.5";
2656
            break;
2657
        case USB_SPEED_FULL:
2658
            speed_str = "12";
2659
            break;
2660
        case USB_SPEED_HIGH:
2661
            speed_str = "480";
2662
            break;
2663
        default:
2664
            speed_str = "?";
2665
            break;
2666
        }
2667
        monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
2668
                       0, dev->addr, speed_str, dev->devname);
2669
    }
2670
}
2671

    
2672
/***********************************************************/
2673
/* PCMCIA/Cardbus */
2674

    
2675
static struct pcmcia_socket_entry_s {
2676
    PCMCIASocket *socket;
2677
    struct pcmcia_socket_entry_s *next;
2678
} *pcmcia_sockets = 0;
2679

    
2680
void pcmcia_socket_register(PCMCIASocket *socket)
2681
{
2682
    struct pcmcia_socket_entry_s *entry;
2683

    
2684
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2685
    entry->socket = socket;
2686
    entry->next = pcmcia_sockets;
2687
    pcmcia_sockets = entry;
2688
}
2689

    
2690
void pcmcia_socket_unregister(PCMCIASocket *socket)
2691
{
2692
    struct pcmcia_socket_entry_s *entry, **ptr;
2693

    
2694
    ptr = &pcmcia_sockets;
2695
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2696
        if (entry->socket == socket) {
2697
            *ptr = entry->next;
2698
            qemu_free(entry);
2699
        }
2700
}
2701

    
2702
void pcmcia_info(Monitor *mon)
2703
{
2704
    struct pcmcia_socket_entry_s *iter;
2705

    
2706
    if (!pcmcia_sockets)
2707
        monitor_printf(mon, "No PCMCIA sockets\n");
2708

    
2709
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2710
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2711
                       iter->socket->attached ? iter->socket->card_string :
2712
                       "Empty");
2713
}
2714

    
2715
/***********************************************************/
2716
/* register display */
2717

    
2718
struct DisplayAllocator default_allocator = {
2719
    defaultallocator_create_displaysurface,
2720
    defaultallocator_resize_displaysurface,
2721
    defaultallocator_free_displaysurface
2722
};
2723

    
2724
void register_displaystate(DisplayState *ds)
2725
{
2726
    DisplayState **s;
2727
    s = &display_state;
2728
    while (*s != NULL)
2729
        s = &(*s)->next;
2730
    ds->next = NULL;
2731
    *s = ds;
2732
}
2733

    
2734
DisplayState *get_displaystate(void)
2735
{
2736
    return display_state;
2737
}
2738

    
2739
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2740
{
2741
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2742
    return ds->allocator;
2743
}
2744

    
2745
/* dumb display */
2746

    
2747
static void dumb_display_init(void)
2748
{
2749
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2750
    ds->allocator = &default_allocator;
2751
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2752
    register_displaystate(ds);
2753
}
2754

    
2755
/***********************************************************/
2756
/* I/O handling */
2757

    
2758
typedef struct IOHandlerRecord {
2759
    int fd;
2760
    IOCanRWHandler *fd_read_poll;
2761
    IOHandler *fd_read;
2762
    IOHandler *fd_write;
2763
    int deleted;
2764
    void *opaque;
2765
    /* temporary data */
2766
    struct pollfd *ufd;
2767
    struct IOHandlerRecord *next;
2768
} IOHandlerRecord;
2769

    
2770
static IOHandlerRecord *first_io_handler;
2771

    
2772
/* XXX: fd_read_poll should be suppressed, but an API change is
2773
   necessary in the character devices to suppress fd_can_read(). */
2774
int qemu_set_fd_handler2(int fd,
2775
                         IOCanRWHandler *fd_read_poll,
2776
                         IOHandler *fd_read,
2777
                         IOHandler *fd_write,
2778
                         void *opaque)
2779
{
2780
    IOHandlerRecord **pioh, *ioh;
2781

    
2782
    if (!fd_read && !fd_write) {
2783
        pioh = &first_io_handler;
2784
        for(;;) {
2785
            ioh = *pioh;
2786
            if (ioh == NULL)
2787
                break;
2788
            if (ioh->fd == fd) {
2789
                ioh->deleted = 1;
2790
                break;
2791
            }
2792
            pioh = &ioh->next;
2793
        }
2794
    } else {
2795
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2796
            if (ioh->fd == fd)
2797
                goto found;
2798
        }
2799
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2800
        ioh->next = first_io_handler;
2801
        first_io_handler = ioh;
2802
    found:
2803
        ioh->fd = fd;
2804
        ioh->fd_read_poll = fd_read_poll;
2805
        ioh->fd_read = fd_read;
2806
        ioh->fd_write = fd_write;
2807
        ioh->opaque = opaque;
2808
        ioh->deleted = 0;
2809
    }
2810
    return 0;
2811
}
2812

    
2813
int qemu_set_fd_handler(int fd,
2814
                        IOHandler *fd_read,
2815
                        IOHandler *fd_write,
2816
                        void *opaque)
2817
{
2818
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2819
}
2820

    
2821
#ifdef _WIN32
2822
/***********************************************************/
2823
/* Polling handling */
2824

    
2825
typedef struct PollingEntry {
2826
    PollingFunc *func;
2827
    void *opaque;
2828
    struct PollingEntry *next;
2829
} PollingEntry;
2830

    
2831
static PollingEntry *first_polling_entry;
2832

    
2833
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2834
{
2835
    PollingEntry **ppe, *pe;
2836
    pe = qemu_mallocz(sizeof(PollingEntry));
2837
    pe->func = func;
2838
    pe->opaque = opaque;
2839
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2840
    *ppe = pe;
2841
    return 0;
2842
}
2843

    
2844
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2845
{
2846
    PollingEntry **ppe, *pe;
2847
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2848
        pe = *ppe;
2849
        if (pe->func == func && pe->opaque == opaque) {
2850
            *ppe = pe->next;
2851
            qemu_free(pe);
2852
            break;
2853
        }
2854
    }
2855
}
2856

    
2857
/***********************************************************/
2858
/* Wait objects support */
2859
typedef struct WaitObjects {
2860
    int num;
2861
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2862
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2863
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2864
} WaitObjects;
2865

    
2866
static WaitObjects wait_objects = {0};
2867

    
2868
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2869
{
2870
    WaitObjects *w = &wait_objects;
2871

    
2872
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2873
        return -1;
2874
    w->events[w->num] = handle;
2875
    w->func[w->num] = func;
2876
    w->opaque[w->num] = opaque;
2877
    w->num++;
2878
    return 0;
2879
}
2880

    
2881
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2882
{
2883
    int i, found;
2884
    WaitObjects *w = &wait_objects;
2885

    
2886
    found = 0;
2887
    for (i = 0; i < w->num; i++) {
2888
        if (w->events[i] == handle)
2889
            found = 1;
2890
        if (found) {
2891
            w->events[i] = w->events[i + 1];
2892
            w->func[i] = w->func[i + 1];
2893
            w->opaque[i] = w->opaque[i + 1];
2894
        }
2895
    }
2896
    if (found)
2897
        w->num--;
2898
}
2899
#endif
2900

    
2901
/***********************************************************/
2902
/* ram save/restore */
2903

    
2904
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2905
{
2906
    int v;
2907

    
2908
    v = qemu_get_byte(f);
2909
    switch(v) {
2910
    case 0:
2911
        if (qemu_get_buffer(f, buf, len) != len)
2912
            return -EIO;
2913
        break;
2914
    case 1:
2915
        v = qemu_get_byte(f);
2916
        memset(buf, v, len);
2917
        break;
2918
    default:
2919
        return -EINVAL;
2920
    }
2921

    
2922
    if (qemu_file_has_error(f))
2923
        return -EIO;
2924

    
2925
    return 0;
2926
}
2927

    
2928
static int ram_load_v1(QEMUFile *f, void *opaque)
2929
{
2930
    int ret;
2931
    ram_addr_t i;
2932

    
2933
    if (qemu_get_be32(f) != last_ram_offset)
2934
        return -EINVAL;
2935
    for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2936
        ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2937
        if (ret)
2938
            return ret;
2939
    }
2940
    return 0;
2941
}
2942

    
2943
#define BDRV_HASH_BLOCK_SIZE 1024
2944
#define IOBUF_SIZE 4096
2945
#define RAM_CBLOCK_MAGIC 0xfabe
2946

    
2947
typedef struct RamDecompressState {
2948
    z_stream zstream;
2949
    QEMUFile *f;
2950
    uint8_t buf[IOBUF_SIZE];
2951
} RamDecompressState;
2952

    
2953
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2954
{
2955
    int ret;
2956
    memset(s, 0, sizeof(*s));
2957
    s->f = f;
2958
    ret = inflateInit(&s->zstream);
2959
    if (ret != Z_OK)
2960
        return -1;
2961
    return 0;
2962
}
2963

    
2964
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2965
{
2966
    int ret, clen;
2967

    
2968
    s->zstream.avail_out = len;
2969
    s->zstream.next_out = buf;
2970
    while (s->zstream.avail_out > 0) {
2971
        if (s->zstream.avail_in == 0) {
2972
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2973
                return -1;
2974
            clen = qemu_get_be16(s->f);
2975
            if (clen > IOBUF_SIZE)
2976
                return -1;
2977
            qemu_get_buffer(s->f, s->buf, clen);
2978
            s->zstream.avail_in = clen;
2979
            s->zstream.next_in = s->buf;
2980
        }
2981
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2982
        if (ret != Z_OK && ret != Z_STREAM_END) {
2983
            return -1;
2984
        }
2985
    }
2986
    return 0;
2987
}
2988

    
2989
static void ram_decompress_close(RamDecompressState *s)
2990
{
2991
    inflateEnd(&s->zstream);
2992
}
2993

    
2994
#define RAM_SAVE_FLAG_FULL        0x01
2995
#define RAM_SAVE_FLAG_COMPRESS        0x02
2996
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2997
#define RAM_SAVE_FLAG_PAGE        0x08
2998
#define RAM_SAVE_FLAG_EOS        0x10
2999

    
3000
static int is_dup_page(uint8_t *page, uint8_t ch)
3001
{
3002
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3003
    uint32_t *array = (uint32_t *)page;
3004
    int i;
3005

    
3006
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3007
        if (array[i] != val)
3008
            return 0;
3009
    }
3010

    
3011
    return 1;
3012
}
3013

    
3014
static int ram_save_block(QEMUFile *f)
3015
{
3016
    static ram_addr_t current_addr = 0;
3017
    ram_addr_t saved_addr = current_addr;
3018
    ram_addr_t addr = 0;
3019
    int found = 0;
3020

    
3021
    while (addr < last_ram_offset) {
3022
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3023
            uint8_t *p;
3024

    
3025
            cpu_physical_memory_reset_dirty(current_addr,
3026
                                            current_addr + TARGET_PAGE_SIZE,
3027
                                            MIGRATION_DIRTY_FLAG);
3028

    
3029
            p = qemu_get_ram_ptr(current_addr);
3030

    
3031
            if (is_dup_page(p, *p)) {
3032
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3033
                qemu_put_byte(f, *p);
3034
            } else {
3035
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3036
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3037
            }
3038

    
3039
            found = 1;
3040
            break;
3041
        }
3042
        addr += TARGET_PAGE_SIZE;
3043
        current_addr = (saved_addr + addr) % last_ram_offset;
3044
    }
3045

    
3046
    return found;
3047
}
3048

    
3049
static uint64_t bytes_transferred = 0;
3050

    
3051
static ram_addr_t ram_save_remaining(void)
3052
{
3053
    ram_addr_t addr;
3054
    ram_addr_t count = 0;
3055

    
3056
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3057
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3058
            count++;
3059
    }
3060

    
3061
    return count;
3062
}
3063

    
3064
uint64_t ram_bytes_remaining(void)
3065
{
3066
    return ram_save_remaining() * TARGET_PAGE_SIZE;
3067
}
3068

    
3069
uint64_t ram_bytes_transferred(void)
3070
{
3071
    return bytes_transferred;
3072
}
3073

    
3074
uint64_t ram_bytes_total(void)
3075
{
3076
    return last_ram_offset;
3077
}
3078

    
3079
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3080
{
3081
    ram_addr_t addr;
3082
    uint64_t bytes_transferred_last;
3083
    double bwidth = 0;
3084
    uint64_t expected_time = 0;
3085

    
3086
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3087
        qemu_file_set_error(f);
3088
        return 0;
3089
    }
3090

    
3091
    if (stage == 1) {
3092
        /* Make sure all dirty bits are set */
3093
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3094
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3095
                cpu_physical_memory_set_dirty(addr);
3096
        }
3097

    
3098
        /* Enable dirty memory tracking */
3099
        cpu_physical_memory_set_dirty_tracking(1);
3100

    
3101
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3102
    }
3103

    
3104
    bytes_transferred_last = bytes_transferred;
3105
    bwidth = get_clock();
3106

    
3107
    while (!qemu_file_rate_limit(f)) {
3108
        int ret;
3109

    
3110
        ret = ram_save_block(f);
3111
        bytes_transferred += ret * TARGET_PAGE_SIZE;
3112
        if (ret == 0) /* no more blocks */
3113
            break;
3114
    }
3115

    
3116
    bwidth = get_clock() - bwidth;
3117
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3118

    
3119
    /* if we haven't transferred anything this round, force expected_time to a
3120
     * a very high value, but without crashing */
3121
    if (bwidth == 0)
3122
        bwidth = 0.000001;
3123

    
3124
    /* try transferring iterative blocks of memory */
3125

    
3126
    if (stage == 3) {
3127

    
3128
        /* flush all remaining blocks regardless of rate limiting */
3129
        while (ram_save_block(f) != 0) {
3130
            bytes_transferred += TARGET_PAGE_SIZE;
3131
        }
3132
        cpu_physical_memory_set_dirty_tracking(0);
3133
    }
3134

    
3135
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3136

    
3137
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3138

    
3139
    return (stage == 2) && (expected_time <= migrate_max_downtime());
3140
}
3141

    
3142
static int ram_load_dead(QEMUFile *f, void *opaque)
3143
{
3144
    RamDecompressState s1, *s = &s1;
3145
    uint8_t buf[10];
3146
    ram_addr_t i;
3147

    
3148
    if (ram_decompress_open(s, f) < 0)
3149
        return -EINVAL;
3150
    for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3151
        if (ram_decompress_buf(s, buf, 1) < 0) {
3152
            fprintf(stderr, "Error while reading ram block header\n");
3153
            goto error;
3154
        }
3155
        if (buf[0] == 0) {
3156
            if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3157
                                   BDRV_HASH_BLOCK_SIZE) < 0) {
3158
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3159
                goto error;
3160
            }
3161
        } else {
3162
        error:
3163
            printf("Error block header\n");
3164
            return -EINVAL;
3165
        }
3166
    }
3167
    ram_decompress_close(s);
3168

    
3169
    return 0;
3170
}
3171

    
3172
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3173
{
3174
    ram_addr_t addr;
3175
    int flags;
3176

    
3177
    if (version_id == 1)
3178
        return ram_load_v1(f, opaque);
3179

    
3180
    if (version_id == 2) {
3181
        if (qemu_get_be32(f) != last_ram_offset)
3182
            return -EINVAL;
3183
        return ram_load_dead(f, opaque);
3184
    }
3185

    
3186
    if (version_id != 3)
3187
        return -EINVAL;
3188

    
3189
    do {
3190
        addr = qemu_get_be64(f);
3191

    
3192
        flags = addr & ~TARGET_PAGE_MASK;
3193
        addr &= TARGET_PAGE_MASK;
3194

    
3195
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3196
            if (addr != last_ram_offset)
3197
                return -EINVAL;
3198
        }
3199

    
3200
        if (flags & RAM_SAVE_FLAG_FULL) {
3201
            if (ram_load_dead(f, opaque) < 0)
3202
                return -EINVAL;
3203
        }
3204
        
3205
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3206
            uint8_t ch = qemu_get_byte(f);
3207
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3208
#ifndef _WIN32
3209
            if (ch == 0 &&
3210
                (!kvm_enabled() || kvm_has_sync_mmu())) {
3211
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3212
            }
3213
#endif
3214
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3215
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3216
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3217

    
3218
    return 0;
3219
}
3220

    
3221
void qemu_service_io(void)
3222
{
3223
    qemu_notify_event();
3224
}
3225

    
3226
/***********************************************************/
3227
/* bottom halves (can be seen as timers which expire ASAP) */
3228

    
3229
struct QEMUBH {
3230
    QEMUBHFunc *cb;
3231
    void *opaque;
3232
    int scheduled;
3233
    int idle;
3234
    int deleted;
3235
    QEMUBH *next;
3236
};
3237

    
3238
static QEMUBH *first_bh = NULL;
3239

    
3240
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3241
{
3242
    QEMUBH *bh;
3243
    bh = qemu_mallocz(sizeof(QEMUBH));
3244
    bh->cb = cb;
3245
    bh->opaque = opaque;
3246
    bh->next = first_bh;
3247
    first_bh = bh;
3248
    return bh;
3249
}
3250

    
3251
int qemu_bh_poll(void)
3252
{
3253
    QEMUBH *bh, **bhp;
3254
    int ret;
3255

    
3256
    ret = 0;
3257
    for (bh = first_bh; bh; bh = bh->next) {
3258
        if (!bh->deleted && bh->scheduled) {
3259
            bh->scheduled = 0;
3260
            if (!bh->idle)
3261
                ret = 1;
3262
            bh->idle = 0;
3263
            bh->cb(bh->opaque);
3264
        }
3265
    }
3266

    
3267
    /* remove deleted bhs */
3268
    bhp = &first_bh;
3269
    while (*bhp) {
3270
        bh = *bhp;
3271
        if (bh->deleted) {
3272
            *bhp = bh->next;
3273
            qemu_free(bh);
3274
        } else
3275
            bhp = &bh->next;
3276
    }
3277

    
3278
    return ret;
3279
}
3280

    
3281
void qemu_bh_schedule_idle(QEMUBH *bh)
3282
{
3283
    if (bh->scheduled)
3284
        return;
3285
    bh->scheduled = 1;
3286
    bh->idle = 1;
3287
}
3288

    
3289
void qemu_bh_schedule(QEMUBH *bh)
3290
{
3291
    if (bh->scheduled)
3292
        return;
3293
    bh->scheduled = 1;
3294
    bh->idle = 0;
3295
    /* stop the currently executing CPU to execute the BH ASAP */
3296
    qemu_notify_event();
3297
}
3298

    
3299
void qemu_bh_cancel(QEMUBH *bh)
3300
{
3301
    bh->scheduled = 0;
3302
}
3303

    
3304
void qemu_bh_delete(QEMUBH *bh)
3305
{
3306
    bh->scheduled = 0;
3307
    bh->deleted = 1;
3308
}
3309

    
3310
static void qemu_bh_update_timeout(int *timeout)
3311
{
3312
    QEMUBH *bh;
3313

    
3314
    for (bh = first_bh; bh; bh = bh->next) {
3315
        if (!bh->deleted && bh->scheduled) {
3316
            if (bh->idle) {
3317
                /* idle bottom halves will be polled at least
3318
                 * every 10ms */
3319
                *timeout = MIN(10, *timeout);
3320
            } else {
3321
                /* non-idle bottom halves will be executed
3322
                 * immediately */
3323
                *timeout = 0;
3324
                break;
3325
            }
3326
        }
3327
    }
3328
}
3329

    
3330
/***********************************************************/
3331
/* machine registration */
3332

    
3333
static QEMUMachine *first_machine = NULL;
3334
QEMUMachine *current_machine = NULL;
3335

    
3336
int qemu_register_machine(QEMUMachine *m)
3337
{
3338
    QEMUMachine **pm;
3339
    pm = &first_machine;
3340
    while (*pm != NULL)
3341
        pm = &(*pm)->next;
3342
    m->next = NULL;
3343
    *pm = m;
3344
    return 0;
3345
}
3346

    
3347
static QEMUMachine *find_machine(const char *name)
3348
{
3349
    QEMUMachine *m;
3350

    
3351
    for(m = first_machine; m != NULL; m = m->next) {
3352
        if (!strcmp(m->name, name))
3353
            return m;
3354
        if (m->alias && !strcmp(m->alias, name))
3355
            return m;
3356
    }
3357
    return NULL;
3358
}
3359

    
3360
static QEMUMachine *find_default_machine(void)
3361
{
3362
    QEMUMachine *m;
3363

    
3364
    for(m = first_machine; m != NULL; m = m->next) {
3365
        if (m->is_default) {
3366
            return m;
3367
        }
3368
    }
3369
    return NULL;
3370
}
3371

    
3372
/***********************************************************/
3373
/* main execution loop */
3374

    
3375
static void gui_update(void *opaque)
3376
{
3377
    uint64_t interval = GUI_REFRESH_INTERVAL;
3378
    DisplayState *ds = opaque;
3379
    DisplayChangeListener *dcl = ds->listeners;
3380

    
3381
    dpy_refresh(ds);
3382

    
3383
    while (dcl != NULL) {
3384
        if (dcl->gui_timer_interval &&
3385
            dcl->gui_timer_interval < interval)
3386
            interval = dcl->gui_timer_interval;
3387
        dcl = dcl->next;
3388
    }
3389
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3390
}
3391

    
3392
static void nographic_update(void *opaque)
3393
{
3394
    uint64_t interval = GUI_REFRESH_INTERVAL;
3395

    
3396
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3397
}
3398

    
3399
struct vm_change_state_entry {
3400
    VMChangeStateHandler *cb;
3401
    void *opaque;
3402
    LIST_ENTRY (vm_change_state_entry) entries;
3403
};
3404

    
3405
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3406

    
3407
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3408
                                                     void *opaque)
3409
{
3410
    VMChangeStateEntry *e;
3411

    
3412
    e = qemu_mallocz(sizeof (*e));
3413

    
3414
    e->cb = cb;
3415
    e->opaque = opaque;
3416
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3417
    return e;
3418
}
3419

    
3420
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3421
{
3422
    LIST_REMOVE (e, entries);
3423
    qemu_free (e);
3424
}
3425

    
3426
static void vm_state_notify(int running, int reason)
3427
{
3428
    VMChangeStateEntry *e;
3429

    
3430
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3431
        e->cb(e->opaque, running, reason);
3432
    }
3433
}
3434

    
3435
static void resume_all_vcpus(void);
3436
static void pause_all_vcpus(void);
3437

    
3438
void vm_start(void)
3439
{
3440
    if (!vm_running) {
3441
        cpu_enable_ticks();
3442
        vm_running = 1;
3443
        vm_state_notify(1, 0);
3444
        qemu_rearm_alarm_timer(alarm_timer);
3445
        resume_all_vcpus();
3446
    }
3447
}
3448

    
3449
/* reset/shutdown handler */
3450

    
3451
typedef struct QEMUResetEntry {
3452
    TAILQ_ENTRY(QEMUResetEntry) entry;
3453
    QEMUResetHandler *func;
3454
    void *opaque;
3455
} QEMUResetEntry;
3456

    
3457
static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3458
    TAILQ_HEAD_INITIALIZER(reset_handlers);
3459
static int reset_requested;
3460
static int shutdown_requested;
3461
static int powerdown_requested;
3462
static int debug_requested;
3463
static int vmstop_requested;
3464

    
3465
int qemu_shutdown_requested(void)
3466
{
3467
    int r = shutdown_requested;
3468
    shutdown_requested = 0;
3469
    return r;
3470
}
3471

    
3472
int qemu_reset_requested(void)
3473
{
3474
    int r = reset_requested;
3475
    reset_requested = 0;
3476
    return r;
3477
}
3478

    
3479
int qemu_powerdown_requested(void)
3480
{
3481
    int r = powerdown_requested;
3482
    powerdown_requested = 0;
3483
    return r;
3484
}
3485

    
3486
static int qemu_debug_requested(void)
3487
{
3488
    int r = debug_requested;
3489
    debug_requested = 0;
3490
    return r;
3491
}
3492

    
3493
static int qemu_vmstop_requested(void)
3494
{
3495
    int r = vmstop_requested;
3496
    vmstop_requested = 0;
3497
    return r;
3498
}
3499

    
3500
static void do_vm_stop(int reason)
3501
{
3502
    if (vm_running) {
3503
        cpu_disable_ticks();
3504
        vm_running = 0;
3505
        pause_all_vcpus();
3506
        vm_state_notify(0, reason);
3507
    }
3508
}
3509

    
3510
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3511
{
3512
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3513

    
3514
    re->func = func;
3515
    re->opaque = opaque;
3516
    TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3517
}
3518

    
3519
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3520
{
3521
    QEMUResetEntry *re;
3522

    
3523
    TAILQ_FOREACH(re, &reset_handlers, entry) {
3524
        if (re->func == func && re->opaque == opaque) {
3525
            TAILQ_REMOVE(&reset_handlers, re, entry);
3526
            qemu_free(re);
3527
            return;
3528
        }
3529
    }
3530
}
3531

    
3532
void qemu_system_reset(void)
3533
{
3534
    QEMUResetEntry *re, *nre;
3535

    
3536
    /* reset all devices */
3537
    TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3538
        re->func(re->opaque);
3539
    }
3540
}
3541

    
3542
void qemu_system_reset_request(void)
3543
{
3544
    if (no_reboot) {
3545
        shutdown_requested = 1;
3546
    } else {
3547
        reset_requested = 1;
3548
    }
3549
    qemu_notify_event();
3550
}
3551

    
3552
void qemu_system_shutdown_request(void)
3553
{
3554
    shutdown_requested = 1;
3555
    qemu_notify_event();
3556
}
3557

    
3558
void qemu_system_powerdown_request(void)
3559
{
3560
    powerdown_requested = 1;
3561
    qemu_notify_event();
3562
}
3563

    
3564
#ifdef CONFIG_IOTHREAD
3565
static void qemu_system_vmstop_request(int reason)
3566
{
3567
    vmstop_requested = reason;
3568
    qemu_notify_event();
3569
}
3570
#endif
3571

    
3572
#ifndef _WIN32
3573
static int io_thread_fd = -1;
3574

    
3575
static void qemu_event_increment(void)
3576
{
3577
    static const char byte = 0;
3578

    
3579
    if (io_thread_fd == -1)
3580
        return;
3581

    
3582
    write(io_thread_fd, &byte, sizeof(byte));
3583
}
3584

    
3585
static void qemu_event_read(void *opaque)
3586
{
3587
    int fd = (unsigned long)opaque;
3588
    ssize_t len;
3589

    
3590
    /* Drain the notify pipe */
3591
    do {
3592
        char buffer[512];
3593
        len = read(fd, buffer, sizeof(buffer));
3594
    } while ((len == -1 && errno == EINTR) || len > 0);
3595
}
3596

    
3597
static int qemu_event_init(void)
3598
{
3599
    int err;
3600
    int fds[2];
3601

    
3602
    err = pipe(fds);
3603
    if (err == -1)
3604
        return -errno;
3605

    
3606
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3607
    if (err < 0)
3608
        goto fail;
3609

    
3610
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3611
    if (err < 0)
3612
        goto fail;
3613

    
3614
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3615
                         (void *)(unsigned long)fds[0]);
3616

    
3617
    io_thread_fd = fds[1];
3618
    return 0;
3619

    
3620
fail:
3621
    close(fds[0]);
3622
    close(fds[1]);
3623
    return err;
3624
}
3625
#else
3626
HANDLE qemu_event_handle;
3627

    
3628
static void dummy_event_handler(void *opaque)
3629
{
3630
}
3631

    
3632
static int qemu_event_init(void)
3633
{
3634
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3635
    if (!qemu_event_handle) {
3636
        perror("Failed CreateEvent");
3637
        return -1;
3638
    }
3639
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3640
    return 0;
3641
}
3642

    
3643
static void qemu_event_increment(void)
3644
{
3645
    SetEvent(qemu_event_handle);
3646
}
3647
#endif
3648

    
3649
static int cpu_can_run(CPUState *env)
3650
{
3651
    if (env->stop)
3652
        return 0;
3653
    if (env->stopped)
3654
        return 0;
3655
    return 1;
3656
}
3657

    
3658
#ifndef CONFIG_IOTHREAD
3659
static int qemu_init_main_loop(void)
3660
{
3661
    return qemu_event_init();
3662
}
3663

    
3664
void qemu_init_vcpu(void *_env)
3665
{
3666
    CPUState *env = _env;
3667

    
3668
    if (kvm_enabled())
3669
        kvm_init_vcpu(env);
3670
    return;
3671
}
3672

    
3673
int qemu_cpu_self(void *env)
3674
{
3675
    return 1;
3676
}
3677

    
3678
static void resume_all_vcpus(void)
3679
{
3680
}
3681

    
3682
static void pause_all_vcpus(void)
3683
{
3684
}
3685

    
3686
void qemu_cpu_kick(void *env)
3687
{
3688
    return;
3689
}
3690

    
3691
void qemu_notify_event(void)
3692
{
3693
    CPUState *env = cpu_single_env;
3694

    
3695
    if (env) {
3696
        cpu_exit(env);
3697
#ifdef USE_KQEMU
3698
        if (env->kqemu_enabled)
3699
            kqemu_cpu_interrupt(env);
3700
#endif
3701
     }
3702
}
3703

    
3704
#define qemu_mutex_lock_iothread() do { } while (0)
3705
#define qemu_mutex_unlock_iothread() do { } while (0)
3706

    
3707
void vm_stop(int reason)
3708
{
3709
    do_vm_stop(reason);
3710
}
3711

    
3712
#else /* CONFIG_IOTHREAD */
3713

    
3714
#include "qemu-thread.h"
3715

    
3716
QemuMutex qemu_global_mutex;
3717
static QemuMutex qemu_fair_mutex;
3718

    
3719
static QemuThread io_thread;
3720

    
3721
static QemuThread *tcg_cpu_thread;
3722
static QemuCond *tcg_halt_cond;
3723

    
3724
static int qemu_system_ready;
3725
/* cpu creation */
3726
static QemuCond qemu_cpu_cond;
3727
/* system init */
3728
static QemuCond qemu_system_cond;
3729
static QemuCond qemu_pause_cond;
3730

    
3731
static void block_io_signals(void);
3732
static void unblock_io_signals(void);
3733
static int tcg_has_work(void);
3734

    
3735
static int qemu_init_main_loop(void)
3736
{
3737
    int ret;
3738

    
3739
    ret = qemu_event_init();
3740
    if (ret)
3741
        return ret;
3742

    
3743
    qemu_cond_init(&qemu_pause_cond);
3744
    qemu_mutex_init(&qemu_fair_mutex);
3745
    qemu_mutex_init(&qemu_global_mutex);
3746
    qemu_mutex_lock(&qemu_global_mutex);
3747

    
3748
    unblock_io_signals();
3749
    qemu_thread_self(&io_thread);
3750

    
3751
    return 0;
3752
}
3753

    
3754
static void qemu_wait_io_event(CPUState *env)
3755
{
3756
    while (!tcg_has_work())
3757
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3758

    
3759
    qemu_mutex_unlock(&qemu_global_mutex);
3760

    
3761
    /*
3762
     * Users of qemu_global_mutex can be starved, having no chance
3763
     * to acquire it since this path will get to it first.
3764
     * So use another lock to provide fairness.
3765
     */
3766
    qemu_mutex_lock(&qemu_fair_mutex);
3767
    qemu_mutex_unlock(&qemu_fair_mutex);
3768

    
3769
    qemu_mutex_lock(&qemu_global_mutex);
3770
    if (env->stop) {
3771
        env->stop = 0;
3772
        env->stopped = 1;
3773
        qemu_cond_signal(&qemu_pause_cond);
3774
    }
3775
}
3776

    
3777
static int qemu_cpu_exec(CPUState *env);
3778

    
3779
static void *kvm_cpu_thread_fn(void *arg)
3780
{
3781
    CPUState *env = arg;
3782

    
3783
    block_io_signals();
3784
    qemu_thread_self(env->thread);
3785

    
3786
    /* signal CPU creation */
3787
    qemu_mutex_lock(&qemu_global_mutex);
3788
    env->created = 1;
3789
    qemu_cond_signal(&qemu_cpu_cond);
3790

    
3791
    /* and wait for machine initialization */
3792
    while (!qemu_system_ready)
3793
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3794

    
3795
    while (1) {
3796
        if (cpu_can_run(env))
3797
            qemu_cpu_exec(env);
3798
        qemu_wait_io_event(env);
3799
    }
3800

    
3801
    return NULL;
3802
}
3803

    
3804
static void tcg_cpu_exec(void);
3805

    
3806
static void *tcg_cpu_thread_fn(void *arg)
3807
{
3808
    CPUState *env = arg;
3809

    
3810
    block_io_signals();
3811
    qemu_thread_self(env->thread);
3812

    
3813
    /* signal CPU creation */
3814
    qemu_mutex_lock(&qemu_global_mutex);
3815
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3816
        env->created = 1;
3817
    qemu_cond_signal(&qemu_cpu_cond);
3818

    
3819
    /* and wait for machine initialization */
3820
    while (!qemu_system_ready)
3821
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3822

    
3823
    while (1) {
3824
        tcg_cpu_exec();
3825
        qemu_wait_io_event(cur_cpu);
3826
    }
3827

    
3828
    return NULL;
3829
}
3830

    
3831
void qemu_cpu_kick(void *_env)
3832
{
3833
    CPUState *env = _env;
3834
    qemu_cond_broadcast(env->halt_cond);
3835
    if (kvm_enabled())
3836
        qemu_thread_signal(env->thread, SIGUSR1);
3837
}
3838

    
3839
int qemu_cpu_self(void *env)
3840
{
3841
    return (cpu_single_env != NULL);
3842
}
3843

    
3844
static void cpu_signal(int sig)
3845
{
3846
    if (cpu_single_env)
3847
        cpu_exit(cpu_single_env);
3848
}
3849

    
3850
static void block_io_signals(void)
3851
{
3852
    sigset_t set;
3853
    struct sigaction sigact;
3854

    
3855
    sigemptyset(&set);
3856
    sigaddset(&set, SIGUSR2);
3857
    sigaddset(&set, SIGIO);
3858
    sigaddset(&set, SIGALRM);
3859
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3860

    
3861
    sigemptyset(&set);
3862
    sigaddset(&set, SIGUSR1);
3863
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3864

    
3865
    memset(&sigact, 0, sizeof(sigact));
3866
    sigact.sa_handler = cpu_signal;
3867
    sigaction(SIGUSR1, &sigact, NULL);
3868
}
3869

    
3870
static void unblock_io_signals(void)
3871
{
3872
    sigset_t set;
3873

    
3874
    sigemptyset(&set);
3875
    sigaddset(&set, SIGUSR2);
3876
    sigaddset(&set, SIGIO);
3877
    sigaddset(&set, SIGALRM);
3878
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3879

    
3880
    sigemptyset(&set);
3881
    sigaddset(&set, SIGUSR1);
3882
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3883
}
3884

    
3885
static void qemu_signal_lock(unsigned int msecs)
3886
{
3887
    qemu_mutex_lock(&qemu_fair_mutex);
3888

    
3889
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3890
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3891
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3892
            break;
3893
    }
3894
    qemu_mutex_unlock(&qemu_fair_mutex);
3895
}
3896

    
3897
static void qemu_mutex_lock_iothread(void)
3898
{
3899
    if (kvm_enabled()) {
3900
        qemu_mutex_lock(&qemu_fair_mutex);
3901
        qemu_mutex_lock(&qemu_global_mutex);
3902
        qemu_mutex_unlock(&qemu_fair_mutex);
3903
    } else
3904
        qemu_signal_lock(100);
3905
}
3906

    
3907
static void qemu_mutex_unlock_iothread(void)
3908
{
3909
    qemu_mutex_unlock(&qemu_global_mutex);
3910
}
3911

    
3912
static int all_vcpus_paused(void)
3913
{
3914
    CPUState *penv = first_cpu;
3915

    
3916
    while (penv) {
3917
        if (!penv->stopped)
3918
            return 0;
3919
        penv = (CPUState *)penv->next_cpu;
3920
    }
3921

    
3922
    return 1;
3923
}
3924

    
3925
static void pause_all_vcpus(void)
3926
{
3927
    CPUState *penv = first_cpu;
3928

    
3929
    while (penv) {
3930
        penv->stop = 1;
3931
        qemu_thread_signal(penv->thread, SIGUSR1);
3932
        qemu_cpu_kick(penv);
3933
        penv = (CPUState *)penv->next_cpu;
3934
    }
3935

    
3936
    while (!all_vcpus_paused()) {
3937
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3938
        penv = first_cpu;
3939
        while (penv) {
3940
            qemu_thread_signal(penv->thread, SIGUSR1);
3941
            penv = (CPUState *)penv->next_cpu;
3942
        }
3943
    }
3944
}
3945

    
3946
static void resume_all_vcpus(void)
3947
{
3948
    CPUState *penv = first_cpu;
3949

    
3950
    while (penv) {
3951
        penv->stop = 0;
3952
        penv->stopped = 0;
3953
        qemu_thread_signal(penv->thread, SIGUSR1);
3954
        qemu_cpu_kick(penv);
3955
        penv = (CPUState *)penv->next_cpu;
3956
    }
3957
}
3958

    
3959
static void tcg_init_vcpu(void *_env)
3960
{
3961
    CPUState *env = _env;
3962
    /* share a single thread for all cpus with TCG */
3963
    if (!tcg_cpu_thread) {
3964
        env->thread = qemu_mallocz(sizeof(QemuThread));
3965
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3966
        qemu_cond_init(env->halt_cond);
3967
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3968
        while (env->created == 0)
3969
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3970
        tcg_cpu_thread = env->thread;
3971
        tcg_halt_cond = env->halt_cond;
3972
    } else {
3973
        env->thread = tcg_cpu_thread;
3974
        env->halt_cond = tcg_halt_cond;
3975
    }
3976
}
3977

    
3978
static void kvm_start_vcpu(CPUState *env)
3979
{
3980
    kvm_init_vcpu(env);
3981
    env->thread = qemu_mallocz(sizeof(QemuThread));
3982
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3983
    qemu_cond_init(env->halt_cond);
3984
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3985
    while (env->created == 0)
3986
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3987
}
3988

    
3989
void qemu_init_vcpu(void *_env)
3990
{
3991
    CPUState *env = _env;
3992

    
3993
    if (kvm_enabled())
3994
        kvm_start_vcpu(env);
3995
    else
3996
        tcg_init_vcpu(env);
3997
}
3998

    
3999
void qemu_notify_event(void)
4000
{
4001
    qemu_event_increment();
4002
}
4003

    
4004
void vm_stop(int reason)
4005
{
4006
    QemuThread me;
4007
    qemu_thread_self(&me);
4008

    
4009
    if (!qemu_thread_equal(&me, &io_thread)) {
4010
        qemu_system_vmstop_request(reason);
4011
        /*
4012
         * FIXME: should not return to device code in case
4013
         * vm_stop() has been requested.
4014
         */
4015
        if (cpu_single_env) {
4016
            cpu_exit(cpu_single_env);
4017
            cpu_single_env->stop = 1;
4018
        }
4019
        return;
4020
    }
4021
    do_vm_stop(reason);
4022
}
4023

    
4024
#endif
4025

    
4026

    
4027
#ifdef _WIN32
4028
static void host_main_loop_wait(int *timeout)
4029
{
4030
    int ret, ret2, i;
4031
    PollingEntry *pe;
4032

    
4033

    
4034
    /* XXX: need to suppress polling by better using win32 events */
4035
    ret = 0;
4036
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4037
        ret |= pe->func(pe->opaque);
4038
    }
4039
    if (ret == 0) {
4040
        int err;
4041
        WaitObjects *w = &wait_objects;
4042

    
4043
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4044
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4045
            if (w->func[ret - WAIT_OBJECT_0])
4046
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4047

    
4048
            /* Check for additional signaled events */
4049
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4050

    
4051
                /* Check if event is signaled */
4052
                ret2 = WaitForSingleObject(w->events[i], 0);
4053
                if(ret2 == WAIT_OBJECT_0) {
4054
                    if (w->func[i])
4055
                        w->func[i](w->opaque[i]);
4056
                } else if (ret2 == WAIT_TIMEOUT) {
4057
                } else {
4058
                    err = GetLastError();
4059
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4060
                }
4061
            }
4062
        } else if (ret == WAIT_TIMEOUT) {
4063
        } else {
4064
            err = GetLastError();
4065
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4066
        }
4067
    }
4068

    
4069
    *timeout = 0;
4070
}
4071
#else
4072
static void host_main_loop_wait(int *timeout)
4073
{
4074
}
4075
#endif
4076

    
4077
void main_loop_wait(int timeout)
4078
{
4079
    IOHandlerRecord *ioh;
4080
    fd_set rfds, wfds, xfds;
4081
    int ret, nfds;
4082
    struct timeval tv;
4083

    
4084
    qemu_bh_update_timeout(&timeout);
4085

    
4086
    host_main_loop_wait(&timeout);
4087

    
4088
    /* poll any events */
4089
    /* XXX: separate device handlers from system ones */
4090
    nfds = -1;
4091
    FD_ZERO(&rfds);
4092
    FD_ZERO(&wfds);
4093
    FD_ZERO(&xfds);
4094
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4095
        if (ioh->deleted)
4096
            continue;
4097
        if (ioh->fd_read &&
4098
            (!ioh->fd_read_poll ||
4099
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4100
            FD_SET(ioh->fd, &rfds);
4101
            if (ioh->fd > nfds)
4102
                nfds = ioh->fd;
4103
        }
4104
        if (ioh->fd_write) {
4105
            FD_SET(ioh->fd, &wfds);
4106
            if (ioh->fd > nfds)
4107
                nfds = ioh->fd;
4108
        }
4109
    }
4110

    
4111
    tv.tv_sec = timeout / 1000;
4112
    tv.tv_usec = (timeout % 1000) * 1000;
4113

    
4114
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4115

    
4116
    qemu_mutex_unlock_iothread();
4117
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4118
    qemu_mutex_lock_iothread();
4119
    if (ret > 0) {
4120
        IOHandlerRecord **pioh;
4121

    
4122
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4123
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4124
                ioh->fd_read(ioh->opaque);
4125
            }
4126
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4127
                ioh->fd_write(ioh->opaque);
4128
            }
4129
        }
4130

    
4131
        /* remove deleted IO handlers */
4132
        pioh = &first_io_handler;
4133
        while (*pioh) {
4134
            ioh = *pioh;
4135
            if (ioh->deleted) {
4136
                *pioh = ioh->next;
4137
                qemu_free(ioh);
4138
            } else
4139
                pioh = &ioh->next;
4140
        }
4141
    }
4142

    
4143
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4144

    
4145
    /* rearm timer, if not periodic */
4146
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4147
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4148
        qemu_rearm_alarm_timer(alarm_timer);
4149
    }
4150

    
4151
    /* vm time timers */
4152
    if (vm_running) {
4153
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4154
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4155
                qemu_get_clock(vm_clock));
4156
    }
4157

    
4158
    /* real time timers */
4159
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4160
                    qemu_get_clock(rt_clock));
4161

    
4162
    /* Check bottom-halves last in case any of the earlier events triggered
4163
       them.  */
4164
    qemu_bh_poll();
4165

    
4166
}
4167

    
4168
static int qemu_cpu_exec(CPUState *env)
4169
{
4170
    int ret;
4171
#ifdef CONFIG_PROFILER
4172
    int64_t ti;
4173
#endif
4174

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

    
4208
static void tcg_cpu_exec(void)
4209
{
4210
    int ret = 0;
4211

    
4212
    if (next_cpu == NULL)
4213
        next_cpu = first_cpu;
4214
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4215
        CPUState *env = cur_cpu = next_cpu;
4216

    
4217
        if (!vm_running)
4218
            break;
4219
        if (timer_alarm_pending) {
4220
            timer_alarm_pending = 0;
4221
            break;
4222
        }
4223
        if (cpu_can_run(env))
4224
            ret = qemu_cpu_exec(env);
4225
        if (ret == EXCP_DEBUG) {
4226
            gdb_set_stop_cpu(env);
4227
            debug_requested = 1;
4228
            break;
4229
        }
4230
    }
4231
}
4232

    
4233
static int cpu_has_work(CPUState *env)
4234
{
4235
    if (env->stop)
4236
        return 1;
4237
    if (env->stopped)
4238
        return 0;
4239
    if (!env->halted)
4240
        return 1;
4241
    if (qemu_cpu_has_work(env))
4242
        return 1;
4243
    return 0;
4244
}
4245

    
4246
static int tcg_has_work(void)
4247
{
4248
    CPUState *env;
4249

    
4250
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4251
        if (cpu_has_work(env))
4252
            return 1;
4253
    return 0;
4254
}
4255

    
4256
static int qemu_calculate_timeout(void)
4257
{
4258
#ifndef CONFIG_IOTHREAD
4259
    int timeout;
4260

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

    
4303
    return timeout;
4304
#else /* CONFIG_IOTHREAD */
4305
    return 1000;
4306
#endif
4307
}
4308

    
4309
static int vm_can_run(void)
4310
{
4311
    if (powerdown_requested)
4312
        return 0;
4313
    if (reset_requested)
4314
        return 0;
4315
    if (shutdown_requested)
4316
        return 0;
4317
    if (debug_requested)
4318
        return 0;
4319
    return 1;
4320
}
4321

    
4322
static void main_loop(void)
4323
{
4324
    int r;
4325

    
4326
#ifdef CONFIG_IOTHREAD
4327
    qemu_system_ready = 1;
4328
    qemu_cond_broadcast(&qemu_system_cond);
4329
#endif
4330

    
4331
    for (;;) {
4332
        do {
4333
#ifdef CONFIG_PROFILER
4334
            int64_t ti;
4335
#endif
4336
#ifndef CONFIG_IOTHREAD
4337
            tcg_cpu_exec();
4338
#endif
4339
#ifdef CONFIG_PROFILER
4340
            ti = profile_getclock();
4341
#endif
4342
            main_loop_wait(qemu_calculate_timeout());
4343
#ifdef CONFIG_PROFILER
4344
            dev_time += profile_getclock() - ti;
4345
#endif
4346
        } while (vm_can_run());
4347

    
4348
        if (qemu_debug_requested())
4349
            vm_stop(EXCP_DEBUG);
4350
        if (qemu_shutdown_requested()) {
4351
            if (no_shutdown) {
4352
                vm_stop(0);
4353
                no_shutdown = 0;
4354
            } else
4355
                break;
4356
        }
4357
        if (qemu_reset_requested()) {
4358
            pause_all_vcpus();
4359
            qemu_system_reset();
4360
            resume_all_vcpus();
4361
        }
4362
        if (qemu_powerdown_requested())
4363
            qemu_system_powerdown();
4364
        if ((r = qemu_vmstop_requested()))
4365
            vm_stop(r);
4366
    }
4367
    pause_all_vcpus();
4368
}
4369

    
4370
static void version(void)
4371
{
4372
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4373
}
4374

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

    
4408
#define HAS_ARG 0x0001
4409

    
4410
enum {
4411
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4412
    opt_enum,
4413
#define DEFHEADING(text)
4414
#include "qemu-options.h"
4415
#undef DEF
4416
#undef DEFHEADING
4417
#undef GEN_DOCS
4418
};
4419

    
4420
typedef struct QEMUOption {
4421
    const char *name;
4422
    int flags;
4423
    int index;
4424
} QEMUOption;
4425

    
4426
static const QEMUOption qemu_options[] = {
4427
    { "h", 0, QEMU_OPTION_h },
4428
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4429
    { option, opt_arg, opt_enum },
4430
#define DEFHEADING(text)
4431
#include "qemu-options.h"
4432
#undef DEF
4433
#undef DEFHEADING
4434
#undef GEN_DOCS
4435
    { NULL },
4436
};
4437

    
4438
#ifdef HAS_AUDIO
4439
struct soundhw soundhw[] = {
4440
#ifdef HAS_AUDIO_CHOICE
4441
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4442
    {
4443
        "pcspk",
4444
        "PC speaker",
4445
        0,
4446
        1,
4447
        { .init_isa = pcspk_audio_init }
4448
    },
4449
#endif
4450

    
4451
#ifdef CONFIG_SB16
4452
    {
4453
        "sb16",
4454
        "Creative Sound Blaster 16",
4455
        0,
4456
        1,
4457
        { .init_isa = SB16_init }
4458
    },
4459
#endif
4460

    
4461
#ifdef CONFIG_CS4231A
4462
    {
4463
        "cs4231a",
4464
        "CS4231A",
4465
        0,
4466
        1,
4467
        { .init_isa = cs4231a_init }
4468
    },
4469
#endif
4470

    
4471
#ifdef CONFIG_ADLIB
4472
    {
4473
        "adlib",
4474
#ifdef HAS_YMF262
4475
        "Yamaha YMF262 (OPL3)",
4476
#else
4477
        "Yamaha YM3812 (OPL2)",
4478
#endif
4479
        0,
4480
        1,
4481
        { .init_isa = Adlib_init }
4482
    },
4483
#endif
4484

    
4485
#ifdef CONFIG_GUS
4486
    {
4487
        "gus",
4488
        "Gravis Ultrasound GF1",
4489
        0,
4490
        1,
4491
        { .init_isa = GUS_init }
4492
    },
4493
#endif
4494

    
4495
#ifdef CONFIG_AC97
4496
    {
4497
        "ac97",
4498
        "Intel 82801AA AC97 Audio",
4499
        0,
4500
        0,
4501
        { .init_pci = ac97_init }
4502
    },
4503
#endif
4504

    
4505
#ifdef CONFIG_ES1370
4506
    {
4507
        "es1370",
4508
        "ENSONIQ AudioPCI ES1370",
4509
        0,
4510
        0,
4511
        { .init_pci = es1370_init }
4512
    },
4513
#endif
4514

    
4515
#endif /* HAS_AUDIO_CHOICE */
4516

    
4517
    { NULL, NULL, 0, 0, { NULL } }
4518
};
4519

    
4520
static void select_soundhw (const char *optarg)
4521
{
4522
    struct soundhw *c;
4523

    
4524
    if (*optarg == '?') {
4525
    show_valid_cards:
4526

    
4527
        printf ("Valid sound card names (comma separated):\n");
4528
        for (c = soundhw; c->name; ++c) {
4529
            printf ("%-11s %s\n", c->name, c->descr);
4530
        }
4531
        printf ("\n-soundhw all will enable all of the above\n");
4532
        exit (*optarg != '?');
4533
    }
4534
    else {
4535
        size_t l;
4536
        const char *p;
4537
        char *e;
4538
        int bad_card = 0;
4539

    
4540
        if (!strcmp (optarg, "all")) {
4541
            for (c = soundhw; c->name; ++c) {
4542
                c->enabled = 1;
4543
            }
4544
            return;
4545
        }
4546

    
4547
        p = optarg;
4548
        while (*p) {
4549
            e = strchr (p, ',');
4550
            l = !e ? strlen (p) : (size_t) (e - p);
4551

    
4552
            for (c = soundhw; c->name; ++c) {
4553
                if (!strncmp (c->name, p, l)) {
4554
                    c->enabled = 1;
4555
                    break;
4556
                }
4557
            }
4558

    
4559
            if (!c->name) {
4560
                if (l > 80) {
4561
                    fprintf (stderr,
4562
                             "Unknown sound card name (too big to show)\n");
4563
                }
4564
                else {
4565
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4566
                             (int) l, p);
4567
                }
4568
                bad_card = 1;
4569
            }
4570
            p += l + (e != NULL);
4571
        }
4572

    
4573
        if (bad_card)
4574
            goto show_valid_cards;
4575
    }
4576
}
4577
#endif
4578

    
4579
static void select_vgahw (const char *p)
4580
{
4581
    const char *opts;
4582

    
4583
    cirrus_vga_enabled = 0;
4584
    std_vga_enabled = 0;
4585
    vmsvga_enabled = 0;
4586
    xenfb_enabled = 0;
4587
    if (strstart(p, "std", &opts)) {
4588
        std_vga_enabled = 1;
4589
    } else if (strstart(p, "cirrus", &opts)) {
4590
        cirrus_vga_enabled = 1;
4591
    } else if (strstart(p, "vmware", &opts)) {
4592
        vmsvga_enabled = 1;
4593
    } else if (strstart(p, "xenfb", &opts)) {
4594
        xenfb_enabled = 1;
4595
    } else if (!strstart(p, "none", &opts)) {
4596
    invalid_vga:
4597
        fprintf(stderr, "Unknown vga type: %s\n", p);
4598
        exit(1);
4599
    }
4600
    while (*opts) {
4601
        const char *nextopt;
4602

    
4603
        if (strstart(opts, ",retrace=", &nextopt)) {
4604
            opts = nextopt;
4605
            if (strstart(opts, "dumb", &nextopt))
4606
                vga_retrace_method = VGA_RETRACE_DUMB;
4607
            else if (strstart(opts, "precise", &nextopt))
4608
                vga_retrace_method = VGA_RETRACE_PRECISE;
4609
            else goto invalid_vga;
4610
        } else goto invalid_vga;
4611
        opts = nextopt;
4612
    }
4613
}
4614

    
4615
#ifdef TARGET_I386
4616
static int balloon_parse(const char *arg)
4617
{
4618
    char buf[128];
4619
    const char *p;
4620

    
4621
    if (!strcmp(arg, "none")) {
4622
        virtio_balloon = 0;
4623
    } else if (!strncmp(arg, "virtio", 6)) {
4624
        virtio_balloon = 1;
4625
        if (arg[6] == ',')  {
4626
            p = arg + 7;
4627
            if (get_param_value(buf, sizeof(buf), "addr", p)) {
4628
                virtio_balloon_devaddr = strdup(buf);
4629
            }
4630
        }
4631
    } else {
4632
        return -1;
4633
    }
4634
    return 0;
4635
}
4636
#endif
4637

    
4638
#ifdef _WIN32
4639
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4640
{
4641
    exit(STATUS_CONTROL_C_EXIT);
4642
    return TRUE;
4643
}
4644
#endif
4645

    
4646
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4647
{
4648
    int ret;
4649

    
4650
    if(strlen(str) != 36)
4651
        return -1;
4652

    
4653
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4654
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4655
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4656

    
4657
    if(ret != 16)
4658
        return -1;
4659

    
4660
#ifdef TARGET_I386
4661
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4662
#endif
4663

    
4664
    return 0;
4665
}
4666

    
4667
#define MAX_NET_CLIENTS 32
4668

    
4669
#ifndef _WIN32
4670

    
4671
static void termsig_handler(int signal)
4672
{
4673
    qemu_system_shutdown_request();
4674
}
4675

    
4676
static void sigchld_handler(int signal)
4677
{
4678
    waitpid(-1, NULL, WNOHANG);
4679
}
4680

    
4681
static void sighandler_setup(void)
4682
{
4683
    struct sigaction act;
4684

    
4685
    memset(&act, 0, sizeof(act));
4686
    act.sa_handler = termsig_handler;
4687
    sigaction(SIGINT,  &act, NULL);
4688
    sigaction(SIGHUP,  &act, NULL);
4689
    sigaction(SIGTERM, &act, NULL);
4690

    
4691
    act.sa_handler = sigchld_handler;
4692
    act.sa_flags = SA_NOCLDSTOP;
4693
    sigaction(SIGCHLD, &act, NULL);
4694
}
4695

    
4696
#endif
4697

    
4698
#ifdef _WIN32
4699
/* Look for support files in the same directory as the executable.  */
4700
static char *find_datadir(const char *argv0)
4701
{
4702
    char *p;
4703
    char buf[MAX_PATH];
4704
    DWORD len;
4705

    
4706
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4707
    if (len == 0) {
4708
        return NULL;
4709
    }
4710

    
4711
    buf[len] = 0;
4712
    p = buf + len - 1;
4713
    while (p != buf && *p != '\\')
4714
        p--;
4715
    *p = 0;
4716
    if (access(buf, R_OK) == 0) {
4717
        return qemu_strdup(buf);
4718
    }
4719
    return NULL;
4720
}
4721
#else /* !_WIN32 */
4722

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

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

    
4771
    max_len = strlen(dir) +
4772
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4773
    res = qemu_mallocz(max_len);
4774
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4775
    if (access(res, R_OK)) {
4776
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4777
        if (access(res, R_OK)) {
4778
            qemu_free(res);
4779
            res = NULL;
4780
        }
4781
    }
4782
#ifndef PATH_MAX
4783
    free(p);
4784
#endif
4785
    return res;
4786
}
4787
#undef SHARE_SUFFIX
4788
#undef BUILD_SUFFIX
4789
#endif
4790

    
4791
char *qemu_find_file(int type, const char *name)
4792
{
4793
    int len;
4794
    const char *subdir;
4795
    char *buf;
4796

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

    
4822
struct device_config {
4823
    enum {
4824
        DEV_GENERIC,   /* -device      */
4825
        DEV_USB,       /* -usbdevice   */
4826
        DEV_BT,        /* -bt          */
4827
    } type;
4828
    const char *cmdline;
4829
    TAILQ_ENTRY(device_config) next;
4830
};
4831
TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4832

    
4833
static void add_device_config(int type, const char *cmdline)
4834
{
4835
    struct device_config *conf;
4836

    
4837
    conf = qemu_mallocz(sizeof(*conf));
4838
    conf->type = type;
4839
    conf->cmdline = cmdline;
4840
    TAILQ_INSERT_TAIL(&device_configs, conf, next);
4841
}
4842

    
4843
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4844
{
4845
    struct device_config *conf;
4846
    int rc;
4847

    
4848
    TAILQ_FOREACH(conf, &device_configs, next) {
4849
        if (conf->type != type)
4850
            continue;
4851
        rc = func(conf->cmdline);
4852
        if (0 != rc)
4853
            return rc;
4854
    }
4855
    return 0;
4856
}
4857

    
4858
static int generic_parse(const char *cmdline)
4859
{
4860
    DeviceState *dev;
4861

    
4862
    dev = qdev_device_add(cmdline);
4863
    if (!dev)
4864
        return -1;
4865
    return 0;
4866
}
4867

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

    
4911
    qemu_cache_utils_init(envp);
4912

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

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

    
4956
    serial_devices[0] = "vc:80Cx24C";
4957
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4958
        serial_devices[i] = NULL;
4959
    serial_device_index = 0;
4960

    
4961
    parallel_devices[0] = "vc:80Cx24C";
4962
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4963
        parallel_devices[i] = NULL;
4964
    parallel_device_index = 0;
4965

    
4966
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4967
        virtio_consoles[i] = NULL;
4968
    virtio_console_index = 0;
4969

    
4970
    for (i = 0; i < MAX_NODES; i++) {
4971
        node_mem[i] = 0;
4972
        node_cpumask[i] = 0;
4973
    }
4974

    
4975
    nb_net_clients = 0;
4976
    nb_numa_nodes = 0;
4977
    nb_nics = 0;
4978

    
4979
    tb_size = 0;
4980
    autostart= 1;
4981

    
4982
    register_watchdogs();
4983

    
4984
    optind = 1;
4985
    for(;;) {
4986
        if (optind >= argc)
4987
            break;
4988
        r = argv[optind];
4989
        if (r[0] != '-') {
4990
            hda_opt = drive_add(argv[optind++], HD_ALIAS, 0);
4991
        } else {
4992
            const QEMUOption *popt;
4993

    
4994
            optind++;
4995
            /* Treat --foo the same as -foo.  */
4996
            if (r[1] == '-')
4997
                r++;
4998
            popt = qemu_options;
4999
            for(;;) {
5000
                if (!popt->name) {
5001
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
5002
                            argv[0], r);
5003
                    exit(1);
5004
                }
5005
                if (!strcmp(popt->name, r + 1))
5006
                    break;
5007
                popt++;
5008
            }
5009
            if (popt->flags & HAS_ARG) {
5010
                if (optind >= argc) {
5011
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
5012
                            argv[0], r);
5013
                    exit(1);
5014
                }
5015
                optarg = argv[optind++];
5016
            } else {
5017
                optarg = NULL;
5018
            }
5019

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

    
5165
                    if (!strchr(optarg, '=')) {
5166
                        legacy = 1;
5167
                        pstrcpy(buf, sizeof(buf), optarg);
5168
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5169
                        fprintf(stderr,
5170
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5171
                                buf, optarg);
5172
                        exit(1);
5173
                    }
5174

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

    
5261
                value = strtoul(optarg, &ptr, 10);
5262
                switch (*ptr) {
5263
                case 0: case 'M': case 'm':
5264
                    value <<= 20;
5265
                    break;
5266
                case 'G': case 'g':
5267
                    value <<= 30;
5268
                    break;
5269
                default:
5270
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5271
                    exit(1);
5272
                }
5273

    
5274
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5275
                if (value > (2047 << 20)
5276
#ifndef CONFIG_KQEMU
5277
                    && HOST_LONG_BITS == 32
5278
#endif
5279
                    ) {
5280
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5281
                    exit(1);
5282
                }
5283
                if (value != (uint64_t)(ram_addr_t)value) {
5284
                    fprintf(stderr, "qemu: ram size too large\n");
5285
                    exit(1);
5286
                }
5287
                ram_size = value;
5288
                break;
5289
            }
5290
            case QEMU_OPTION_d:
5291
                {
5292
                    int mask;
5293
                    const CPULogItem *item;
5294

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

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

    
5655
    /* If no data_dir is specified then try to find it relative to the
5656
       executable path.  */
5657
    if (!data_dir) {
5658
        data_dir = find_datadir(argv[0]);
5659
    }
5660
    /* If all else fails use the install patch specified when building.  */
5661
    if (!data_dir) {
5662
        data_dir = CONFIG_QEMU_SHAREDIR;
5663
    }
5664

    
5665
#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5666
    if (kvm_allowed && kqemu_allowed) {
5667
        fprintf(stderr,
5668
                "You can not enable both KVM and kqemu at the same time\n");
5669
        exit(1);
5670
    }
5671
#endif
5672

    
5673
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5674
    if (smp_cpus > machine->max_cpus) {
5675
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5676
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5677
                machine->max_cpus);
5678
        exit(1);
5679
    }
5680

    
5681
    if (display_type == DT_NOGRAPHIC) {
5682
       if (serial_device_index == 0)
5683
           serial_devices[0] = "stdio";
5684
       if (parallel_device_index == 0)
5685
           parallel_devices[0] = "null";
5686
       if (strncmp(monitor_device, "vc", 2) == 0)
5687
           monitor_device = "stdio";
5688
    }
5689

    
5690
#ifndef _WIN32
5691
    if (daemonize) {
5692
        pid_t pid;
5693

    
5694
        if (pipe(fds) == -1)
5695
            exit(1);
5696

    
5697
        pid = fork();
5698
        if (pid > 0) {
5699
            uint8_t status;
5700
            ssize_t len;
5701

    
5702
            close(fds[1]);
5703

    
5704
        again:
5705
            len = read(fds[0], &status, 1);
5706
            if (len == -1 && (errno == EINTR))
5707
                goto again;
5708

    
5709
            if (len != 1)
5710
                exit(1);
5711
            else if (status == 1) {
5712
                fprintf(stderr, "Could not acquire pidfile\n");
5713
                exit(1);
5714
            } else
5715
                exit(0);
5716
        } else if (pid < 0)
5717
            exit(1);
5718

    
5719
        setsid();
5720

    
5721
        pid = fork();
5722
        if (pid > 0)
5723
            exit(0);
5724
        else if (pid < 0)
5725
            exit(1);
5726

    
5727
        umask(027);
5728

    
5729
        signal(SIGTSTP, SIG_IGN);
5730
        signal(SIGTTOU, SIG_IGN);
5731
        signal(SIGTTIN, SIG_IGN);
5732
    }
5733

    
5734
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5735
        if (daemonize) {
5736
            uint8_t status = 1;
5737
            write(fds[1], &status, 1);
5738
        } else
5739
            fprintf(stderr, "Could not acquire pid file\n");
5740
        exit(1);
5741
    }
5742
#endif
5743

    
5744
#ifdef CONFIG_KQEMU
5745
    if (smp_cpus > 1)
5746
        kqemu_allowed = 0;
5747
#endif
5748
    if (qemu_init_main_loop()) {
5749
        fprintf(stderr, "qemu_init_main_loop failed\n");
5750
        exit(1);
5751
    }
5752
    linux_boot = (kernel_filename != NULL);
5753

    
5754
    if (!linux_boot && *kernel_cmdline != '\0') {
5755
        fprintf(stderr, "-append only allowed with -kernel option\n");
5756
        exit(1);
5757
    }
5758

    
5759
    if (!linux_boot && initrd_filename != NULL) {
5760
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5761
        exit(1);
5762
    }
5763

    
5764
    setvbuf(stdout, NULL, _IOLBF, 0);
5765

    
5766
    init_timers();
5767
    if (init_timer_alarm() < 0) {
5768
        fprintf(stderr, "could not initialize alarm timer\n");
5769
        exit(1);
5770
    }
5771
    if (use_icount && icount_time_shift < 0) {
5772
        use_icount = 2;
5773
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5774
           It will be corrected fairly quickly anyway.  */
5775
        icount_time_shift = 3;
5776
        init_icount_adjust();
5777
    }
5778

    
5779
#ifdef _WIN32
5780
    socket_init();
5781
#endif
5782

    
5783
    /* init network clients */
5784
    if (nb_net_clients == 0) {
5785
        /* if no clients, we use a default config */
5786
        net_clients[nb_net_clients++] = "nic";
5787
#ifdef CONFIG_SLIRP
5788
        net_clients[nb_net_clients++] = "user";
5789
#endif
5790
    }
5791

    
5792
    for(i = 0;i < nb_net_clients; i++) {
5793
        if (net_client_parse(net_clients[i]) < 0)
5794
            exit(1);
5795
    }
5796

    
5797
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5798
    net_set_boot_mask(net_boot);
5799

    
5800
    net_client_check();
5801

    
5802
    /* init the bluetooth world */
5803
    if (foreach_device_config(DEV_BT, bt_parse))
5804
        exit(1);
5805

    
5806
    /* init the memory */
5807
    if (ram_size == 0)
5808
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5809

    
5810
#ifdef CONFIG_KQEMU
5811
    /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5812
       guest ram allocation.  It needs to go away.  */
5813
    if (kqemu_allowed) {
5814
        kqemu_phys_ram_size = ram_size + 8 * 1024 * 1024 + 4 * 1024 * 1024;
5815
        kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5816
        if (!kqemu_phys_ram_base) {
5817
            fprintf(stderr, "Could not allocate physical memory\n");
5818
            exit(1);
5819
        }
5820
    }
5821
#endif
5822

    
5823
    /* init the dynamic translator */
5824
    cpu_exec_init_all(tb_size * 1024 * 1024);
5825

    
5826
    bdrv_init();
5827

    
5828
    /* we always create the cdrom drive, even if no disk is there */
5829
    drive_add(NULL, CDROM_ALIAS);
5830

    
5831
    /* we always create at least one floppy */
5832
    drive_add(NULL, FD_ALIAS, 0);
5833

    
5834
    /* we always create one sd slot, even if no card is in it */
5835
    drive_add(NULL, SD_ALIAS);
5836

    
5837
    /* open the virtual block devices */
5838

    
5839
    TAILQ_FOREACH(dopt, &driveopts, next) {
5840
        int fatal_error;
5841
        if (drive_init(dopt, snapshot, machine, &fatal_error) == NULL)
5842
            if (fatal_error)
5843
                exit(1);
5844
    }
5845

    
5846
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5847
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5848

    
5849
#ifndef _WIN32
5850
    /* must be after terminal init, SDL library changes signal handlers */
5851
    sighandler_setup();
5852
#endif
5853

    
5854
    /* Maintain compatibility with multiple stdio monitors */
5855
    if (!strcmp(monitor_device,"stdio")) {
5856
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5857
            const char *devname = serial_devices[i];
5858
            if (devname && !strcmp(devname,"mon:stdio")) {
5859
                monitor_device = NULL;
5860
                break;
5861
            } else if (devname && !strcmp(devname,"stdio")) {
5862
                monitor_device = NULL;
5863
                serial_devices[i] = "mon:stdio";
5864
                break;
5865
            }
5866
        }
5867
    }
5868

    
5869
    if (nb_numa_nodes > 0) {
5870
        int i;
5871

    
5872
        if (nb_numa_nodes > smp_cpus) {
5873
            nb_numa_nodes = smp_cpus;
5874
        }
5875

    
5876
        /* If no memory size if given for any node, assume the default case
5877
         * and distribute the available memory equally across all nodes
5878
         */
5879
        for (i = 0; i < nb_numa_nodes; i++) {
5880
            if (node_mem[i] != 0)
5881
                break;
5882
        }
5883
        if (i == nb_numa_nodes) {
5884
            uint64_t usedmem = 0;
5885

    
5886
            /* On Linux, the each node's border has to be 8MB aligned,
5887
             * the final node gets the rest.
5888
             */
5889
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5890
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5891
                usedmem += node_mem[i];
5892
            }
5893
            node_mem[i] = ram_size - usedmem;
5894
        }
5895

    
5896
        for (i = 0; i < nb_numa_nodes; i++) {
5897
            if (node_cpumask[i] != 0)
5898
                break;
5899
        }
5900
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5901
         * must cope with this anyway, because there are BIOSes out there in
5902
         * real machines which also use this scheme.
5903
         */
5904
        if (i == nb_numa_nodes) {
5905
            for (i = 0; i < smp_cpus; i++) {
5906
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5907
            }
5908
        }
5909
    }
5910

    
5911
    if (kvm_enabled()) {
5912
        int ret;
5913

    
5914
        ret = kvm_init(smp_cpus);
5915
        if (ret < 0) {
5916
            fprintf(stderr, "failed to initialize KVM\n");
5917
            exit(1);
5918
        }
5919
    }
5920

    
5921
    if (monitor_device) {
5922
        monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5923
        if (!monitor_hd) {
5924
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5925
            exit(1);
5926
        }
5927
    }
5928

    
5929
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5930
        const char *devname = serial_devices[i];
5931
        if (devname && strcmp(devname, "none")) {
5932
            char label[32];
5933
            snprintf(label, sizeof(label), "serial%d", i);
5934
            serial_hds[i] = qemu_chr_open(label, devname, NULL);
5935
            if (!serial_hds[i]) {
5936
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5937
                        devname);
5938
                exit(1);
5939
            }
5940
        }
5941
    }
5942

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

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

    
5971
    module_call_init(MODULE_INIT_DEVICE);
5972

    
5973
    if (machine->compat_props) {
5974
        qdev_prop_register_compat(machine->compat_props);
5975
    }
5976
    machine->init(ram_size, boot_devices,
5977
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5978

    
5979

    
5980
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5981
        for (i = 0; i < nb_numa_nodes; i++) {
5982
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5983
                env->numa_node = i;
5984
            }
5985
        }
5986
    }
5987

    
5988
    current_machine = machine;
5989

    
5990
    /* init USB devices */
5991
    if (usb_enabled) {
5992
        foreach_device_config(DEV_USB, usb_parse);
5993
    }
5994

    
5995
    /* init generic devices */
5996
    if (foreach_device_config(DEV_GENERIC, generic_parse))
5997
        exit(1);
5998

    
5999
    if (!display_state)
6000
        dumb_display_init();
6001
    /* just use the first displaystate for the moment */
6002
    ds = display_state;
6003

    
6004
    if (display_type == DT_DEFAULT) {
6005
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6006
        display_type = DT_SDL;
6007
#else
6008
        display_type = DT_VNC;
6009
        vnc_display = "localhost:0,to=99";
6010
        show_vnc_port = 1;
6011
#endif
6012
    }
6013
        
6014

    
6015
    switch (display_type) {
6016
    case DT_NOGRAPHIC:
6017
        break;
6018
#if defined(CONFIG_CURSES)
6019
    case DT_CURSES:
6020
        curses_display_init(ds, full_screen);
6021
        break;
6022
#endif
6023
#if defined(CONFIG_SDL)
6024
    case DT_SDL:
6025
        sdl_display_init(ds, full_screen, no_frame);
6026
        break;
6027
#elif defined(CONFIG_COCOA)
6028
    case DT_SDL:
6029
        cocoa_display_init(ds, full_screen);
6030
        break;
6031
#endif
6032
    case DT_VNC:
6033
        vnc_display_init(ds);
6034
        if (vnc_display_open(ds, vnc_display) < 0)
6035
            exit(1);
6036

    
6037
        if (show_vnc_port) {
6038
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6039
        }
6040
        break;
6041
    default:
6042
        break;
6043
    }
6044
    dpy_resize(ds);
6045

    
6046
    dcl = ds->listeners;
6047
    while (dcl != NULL) {
6048
        if (dcl->dpy_refresh != NULL) {
6049
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6050
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6051
        }
6052
        dcl = dcl->next;
6053
    }
6054

    
6055
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6056
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6057
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6058
    }
6059

    
6060
    text_consoles_set_display(display_state);
6061
    qemu_chr_initial_reset();
6062

    
6063
    if (monitor_device && monitor_hd)
6064
        monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6065

    
6066
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6067
        const char *devname = serial_devices[i];
6068
        if (devname && strcmp(devname, "none")) {
6069
            if (strstart(devname, "vc", 0))
6070
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6071
        }
6072
    }
6073

    
6074
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6075
        const char *devname = parallel_devices[i];
6076
        if (devname && strcmp(devname, "none")) {
6077
            if (strstart(devname, "vc", 0))
6078
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6079
        }
6080
    }
6081

    
6082
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6083
        const char *devname = virtio_consoles[i];
6084
        if (virtcon_hds[i] && devname) {
6085
            if (strstart(devname, "vc", 0))
6086
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6087
        }
6088
    }
6089

    
6090
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6091
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6092
                gdbstub_dev);
6093
        exit(1);
6094
    }
6095

    
6096
    if (loadvm)
6097
        do_loadvm(cur_mon, loadvm);
6098

    
6099
    if (incoming)
6100
        qemu_start_incoming_migration(incoming);
6101

    
6102
    if (autostart)
6103
        vm_start();
6104

    
6105
#ifndef _WIN32
6106
    if (daemonize) {
6107
        uint8_t status = 0;
6108
        ssize_t len;
6109

    
6110
    again1:
6111
        len = write(fds[1], &status, 1);
6112
        if (len == -1 && (errno == EINTR))
6113
            goto again1;
6114

    
6115
        if (len != 1)
6116
            exit(1);
6117

    
6118
        chdir("/");
6119
        TFR(fd = open("/dev/null", O_RDWR));
6120
        if (fd == -1)
6121
            exit(1);
6122
    }
6123

    
6124
    if (run_as) {
6125
        pwd = getpwnam(run_as);
6126
        if (!pwd) {
6127
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6128
            exit(1);
6129
        }
6130
    }
6131

    
6132
    if (chroot_dir) {
6133
        if (chroot(chroot_dir) < 0) {
6134
            fprintf(stderr, "chroot failed\n");
6135
            exit(1);
6136
        }
6137
        chdir("/");
6138
    }
6139

    
6140
    if (run_as) {
6141
        if (setgid(pwd->pw_gid) < 0) {
6142
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6143
            exit(1);
6144
        }
6145
        if (setuid(pwd->pw_uid) < 0) {
6146
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6147
            exit(1);
6148
        }
6149
        if (setuid(0) != -1) {
6150
            fprintf(stderr, "Dropping privileges failed\n");
6151
            exit(1);
6152
        }
6153
    }
6154

    
6155
    if (daemonize) {
6156
        dup2(fd, 0);
6157
        dup2(fd, 1);
6158
        dup2(fd, 2);
6159

    
6160
        close(fd);
6161
    }
6162
#endif
6163

    
6164
    main_loop();
6165
    quit_timers();
6166
    net_cleanup();
6167

    
6168
    return 0;
6169
}