Statistics
| Branch: | Revision:

root / vl.c @ 88b3be20

History | View | Annotate | Download (155.1 kB)

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

    
32
/* Needed early for CONFIG_BSD etc. */
33
#include "config-host.h"
34
/* 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 CONFIG_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 <mmsystem.h>
112
#endif
113

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

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

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

    
163
#include "disas.h"
164

    
165
#include "exec-all.h"
166

    
167
#include "qemu_socket.h"
168

    
169
#include "slirp/libslirp.h"
170

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

    
174
#define DEFAULT_RAM_SIZE 128
175

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

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

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

    
267
uint8_t qemu_uuid[16];
268

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

    
272
/***********************************************************/
273
/* x86 ISA bus support */
274

    
275
target_phys_addr_t isa_mem_base = 0;
276
PicState2 *isa_pic;
277

    
278
/***********************************************************/
279
void hw_error(const char *fmt, ...)
280
{
281
    va_list ap;
282
    CPUState *env;
283

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

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

    
317
static QEMUBalloonEvent *qemu_balloon_event;
318
void *qemu_balloon_event_opaque;
319

    
320
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
321
{
322
    qemu_balloon_event = func;
323
    qemu_balloon_event_opaque = opaque;
324
}
325

    
326
void qemu_balloon(ram_addr_t target)
327
{
328
    if (qemu_balloon_event)
329
        qemu_balloon_event(qemu_balloon_event_opaque, target);
330
}
331

    
332
ram_addr_t qemu_balloon_status(void)
333
{
334
    if (qemu_balloon_event)
335
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
336
    return 0;
337
}
338

    
339
/***********************************************************/
340
/* keyboard/mouse */
341

    
342
static QEMUPutKBDEvent *qemu_put_kbd_event;
343
static void *qemu_put_kbd_event_opaque;
344
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
345
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
346

    
347
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
348
{
349
    qemu_put_kbd_event_opaque = opaque;
350
    qemu_put_kbd_event = func;
351
}
352

    
353
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
354
                                                void *opaque, int absolute,
355
                                                const char *name)
356
{
357
    QEMUPutMouseEntry *s, *cursor;
358

    
359
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
360

    
361
    s->qemu_put_mouse_event = func;
362
    s->qemu_put_mouse_event_opaque = opaque;
363
    s->qemu_put_mouse_event_absolute = absolute;
364
    s->qemu_put_mouse_event_name = qemu_strdup(name);
365
    s->next = NULL;
366

    
367
    if (!qemu_put_mouse_event_head) {
368
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
369
        return s;
370
    }
371

    
372
    cursor = qemu_put_mouse_event_head;
373
    while (cursor->next != NULL)
374
        cursor = cursor->next;
375

    
376
    cursor->next = s;
377
    qemu_put_mouse_event_current = s;
378

    
379
    return s;
380
}
381

    
382
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
383
{
384
    QEMUPutMouseEntry *prev = NULL, *cursor;
385

    
386
    if (!qemu_put_mouse_event_head || entry == NULL)
387
        return;
388

    
389
    cursor = qemu_put_mouse_event_head;
390
    while (cursor != NULL && cursor != entry) {
391
        prev = cursor;
392
        cursor = cursor->next;
393
    }
394

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

    
406
    prev->next = entry->next;
407

    
408
    if (qemu_put_mouse_event_current == entry)
409
        qemu_put_mouse_event_current = prev;
410

    
411
    qemu_free(entry->qemu_put_mouse_event_name);
412
    qemu_free(entry);
413
}
414

    
415
void kbd_put_keycode(int keycode)
416
{
417
    if (qemu_put_kbd_event) {
418
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
419
    }
420
}
421

    
422
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
423
{
424
    QEMUPutMouseEvent *mouse_event;
425
    void *mouse_event_opaque;
426
    int width;
427

    
428
    if (!qemu_put_mouse_event_current) {
429
        return;
430
    }
431

    
432
    mouse_event =
433
        qemu_put_mouse_event_current->qemu_put_mouse_event;
434
    mouse_event_opaque =
435
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
436

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

    
451
int kbd_mouse_is_absolute(void)
452
{
453
    if (!qemu_put_mouse_event_current)
454
        return 0;
455

    
456
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
457
}
458

    
459
void do_info_mice(Monitor *mon)
460
{
461
    QEMUPutMouseEntry *cursor;
462
    int index = 0;
463

    
464
    if (!qemu_put_mouse_event_head) {
465
        monitor_printf(mon, "No mouse devices connected\n");
466
        return;
467
    }
468

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

    
480
void do_mouse_set(Monitor *mon, int index)
481
{
482
    QEMUPutMouseEntry *cursor;
483
    int i = 0;
484

    
485
    if (!qemu_put_mouse_event_head) {
486
        monitor_printf(mon, "No mouse devices connected\n");
487
        return;
488
    }
489

    
490
    cursor = qemu_put_mouse_event_head;
491
    while (cursor != NULL && index != i) {
492
        i++;
493
        cursor = cursor->next;
494
    }
495

    
496
    if (cursor != NULL)
497
        qemu_put_mouse_event_current = cursor;
498
    else
499
        monitor_printf(mon, "Mouse at given index not found\n");
500
}
501

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

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

    
526
/***********************************************************/
527
/* real time host monotonic timer */
528

    
529
#define QEMU_TIMER_BASE 1000000000LL
530

    
531
#ifdef WIN32
532

    
533
static int64_t clock_freq;
534

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

    
547
static int64_t get_clock(void)
548
{
549
    LARGE_INTEGER ti;
550
    QueryPerformanceCounter(&ti);
551
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
552
}
553

    
554
#else
555

    
556
static int use_rt_clock;
557

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

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

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

    
606
/***********************************************************/
607
/* guest cycle counter */
608

    
609
static int64_t cpu_ticks_prev;
610
static int64_t cpu_ticks_offset;
611
static int64_t cpu_clock_offset;
612
static int cpu_ticks_enabled;
613

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

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

    
647
/* enable cpu_get_ticks() */
648
void cpu_enable_ticks(void)
649
{
650
    if (!cpu_ticks_enabled) {
651
        cpu_ticks_offset -= cpu_get_real_ticks();
652
        cpu_clock_offset -= get_clock();
653
        cpu_ticks_enabled = 1;
654
    }
655
}
656

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

    
668
/***********************************************************/
669
/* timers */
670

    
671
#define QEMU_TIMER_REALTIME 0
672
#define QEMU_TIMER_VIRTUAL  1
673

    
674
struct QEMUClock {
675
    int type;
676
    /* XXX: add frequency */
677
};
678

    
679
struct QEMUTimer {
680
    QEMUClock *clock;
681
    int64_t expire_time;
682
    QEMUTimerCB *cb;
683
    void *opaque;
684
    struct QEMUTimer *next;
685
};
686

    
687
struct qemu_alarm_timer {
688
    char const *name;
689
    unsigned int flags;
690

    
691
    int (*start)(struct qemu_alarm_timer *t);
692
    void (*stop)(struct qemu_alarm_timer *t);
693
    void (*rearm)(struct qemu_alarm_timer *t);
694
    void *priv;
695
};
696

    
697
#define ALARM_FLAG_DYNTICKS  0x1
698
#define ALARM_FLAG_EXPIRED   0x2
699

    
700
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
701
{
702
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
703
}
704

    
705
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
706
{
707
    if (!alarm_has_dynticks(t))
708
        return;
709

    
710
    t->rearm(t);
711
}
712

    
713
/* TODO: MIN_TIMER_REARM_US should be optimized */
714
#define MIN_TIMER_REARM_US 250
715

    
716
static struct qemu_alarm_timer *alarm_timer;
717

    
718
#ifdef _WIN32
719

    
720
struct qemu_alarm_win32 {
721
    MMRESULT timerId;
722
    unsigned int period;
723
} alarm_win32_data = {0, -1};
724

    
725
static int win32_start_timer(struct qemu_alarm_timer *t);
726
static void win32_stop_timer(struct qemu_alarm_timer *t);
727
static void win32_rearm_timer(struct qemu_alarm_timer *t);
728

    
729
#else
730

    
731
static int unix_start_timer(struct qemu_alarm_timer *t);
732
static void unix_stop_timer(struct qemu_alarm_timer *t);
733

    
734
#ifdef __linux__
735

    
736
static int dynticks_start_timer(struct qemu_alarm_timer *t);
737
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
738
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
739

    
740
static int hpet_start_timer(struct qemu_alarm_timer *t);
741
static void hpet_stop_timer(struct qemu_alarm_timer *t);
742

    
743
static int rtc_start_timer(struct qemu_alarm_timer *t);
744
static void rtc_stop_timer(struct qemu_alarm_timer *t);
745

    
746
#endif /* __linux__ */
747

    
748
#endif /* _WIN32 */
749

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

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

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

    
786
static void icount_adjust_rt(void * opaque)
787
{
788
    qemu_mod_timer(icount_rt_timer,
789
                   qemu_get_clock(rt_clock) + 1000);
790
    icount_adjust();
791
}
792

    
793
static void icount_adjust_vm(void * opaque)
794
{
795
    qemu_mod_timer(icount_vm_timer,
796
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
797
    icount_adjust();
798
}
799

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

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

    
835
static void show_available_alarms(void)
836
{
837
    int i;
838

    
839
    printf("Available alarm timers, in order of precedence:\n");
840
    for (i = 0; alarm_timers[i].name; i++)
841
        printf("%s\n", alarm_timers[i].name);
842
}
843

    
844
static void configure_alarms(char const *opt)
845
{
846
    int i;
847
    int cur = 0;
848
    int count = ARRAY_SIZE(alarm_timers) - 1;
849
    char *arg;
850
    char *name;
851
    struct qemu_alarm_timer tmp;
852

    
853
    if (!strcmp(opt, "?")) {
854
        show_available_alarms();
855
        exit(0);
856
    }
857

    
858
    arg = strdup(opt);
859

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

    
868
        if (i == count) {
869
            fprintf(stderr, "Unknown clock %s\n", name);
870
            goto next;
871
        }
872

    
873
        if (i < cur)
874
            /* Ignore */
875
            goto next;
876

    
877
        /* Swap */
878
        tmp = alarm_timers[i];
879
        alarm_timers[i] = alarm_timers[cur];
880
        alarm_timers[cur] = tmp;
881

    
882
        cur++;
883
next:
884
        name = strtok(NULL, ",");
885
    }
886

    
887
    free(arg);
888

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

    
899
QEMUClock *rt_clock;
900
QEMUClock *vm_clock;
901

    
902
static QEMUTimer *active_timers[2];
903

    
904
static QEMUClock *qemu_new_clock(int type)
905
{
906
    QEMUClock *clock;
907
    clock = qemu_mallocz(sizeof(QEMUClock));
908
    clock->type = type;
909
    return clock;
910
}
911

    
912
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
913
{
914
    QEMUTimer *ts;
915

    
916
    ts = qemu_mallocz(sizeof(QEMUTimer));
917
    ts->clock = clock;
918
    ts->cb = cb;
919
    ts->opaque = opaque;
920
    return ts;
921
}
922

    
923
void qemu_free_timer(QEMUTimer *ts)
924
{
925
    qemu_free(ts);
926
}
927

    
928
/* stop a timer, but do not dealloc it */
929
void qemu_del_timer(QEMUTimer *ts)
930
{
931
    QEMUTimer **pt, *t;
932

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

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

    
954
    qemu_del_timer(ts);
955

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

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

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

    
993
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
994
{
995
    if (!timer_head)
996
        return 0;
997
    return (timer_head->expire_time <= current_time);
998
}
999

    
1000
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1001
{
1002
    QEMUTimer *ts;
1003

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

    
1012
        /* run the callback (the timer list can be modified) */
1013
        ts->cb(ts->opaque);
1014
    }
1015
}
1016

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

    
1032
static void init_timers(void)
1033
{
1034
    init_get_clock();
1035
    ticks_per_sec = QEMU_TIMER_BASE;
1036
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1037
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1038
}
1039

    
1040
/* save a timer */
1041
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1042
{
1043
    uint64_t expire_time;
1044

    
1045
    if (qemu_timer_pending(ts)) {
1046
        expire_time = ts->expire_time;
1047
    } else {
1048
        expire_time = -1;
1049
    }
1050
    qemu_put_be64(f, expire_time);
1051
}
1052

    
1053
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1054
{
1055
    uint64_t expire_time;
1056

    
1057
    expire_time = qemu_get_be64(f);
1058
    if (expire_time != -1) {
1059
        qemu_mod_timer(ts, expire_time);
1060
    } else {
1061
        qemu_del_timer(ts);
1062
    }
1063
}
1064

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

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

    
1090
static void qemu_event_increment(void);
1091

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

    
1138
#ifndef CONFIG_IOTHREAD
1139
        if (next_cpu) {
1140
            /* stop the currently executing cpu because a timer occured */
1141
            cpu_exit(next_cpu);
1142
        }
1143
#endif
1144
        timer_alarm_pending = 1;
1145
        qemu_notify_event();
1146
    }
1147
}
1148

    
1149
static int64_t qemu_next_deadline(void)
1150
{
1151
    int64_t delta;
1152

    
1153
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1154
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1155
                     qemu_get_clock(vm_clock);
1156
    } else {
1157
        /* To avoid problems with overflow limit this to 2^32.  */
1158
        delta = INT32_MAX;
1159
    }
1160

    
1161
    if (delta < 0)
1162
        delta = 0;
1163

    
1164
    return delta;
1165
}
1166

    
1167
#if defined(__linux__) || defined(_WIN32)
1168
static uint64_t qemu_next_deadline_dyntick(void)
1169
{
1170
    int64_t delta;
1171
    int64_t rtdelta;
1172

    
1173
    if (use_icount)
1174
        delta = INT32_MAX;
1175
    else
1176
        delta = (qemu_next_deadline() + 999) / 1000;
1177

    
1178
    if (active_timers[QEMU_TIMER_REALTIME]) {
1179
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1180
                 qemu_get_clock(rt_clock))*1000;
1181
        if (rtdelta < delta)
1182
            delta = rtdelta;
1183
    }
1184

    
1185
    if (delta < MIN_TIMER_REARM_US)
1186
        delta = MIN_TIMER_REARM_US;
1187

    
1188
    return delta;
1189
}
1190
#endif
1191

    
1192
#ifndef _WIN32
1193

    
1194
/* Sets a specific flag */
1195
static int fcntl_setfl(int fd, int flag)
1196
{
1197
    int flags;
1198

    
1199
    flags = fcntl(fd, F_GETFL);
1200
    if (flags == -1)
1201
        return -errno;
1202

    
1203
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1204
        return -errno;
1205

    
1206
    return 0;
1207
}
1208

    
1209
#if defined(__linux__)
1210

    
1211
#define RTC_FREQ 1024
1212

    
1213
static void enable_sigio_timer(int fd)
1214
{
1215
    struct sigaction act;
1216

    
1217
    /* timer signal */
1218
    sigfillset(&act.sa_mask);
1219
    act.sa_flags = 0;
1220
    act.sa_handler = host_alarm_handler;
1221

    
1222
    sigaction(SIGIO, &act, NULL);
1223
    fcntl_setfl(fd, O_ASYNC);
1224
    fcntl(fd, F_SETOWN, getpid());
1225
}
1226

    
1227
static int hpet_start_timer(struct qemu_alarm_timer *t)
1228
{
1229
    struct hpet_info info;
1230
    int r, fd;
1231

    
1232
    fd = open("/dev/hpet", O_RDONLY);
1233
    if (fd < 0)
1234
        return -1;
1235

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

    
1245
    /* Check capabilities */
1246
    r = ioctl(fd, HPET_INFO, &info);
1247
    if (r < 0)
1248
        goto fail;
1249

    
1250
    /* Enable periodic mode */
1251
    r = ioctl(fd, HPET_EPI, 0);
1252
    if (info.hi_flags && (r < 0))
1253
        goto fail;
1254

    
1255
    /* Enable interrupt */
1256
    r = ioctl(fd, HPET_IE_ON, 0);
1257
    if (r < 0)
1258
        goto fail;
1259

    
1260
    enable_sigio_timer(fd);
1261
    t->priv = (void *)(long)fd;
1262

    
1263
    return 0;
1264
fail:
1265
    close(fd);
1266
    return -1;
1267
}
1268

    
1269
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1270
{
1271
    int fd = (long)t->priv;
1272

    
1273
    close(fd);
1274
}
1275

    
1276
static int rtc_start_timer(struct qemu_alarm_timer *t)
1277
{
1278
    int rtc_fd;
1279
    unsigned long current_rtc_freq = 0;
1280

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

    
1298
    enable_sigio_timer(rtc_fd);
1299

    
1300
    t->priv = (void *)(long)rtc_fd;
1301

    
1302
    return 0;
1303
}
1304

    
1305
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1306
{
1307
    int rtc_fd = (long)t->priv;
1308

    
1309
    close(rtc_fd);
1310
}
1311

    
1312
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1313
{
1314
    struct sigevent ev;
1315
    timer_t host_timer;
1316
    struct sigaction act;
1317

    
1318
    sigfillset(&act.sa_mask);
1319
    act.sa_flags = 0;
1320
    act.sa_handler = host_alarm_handler;
1321

    
1322
    sigaction(SIGALRM, &act, NULL);
1323

    
1324
    /* 
1325
     * Initialize ev struct to 0 to avoid valgrind complaining
1326
     * about uninitialized data in timer_create call
1327
     */
1328
    memset(&ev, 0, sizeof(ev));
1329
    ev.sigev_value.sival_int = 0;
1330
    ev.sigev_notify = SIGEV_SIGNAL;
1331
    ev.sigev_signo = SIGALRM;
1332

    
1333
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1334
        perror("timer_create");
1335

    
1336
        /* disable dynticks */
1337
        fprintf(stderr, "Dynamic Ticks disabled\n");
1338

    
1339
        return -1;
1340
    }
1341

    
1342
    t->priv = (void *)(long)host_timer;
1343

    
1344
    return 0;
1345
}
1346

    
1347
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1348
{
1349
    timer_t host_timer = (timer_t)(long)t->priv;
1350

    
1351
    timer_delete(host_timer);
1352
}
1353

    
1354
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1355
{
1356
    timer_t host_timer = (timer_t)(long)t->priv;
1357
    struct itimerspec timeout;
1358
    int64_t nearest_delta_us = INT64_MAX;
1359
    int64_t current_us;
1360

    
1361
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1362
                !active_timers[QEMU_TIMER_VIRTUAL])
1363
        return;
1364

    
1365
    nearest_delta_us = qemu_next_deadline_dyntick();
1366

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

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

    
1388
#endif /* defined(__linux__) */
1389

    
1390
static int unix_start_timer(struct qemu_alarm_timer *t)
1391
{
1392
    struct sigaction act;
1393
    struct itimerval itv;
1394
    int err;
1395

    
1396
    /* timer signal */
1397
    sigfillset(&act.sa_mask);
1398
    act.sa_flags = 0;
1399
    act.sa_handler = host_alarm_handler;
1400

    
1401
    sigaction(SIGALRM, &act, NULL);
1402

    
1403
    itv.it_interval.tv_sec = 0;
1404
    /* for i386 kernel 2.6 to get 1 ms */
1405
    itv.it_interval.tv_usec = 999;
1406
    itv.it_value.tv_sec = 0;
1407
    itv.it_value.tv_usec = 10 * 1000;
1408

    
1409
    err = setitimer(ITIMER_REAL, &itv, NULL);
1410
    if (err)
1411
        return -1;
1412

    
1413
    return 0;
1414
}
1415

    
1416
static void unix_stop_timer(struct qemu_alarm_timer *t)
1417
{
1418
    struct itimerval itv;
1419

    
1420
    memset(&itv, 0, sizeof(itv));
1421
    setitimer(ITIMER_REAL, &itv, NULL);
1422
}
1423

    
1424
#endif /* !defined(_WIN32) */
1425

    
1426

    
1427
#ifdef _WIN32
1428

    
1429
static int win32_start_timer(struct qemu_alarm_timer *t)
1430
{
1431
    TIMECAPS tc;
1432
    struct qemu_alarm_win32 *data = t->priv;
1433
    UINT flags;
1434

    
1435
    memset(&tc, 0, sizeof(tc));
1436
    timeGetDevCaps(&tc, sizeof(tc));
1437

    
1438
    if (data->period < tc.wPeriodMin)
1439
        data->period = tc.wPeriodMin;
1440

    
1441
    timeBeginPeriod(data->period);
1442

    
1443
    flags = TIME_CALLBACK_FUNCTION;
1444
    if (alarm_has_dynticks(t))
1445
        flags |= TIME_ONESHOT;
1446
    else
1447
        flags |= TIME_PERIODIC;
1448

    
1449
    data->timerId = timeSetEvent(1,         // interval (ms)
1450
                        data->period,       // resolution
1451
                        host_alarm_handler, // function
1452
                        (DWORD)t,           // parameter
1453
                        flags);
1454

    
1455
    if (!data->timerId) {
1456
        perror("Failed to initialize win32 alarm timer");
1457
        timeEndPeriod(data->period);
1458
        return -1;
1459
    }
1460

    
1461
    return 0;
1462
}
1463

    
1464
static void win32_stop_timer(struct qemu_alarm_timer *t)
1465
{
1466
    struct qemu_alarm_win32 *data = t->priv;
1467

    
1468
    timeKillEvent(data->timerId);
1469
    timeEndPeriod(data->period);
1470
}
1471

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

    
1477
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1478
                !active_timers[QEMU_TIMER_VIRTUAL])
1479
        return;
1480

    
1481
    nearest_delta_us = qemu_next_deadline_dyntick();
1482
    nearest_delta_us /= 1000;
1483

    
1484
    timeKillEvent(data->timerId);
1485

    
1486
    data->timerId = timeSetEvent(1,
1487
                        data->period,
1488
                        host_alarm_handler,
1489
                        (DWORD)t,
1490
                        TIME_ONESHOT | TIME_PERIODIC);
1491

    
1492
    if (!data->timerId) {
1493
        perror("Failed to re-arm win32 alarm timer");
1494

    
1495
        timeEndPeriod(data->period);
1496
        exit(1);
1497
    }
1498
}
1499

    
1500
#endif /* _WIN32 */
1501

    
1502
static int init_timer_alarm(void)
1503
{
1504
    struct qemu_alarm_timer *t = NULL;
1505
    int i, err = -1;
1506

    
1507
    for (i = 0; alarm_timers[i].name; i++) {
1508
        t = &alarm_timers[i];
1509

    
1510
        err = t->start(t);
1511
        if (!err)
1512
            break;
1513
    }
1514

    
1515
    if (err) {
1516
        err = -ENOENT;
1517
        goto fail;
1518
    }
1519

    
1520
    alarm_timer = t;
1521

    
1522
    return 0;
1523

    
1524
fail:
1525
    return err;
1526
}
1527

    
1528
static void quit_timers(void)
1529
{
1530
    alarm_timer->stop(alarm_timer);
1531
    alarm_timer = NULL;
1532
}
1533

    
1534
/***********************************************************/
1535
/* host time/date access */
1536
void qemu_get_timedate(struct tm *tm, int offset)
1537
{
1538
    time_t ti;
1539
    struct tm *ret;
1540

    
1541
    time(&ti);
1542
    ti += offset;
1543
    if (rtc_date_offset == -1) {
1544
        if (rtc_utc)
1545
            ret = gmtime(&ti);
1546
        else
1547
            ret = localtime(&ti);
1548
    } else {
1549
        ti -= rtc_date_offset;
1550
        ret = gmtime(&ti);
1551
    }
1552

    
1553
    memcpy(tm, ret, sizeof(struct tm));
1554
}
1555

    
1556
int qemu_timedate_diff(struct tm *tm)
1557
{
1558
    time_t seconds;
1559

    
1560
    if (rtc_date_offset == -1)
1561
        if (rtc_utc)
1562
            seconds = mktimegm(tm);
1563
        else
1564
            seconds = mktime(tm);
1565
    else
1566
        seconds = mktimegm(tm) + rtc_date_offset;
1567

    
1568
    return seconds - time(NULL);
1569
}
1570

    
1571
#ifdef _WIN32
1572
static void socket_cleanup(void)
1573
{
1574
    WSACleanup();
1575
}
1576

    
1577
static int socket_init(void)
1578
{
1579
    WSADATA Data;
1580
    int ret, err;
1581

    
1582
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1583
    if (ret != 0) {
1584
        err = WSAGetLastError();
1585
        fprintf(stderr, "WSAStartup: %d\n", err);
1586
        return -1;
1587
    }
1588
    atexit(socket_cleanup);
1589
    return 0;
1590
}
1591
#endif
1592

    
1593
/***********************************************************/
1594
/* Bluetooth support */
1595
static int nb_hcis;
1596
static int cur_hci;
1597
static struct HCIInfo *hci_table[MAX_NICS];
1598

    
1599
static struct bt_vlan_s {
1600
    struct bt_scatternet_s net;
1601
    int id;
1602
    struct bt_vlan_s *next;
1603
} *first_bt_vlan;
1604

    
1605
/* find or alloc a new bluetooth "VLAN" */
1606
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1607
{
1608
    struct bt_vlan_s **pvlan, *vlan;
1609
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1610
        if (vlan->id == id)
1611
            return &vlan->net;
1612
    }
1613
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1614
    vlan->id = id;
1615
    pvlan = &first_bt_vlan;
1616
    while (*pvlan != NULL)
1617
        pvlan = &(*pvlan)->next;
1618
    *pvlan = vlan;
1619
    return &vlan->net;
1620
}
1621

    
1622
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1623
{
1624
}
1625

    
1626
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1627
{
1628
    return -ENOTSUP;
1629
}
1630

    
1631
static struct HCIInfo null_hci = {
1632
    .cmd_send = null_hci_send,
1633
    .sco_send = null_hci_send,
1634
    .acl_send = null_hci_send,
1635
    .bdaddr_set = null_hci_addr_set,
1636
};
1637

    
1638
struct HCIInfo *qemu_next_hci(void)
1639
{
1640
    if (cur_hci == nb_hcis)
1641
        return &null_hci;
1642

    
1643
    return hci_table[cur_hci++];
1644
}
1645

    
1646
static struct HCIInfo *hci_init(const char *str)
1647
{
1648
    char *endp;
1649
    struct bt_scatternet_s *vlan = 0;
1650

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

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

    
1673
    return 0;
1674
}
1675

    
1676
static int bt_hci_parse(const char *str)
1677
{
1678
    struct HCIInfo *hci;
1679
    bdaddr_t bdaddr;
1680

    
1681
    if (nb_hcis >= MAX_NICS) {
1682
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1683
        return -1;
1684
    }
1685

    
1686
    hci = hci_init(str);
1687
    if (!hci)
1688
        return -1;
1689

    
1690
    bdaddr.b[0] = 0x52;
1691
    bdaddr.b[1] = 0x54;
1692
    bdaddr.b[2] = 0x00;
1693
    bdaddr.b[3] = 0x12;
1694
    bdaddr.b[4] = 0x34;
1695
    bdaddr.b[5] = 0x56 + nb_hcis;
1696
    hci->bdaddr_set(hci, bdaddr.b);
1697

    
1698
    hci_table[nb_hcis++] = hci;
1699

    
1700
    return 0;
1701
}
1702

    
1703
static void bt_vhci_add(int vlan_id)
1704
{
1705
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1706

    
1707
    if (!vlan->slave)
1708
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1709
                        "an empty scatternet %i\n", vlan_id);
1710

    
1711
    bt_vhci_init(bt_new_hci(vlan));
1712
}
1713

    
1714
static struct bt_device_s *bt_device_add(const char *opt)
1715
{
1716
    struct bt_scatternet_s *vlan;
1717
    int vlan_id = 0;
1718
    char *endp = strstr(opt, ",vlan=");
1719
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1720
    char devname[10];
1721

    
1722
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1723

    
1724
    if (endp) {
1725
        vlan_id = strtol(endp + 6, &endp, 0);
1726
        if (*endp) {
1727
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1728
            return 0;
1729
        }
1730
    }
1731

    
1732
    vlan = qemu_find_bt_vlan(vlan_id);
1733

    
1734
    if (!vlan->slave)
1735
        fprintf(stderr, "qemu: warning: adding a slave device to "
1736
                        "an empty scatternet %i\n", vlan_id);
1737

    
1738
    if (!strcmp(devname, "keyboard"))
1739
        return bt_keyboard_init(vlan);
1740

    
1741
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1742
    return 0;
1743
}
1744

    
1745
static int bt_parse(const char *opt)
1746
{
1747
    const char *endp, *p;
1748
    int vlan;
1749

    
1750
    if (strstart(opt, "hci", &endp)) {
1751
        if (!*endp || *endp == ',') {
1752
            if (*endp)
1753
                if (!strstart(endp, ",vlan=", 0))
1754
                    opt = endp + 1;
1755

    
1756
            return bt_hci_parse(opt);
1757
       }
1758
    } else if (strstart(opt, "vhci", &endp)) {
1759
        if (!*endp || *endp == ',') {
1760
            if (*endp) {
1761
                if (strstart(endp, ",vlan=", &p)) {
1762
                    vlan = strtol(p, (char **) &endp, 0);
1763
                    if (*endp) {
1764
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1765
                        return 1;
1766
                    }
1767
                } else {
1768
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1769
                    return 1;
1770
                }
1771
            } else
1772
                vlan = 0;
1773

    
1774
            bt_vhci_add(vlan);
1775
            return 0;
1776
        }
1777
    } else if (strstart(opt, "device:", &endp))
1778
        return !bt_device_add(endp);
1779

    
1780
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1781
    return 1;
1782
}
1783

    
1784
/***********************************************************/
1785
/* QEMU Block devices */
1786

    
1787
#define HD_ALIAS "index=%d,media=disk"
1788
#define CDROM_ALIAS "index=2,media=cdrom"
1789
#define FD_ALIAS "index=%d,if=floppy"
1790
#define PFLASH_ALIAS "if=pflash"
1791
#define MTD_ALIAS "if=mtd"
1792
#define SD_ALIAS "index=0,if=sd"
1793

    
1794
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1795
{
1796
    va_list ap;
1797
    char optstr[1024];
1798
    QemuOpts *opts;
1799

    
1800
    va_start(ap, fmt);
1801
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1802
    va_end(ap);
1803

    
1804
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1805
    if (!opts) {
1806
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1807
                __FUNCTION__, optstr);
1808
        return NULL;
1809
    }
1810
    if (file)
1811
        qemu_opt_set(opts, "file", file);
1812
    return opts;
1813
}
1814

    
1815
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1816
{
1817
    DriveInfo *dinfo;
1818

    
1819
    /* seek interface, bus and unit */
1820

    
1821
    TAILQ_FOREACH(dinfo, &drives, next) {
1822
        if (dinfo->type == type &&
1823
            dinfo->bus == bus &&
1824
            dinfo->unit == unit)
1825
            return dinfo;
1826
    }
1827

    
1828
    return NULL;
1829
}
1830

    
1831
DriveInfo *drive_get_by_id(const char *id)
1832
{
1833
    DriveInfo *dinfo;
1834

    
1835
    TAILQ_FOREACH(dinfo, &drives, next) {
1836
        if (strcmp(id, dinfo->id))
1837
            continue;
1838
        return dinfo;
1839
    }
1840
    return NULL;
1841
}
1842

    
1843
int drive_get_max_bus(BlockInterfaceType type)
1844
{
1845
    int max_bus;
1846
    DriveInfo *dinfo;
1847

    
1848
    max_bus = -1;
1849
    TAILQ_FOREACH(dinfo, &drives, next) {
1850
        if(dinfo->type == type &&
1851
           dinfo->bus > max_bus)
1852
            max_bus = dinfo->bus;
1853
    }
1854
    return max_bus;
1855
}
1856

    
1857
const char *drive_get_serial(BlockDriverState *bdrv)
1858
{
1859
    DriveInfo *dinfo;
1860

    
1861
    TAILQ_FOREACH(dinfo, &drives, next) {
1862
        if (dinfo->bdrv == bdrv)
1863
            return dinfo->serial;
1864
    }
1865

    
1866
    return "\0";
1867
}
1868

    
1869
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1870
{
1871
    DriveInfo *dinfo;
1872

    
1873
    TAILQ_FOREACH(dinfo, &drives, next) {
1874
        if (dinfo->bdrv == bdrv)
1875
            return dinfo->onerror;
1876
    }
1877

    
1878
    return BLOCK_ERR_STOP_ENOSPC;
1879
}
1880

    
1881
static void bdrv_format_print(void *opaque, const char *name)
1882
{
1883
    fprintf(stderr, " %s", name);
1884
}
1885

    
1886
void drive_uninit(BlockDriverState *bdrv)
1887
{
1888
    DriveInfo *dinfo;
1889

    
1890
    TAILQ_FOREACH(dinfo, &drives, next) {
1891
        if (dinfo->bdrv != bdrv)
1892
            continue;
1893
        qemu_opts_del(dinfo->opts);
1894
        TAILQ_REMOVE(&drives, dinfo, next);
1895
        qemu_free(dinfo);
1896
        break;
1897
    }
1898
}
1899

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

    
1923
    *fatal_error = 1;
1924

    
1925
    translation = BIOS_ATA_TRANSLATION_AUTO;
1926
    cache = 1;
1927

    
1928
    if (machine->use_scsi) {
1929
        type = IF_SCSI;
1930
        max_devs = MAX_SCSI_DEVS;
1931
        pstrcpy(devname, sizeof(devname), "scsi");
1932
    } else {
1933
        type = IF_IDE;
1934
        max_devs = MAX_IDE_DEVS;
1935
        pstrcpy(devname, sizeof(devname), "ide");
1936
    }
1937
    media = MEDIA_DISK;
1938

    
1939
    /* extract parameters */
1940
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
1941
    unit_id = qemu_opt_get_number(opts, "unit", -1);
1942
    index   = qemu_opt_get_number(opts, "index", -1);
1943

    
1944
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
1945
    heads = qemu_opt_get_number(opts, "heads", 0);
1946
    secs  = qemu_opt_get_number(opts, "secs", 0);
1947

    
1948
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
1949

    
1950
    file = qemu_opt_get(opts, "file");
1951
    serial = qemu_opt_get(opts, "serial");
1952

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

    
1988
    if (cyls || heads || secs) {
1989
        if (cyls < 1 || cyls > 16383) {
1990
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
1991
            return NULL;
1992
        }
1993
        if (heads < 1 || heads > 16) {
1994
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
1995
            return NULL;
1996
        }
1997
        if (secs < 1 || secs > 63) {
1998
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
1999
            return NULL;
2000
        }
2001
    }
2002

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

    
2022
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2023
        if (!strcmp(buf, "disk")) {
2024
            media = MEDIA_DISK;
2025
        } else if (!strcmp(buf, "cdrom")) {
2026
            if (cyls || secs || heads) {
2027
                fprintf(stderr,
2028
                        "qemu: '%s' invalid physical CHS format\n", buf);
2029
                return NULL;
2030
            }
2031
            media = MEDIA_CDROM;
2032
        } else {
2033
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2034
            return NULL;
2035
        }
2036
    }
2037

    
2038
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2039
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2040
            cache = 0;
2041
        else if (!strcmp(buf, "writethrough"))
2042
            cache = 1;
2043
        else if (!strcmp(buf, "writeback"))
2044
            cache = 2;
2045
        else {
2046
           fprintf(stderr, "qemu: invalid cache option\n");
2047
           return NULL;
2048
        }
2049
    }
2050

    
2051
#ifdef CONFIG_LINUX_AIO
2052
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2053
        if (!strcmp(buf, "threads"))
2054
            aio = 0;
2055
        else if (!strcmp(buf, "native"))
2056
            aio = 1;
2057
        else {
2058
           fprintf(stderr, "qemu: invalid aio option\n");
2059
           return NULL;
2060
        }
2061
    }
2062
#endif
2063

    
2064
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2065
       if (strcmp(buf, "?") == 0) {
2066
            fprintf(stderr, "qemu: Supported formats:");
2067
            bdrv_iterate_format(bdrv_format_print, NULL);
2068
            fprintf(stderr, "\n");
2069
            return NULL;
2070
        }
2071
        drv = bdrv_find_format(buf);
2072
        if (!drv) {
2073
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2074
            return NULL;
2075
        }
2076
    }
2077

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

    
2098
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2099
        if (type != IF_VIRTIO) {
2100
            fprintf(stderr, "addr is not supported\n");
2101
            return NULL;
2102
        }
2103
    }
2104

    
2105
    /* compute bus and unit according index */
2106

    
2107
    if (index != -1) {
2108
        if (bus_id != 0 || unit_id != -1) {
2109
            fprintf(stderr,
2110
                    "qemu: index cannot be used with bus and unit\n");
2111
            return NULL;
2112
        }
2113
        if (max_devs == 0)
2114
        {
2115
            unit_id = index;
2116
            bus_id = 0;
2117
        } else {
2118
            unit_id = index % max_devs;
2119
            bus_id = index / max_devs;
2120
        }
2121
    }
2122

    
2123
    /* if user doesn't specify a unit_id,
2124
     * try to find the first free
2125
     */
2126

    
2127
    if (unit_id == -1) {
2128
       unit_id = 0;
2129
       while (drive_get(type, bus_id, unit_id) != NULL) {
2130
           unit_id++;
2131
           if (max_devs && unit_id >= max_devs) {
2132
               unit_id -= max_devs;
2133
               bus_id++;
2134
           }
2135
       }
2136
    }
2137

    
2138
    /* check unit id */
2139

    
2140
    if (max_devs && unit_id >= max_devs) {
2141
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2142
                unit_id, max_devs - 1);
2143
        return NULL;
2144
    }
2145

    
2146
    /*
2147
     * ignore multiple definitions
2148
     */
2149

    
2150
    if (drive_get(type, bus_id, unit_id) != NULL) {
2151
        *fatal_error = 0;
2152
        return NULL;
2153
    }
2154

    
2155
    /* init */
2156

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

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

    
2234
    if (aio == 1) {
2235
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2236
    } else {
2237
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2238
    }
2239

    
2240
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2241
        fprintf(stderr, "qemu: could not open disk image %s\n",
2242
                        file);
2243
        return NULL;
2244
    }
2245

    
2246
    if (bdrv_key_required(dinfo->bdrv))
2247
        autostart = 0;
2248
    *fatal_error = 0;
2249
    return dinfo;
2250
}
2251

    
2252
static int drive_init_func(QemuOpts *opts, void *opaque)
2253
{
2254
    QEMUMachine *machine = opaque;
2255
    int fatal_error = 0;
2256

    
2257
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2258
        if (fatal_error)
2259
            return 1;
2260
    }
2261
    return 0;
2262
}
2263

    
2264
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2265
{
2266
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2267
        qemu_opt_set(opts, "snapshot", "on");
2268
    }
2269
    return 0;
2270
}
2271

    
2272
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2273
{
2274
    boot_set_handler = func;
2275
    boot_set_opaque = opaque;
2276
}
2277

    
2278
int qemu_boot_set(const char *boot_devices)
2279
{
2280
    if (!boot_set_handler) {
2281
        return -EINVAL;
2282
    }
2283
    return boot_set_handler(boot_set_opaque, boot_devices);
2284
}
2285

    
2286
static int parse_bootdevices(char *devices)
2287
{
2288
    /* We just do some generic consistency checks */
2289
    const char *p;
2290
    int bitmap = 0;
2291

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

    
2315
static void restore_boot_devices(void *opaque)
2316
{
2317
    char *standard_boot_devices = opaque;
2318

    
2319
    qemu_boot_set(standard_boot_devices);
2320

    
2321
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2322
    qemu_free(standard_boot_devices);
2323
}
2324

    
2325
static void numa_add(const char *optarg)
2326
{
2327
    char option[128];
2328
    char *endptr;
2329
    unsigned long long value, endvalue;
2330
    int nodenr;
2331

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

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

    
2381
static void smp_parse(const char *optarg)
2382
{
2383
    int smp, sockets = 0, threads = 0, cores = 0;
2384
    char *endptr;
2385
    char option[128];
2386

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

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

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

    
2434
static USBPort *used_usb_ports;
2435
static USBPort *free_usb_ports;
2436

    
2437
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2438
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2439
                            usb_attachfn attach)
2440
{
2441
    port->opaque = opaque;
2442
    port->index = index;
2443
    port->attach = attach;
2444
    port->next = free_usb_ports;
2445
    free_usb_ports = port;
2446
}
2447

    
2448
int usb_device_add_dev(USBDevice *dev)
2449
{
2450
    USBPort *port;
2451

    
2452
    /* Find a USB port to add the device to.  */
2453
    port = free_usb_ports;
2454
    if (!port->next) {
2455
        USBDevice *hub;
2456

    
2457
        /* Create a new hub and chain it on.  */
2458
        free_usb_ports = NULL;
2459
        port->next = used_usb_ports;
2460
        used_usb_ports = port;
2461

    
2462
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2463
        usb_attach(port, hub);
2464
        port = free_usb_ports;
2465
    }
2466

    
2467
    free_usb_ports = port->next;
2468
    port->next = used_usb_ports;
2469
    used_usb_ports = port;
2470
    usb_attach(port, dev);
2471
    return 0;
2472
}
2473

    
2474
static void usb_msd_password_cb(void *opaque, int err)
2475
{
2476
    USBDevice *dev = opaque;
2477

    
2478
    if (!err)
2479
        usb_device_add_dev(dev);
2480
    else
2481
        dev->handle_destroy(dev);
2482
}
2483

    
2484
static int usb_device_add(const char *devname, int is_hotplug)
2485
{
2486
    const char *p;
2487
    USBDevice *dev;
2488

    
2489
    if (!free_usb_ports)
2490
        return -1;
2491

    
2492
    if (strstart(devname, "host:", &p)) {
2493
        dev = usb_host_device_open(p);
2494
    } else if (!strcmp(devname, "mouse")) {
2495
        dev = usb_mouse_init();
2496
    } else if (!strcmp(devname, "tablet")) {
2497
        dev = usb_tablet_init();
2498
    } else if (!strcmp(devname, "keyboard")) {
2499
        dev = usb_keyboard_init();
2500
    } else if (strstart(devname, "disk:", &p)) {
2501
        BlockDriverState *bs;
2502

    
2503
        dev = usb_msd_init(p);
2504
        if (!dev)
2505
            return -1;
2506
        bs = usb_msd_get_bdrv(dev);
2507
        if (bdrv_key_required(bs)) {
2508
            autostart = 0;
2509
            if (is_hotplug) {
2510
                monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2511
                                            dev);
2512
                return 0;
2513
            }
2514
        }
2515
    } else if (!strcmp(devname, "wacom-tablet")) {
2516
        dev = usb_wacom_init();
2517
    } else if (strstart(devname, "serial:", &p)) {
2518
        dev = usb_serial_init(p);
2519
#ifdef CONFIG_BRLAPI
2520
    } else if (!strcmp(devname, "braille")) {
2521
        dev = usb_baum_init();
2522
#endif
2523
    } else if (strstart(devname, "net:", &p)) {
2524
        int nic = nb_nics;
2525

    
2526
        if (net_client_init(NULL, "nic", p) < 0)
2527
            return -1;
2528
        nd_table[nic].model = "usb";
2529
        dev = usb_net_init(&nd_table[nic]);
2530
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2531
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2532
                        bt_new_hci(qemu_find_bt_vlan(0)));
2533
    } else {
2534
        return -1;
2535
    }
2536
    if (!dev)
2537
        return -1;
2538

    
2539
    return usb_device_add_dev(dev);
2540
}
2541

    
2542
int usb_device_del_addr(int bus_num, int addr)
2543
{
2544
    USBPort *port;
2545
    USBPort **lastp;
2546
    USBDevice *dev;
2547

    
2548
    if (!used_usb_ports)
2549
        return -1;
2550

    
2551
    if (bus_num != 0)
2552
        return -1;
2553

    
2554
    lastp = &used_usb_ports;
2555
    port = used_usb_ports;
2556
    while (port && port->dev->addr != addr) {
2557
        lastp = &port->next;
2558
        port = port->next;
2559
    }
2560

    
2561
    if (!port)
2562
        return -1;
2563

    
2564
    dev = port->dev;
2565
    *lastp = port->next;
2566
    usb_attach(port, NULL);
2567
    dev->handle_destroy(dev);
2568
    port->next = free_usb_ports;
2569
    free_usb_ports = port;
2570
    return 0;
2571
}
2572

    
2573
static int usb_device_del(const char *devname)
2574
{
2575
    int bus_num, addr;
2576
    const char *p;
2577

    
2578
    if (strstart(devname, "host:", &p))
2579
        return usb_host_device_close(p);
2580

    
2581
    if (!used_usb_ports)
2582
        return -1;
2583

    
2584
    p = strchr(devname, '.');
2585
    if (!p)
2586
        return -1;
2587
    bus_num = strtoul(devname, NULL, 0);
2588
    addr = strtoul(p + 1, NULL, 0);
2589

    
2590
    return usb_device_del_addr(bus_num, addr);
2591
}
2592

    
2593
static int usb_parse(const char *cmdline)
2594
{
2595
    return usb_device_add(cmdline, 0);
2596
}
2597

    
2598
void do_usb_add(Monitor *mon, const char *devname)
2599
{
2600
    usb_device_add(devname, 1);
2601
}
2602

    
2603
void do_usb_del(Monitor *mon, const char *devname)
2604
{
2605
    usb_device_del(devname);
2606
}
2607

    
2608
void usb_info(Monitor *mon)
2609
{
2610
    USBDevice *dev;
2611
    USBPort *port;
2612
    const char *speed_str;
2613

    
2614
    if (!usb_enabled) {
2615
        monitor_printf(mon, "USB support not enabled\n");
2616
        return;
2617
    }
2618

    
2619
    for (port = used_usb_ports; port; port = port->next) {
2620
        dev = port->dev;
2621
        if (!dev)
2622
            continue;
2623
        switch(dev->speed) {
2624
        case USB_SPEED_LOW:
2625
            speed_str = "1.5";
2626
            break;
2627
        case USB_SPEED_FULL:
2628
            speed_str = "12";
2629
            break;
2630
        case USB_SPEED_HIGH:
2631
            speed_str = "480";
2632
            break;
2633
        default:
2634
            speed_str = "?";
2635
            break;
2636
        }
2637
        monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
2638
                       0, dev->addr, speed_str, dev->devname);
2639
    }
2640
}
2641

    
2642
/***********************************************************/
2643
/* PCMCIA/Cardbus */
2644

    
2645
static struct pcmcia_socket_entry_s {
2646
    PCMCIASocket *socket;
2647
    struct pcmcia_socket_entry_s *next;
2648
} *pcmcia_sockets = 0;
2649

    
2650
void pcmcia_socket_register(PCMCIASocket *socket)
2651
{
2652
    struct pcmcia_socket_entry_s *entry;
2653

    
2654
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2655
    entry->socket = socket;
2656
    entry->next = pcmcia_sockets;
2657
    pcmcia_sockets = entry;
2658
}
2659

    
2660
void pcmcia_socket_unregister(PCMCIASocket *socket)
2661
{
2662
    struct pcmcia_socket_entry_s *entry, **ptr;
2663

    
2664
    ptr = &pcmcia_sockets;
2665
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2666
        if (entry->socket == socket) {
2667
            *ptr = entry->next;
2668
            qemu_free(entry);
2669
        }
2670
}
2671

    
2672
void pcmcia_info(Monitor *mon)
2673
{
2674
    struct pcmcia_socket_entry_s *iter;
2675

    
2676
    if (!pcmcia_sockets)
2677
        monitor_printf(mon, "No PCMCIA sockets\n");
2678

    
2679
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2680
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2681
                       iter->socket->attached ? iter->socket->card_string :
2682
                       "Empty");
2683
}
2684

    
2685
/***********************************************************/
2686
/* register display */
2687

    
2688
struct DisplayAllocator default_allocator = {
2689
    defaultallocator_create_displaysurface,
2690
    defaultallocator_resize_displaysurface,
2691
    defaultallocator_free_displaysurface
2692
};
2693

    
2694
void register_displaystate(DisplayState *ds)
2695
{
2696
    DisplayState **s;
2697
    s = &display_state;
2698
    while (*s != NULL)
2699
        s = &(*s)->next;
2700
    ds->next = NULL;
2701
    *s = ds;
2702
}
2703

    
2704
DisplayState *get_displaystate(void)
2705
{
2706
    return display_state;
2707
}
2708

    
2709
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2710
{
2711
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2712
    return ds->allocator;
2713
}
2714

    
2715
/* dumb display */
2716

    
2717
static void dumb_display_init(void)
2718
{
2719
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2720
    ds->allocator = &default_allocator;
2721
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2722
    register_displaystate(ds);
2723
}
2724

    
2725
/***********************************************************/
2726
/* I/O handling */
2727

    
2728
typedef struct IOHandlerRecord {
2729
    int fd;
2730
    IOCanRWHandler *fd_read_poll;
2731
    IOHandler *fd_read;
2732
    IOHandler *fd_write;
2733
    int deleted;
2734
    void *opaque;
2735
    /* temporary data */
2736
    struct pollfd *ufd;
2737
    struct IOHandlerRecord *next;
2738
} IOHandlerRecord;
2739

    
2740
static IOHandlerRecord *first_io_handler;
2741

    
2742
/* XXX: fd_read_poll should be suppressed, but an API change is
2743
   necessary in the character devices to suppress fd_can_read(). */
2744
int qemu_set_fd_handler2(int fd,
2745
                         IOCanRWHandler *fd_read_poll,
2746
                         IOHandler *fd_read,
2747
                         IOHandler *fd_write,
2748
                         void *opaque)
2749
{
2750
    IOHandlerRecord **pioh, *ioh;
2751

    
2752
    if (!fd_read && !fd_write) {
2753
        pioh = &first_io_handler;
2754
        for(;;) {
2755
            ioh = *pioh;
2756
            if (ioh == NULL)
2757
                break;
2758
            if (ioh->fd == fd) {
2759
                ioh->deleted = 1;
2760
                break;
2761
            }
2762
            pioh = &ioh->next;
2763
        }
2764
    } else {
2765
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2766
            if (ioh->fd == fd)
2767
                goto found;
2768
        }
2769
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2770
        ioh->next = first_io_handler;
2771
        first_io_handler = ioh;
2772
    found:
2773
        ioh->fd = fd;
2774
        ioh->fd_read_poll = fd_read_poll;
2775
        ioh->fd_read = fd_read;
2776
        ioh->fd_write = fd_write;
2777
        ioh->opaque = opaque;
2778
        ioh->deleted = 0;
2779
    }
2780
    return 0;
2781
}
2782

    
2783
int qemu_set_fd_handler(int fd,
2784
                        IOHandler *fd_read,
2785
                        IOHandler *fd_write,
2786
                        void *opaque)
2787
{
2788
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2789
}
2790

    
2791
#ifdef _WIN32
2792
/***********************************************************/
2793
/* Polling handling */
2794

    
2795
typedef struct PollingEntry {
2796
    PollingFunc *func;
2797
    void *opaque;
2798
    struct PollingEntry *next;
2799
} PollingEntry;
2800

    
2801
static PollingEntry *first_polling_entry;
2802

    
2803
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2804
{
2805
    PollingEntry **ppe, *pe;
2806
    pe = qemu_mallocz(sizeof(PollingEntry));
2807
    pe->func = func;
2808
    pe->opaque = opaque;
2809
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2810
    *ppe = pe;
2811
    return 0;
2812
}
2813

    
2814
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2815
{
2816
    PollingEntry **ppe, *pe;
2817
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2818
        pe = *ppe;
2819
        if (pe->func == func && pe->opaque == opaque) {
2820
            *ppe = pe->next;
2821
            qemu_free(pe);
2822
            break;
2823
        }
2824
    }
2825
}
2826

    
2827
/***********************************************************/
2828
/* Wait objects support */
2829
typedef struct WaitObjects {
2830
    int num;
2831
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2832
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2833
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2834
} WaitObjects;
2835

    
2836
static WaitObjects wait_objects = {0};
2837

    
2838
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2839
{
2840
    WaitObjects *w = &wait_objects;
2841

    
2842
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2843
        return -1;
2844
    w->events[w->num] = handle;
2845
    w->func[w->num] = func;
2846
    w->opaque[w->num] = opaque;
2847
    w->num++;
2848
    return 0;
2849
}
2850

    
2851
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2852
{
2853
    int i, found;
2854
    WaitObjects *w = &wait_objects;
2855

    
2856
    found = 0;
2857
    for (i = 0; i < w->num; i++) {
2858
        if (w->events[i] == handle)
2859
            found = 1;
2860
        if (found) {
2861
            w->events[i] = w->events[i + 1];
2862
            w->func[i] = w->func[i + 1];
2863
            w->opaque[i] = w->opaque[i + 1];
2864
        }
2865
    }
2866
    if (found)
2867
        w->num--;
2868
}
2869
#endif
2870

    
2871
/***********************************************************/
2872
/* ram save/restore */
2873

    
2874
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2875
{
2876
    int v;
2877

    
2878
    v = qemu_get_byte(f);
2879
    switch(v) {
2880
    case 0:
2881
        if (qemu_get_buffer(f, buf, len) != len)
2882
            return -EIO;
2883
        break;
2884
    case 1:
2885
        v = qemu_get_byte(f);
2886
        memset(buf, v, len);
2887
        break;
2888
    default:
2889
        return -EINVAL;
2890
    }
2891

    
2892
    if (qemu_file_has_error(f))
2893
        return -EIO;
2894

    
2895
    return 0;
2896
}
2897

    
2898
static int ram_load_v1(QEMUFile *f, void *opaque)
2899
{
2900
    int ret;
2901
    ram_addr_t i;
2902

    
2903
    if (qemu_get_be32(f) != last_ram_offset)
2904
        return -EINVAL;
2905
    for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2906
        ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2907
        if (ret)
2908
            return ret;
2909
    }
2910
    return 0;
2911
}
2912

    
2913
#define BDRV_HASH_BLOCK_SIZE 1024
2914
#define IOBUF_SIZE 4096
2915
#define RAM_CBLOCK_MAGIC 0xfabe
2916

    
2917
typedef struct RamDecompressState {
2918
    z_stream zstream;
2919
    QEMUFile *f;
2920
    uint8_t buf[IOBUF_SIZE];
2921
} RamDecompressState;
2922

    
2923
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2924
{
2925
    int ret;
2926
    memset(s, 0, sizeof(*s));
2927
    s->f = f;
2928
    ret = inflateInit(&s->zstream);
2929
    if (ret != Z_OK)
2930
        return -1;
2931
    return 0;
2932
}
2933

    
2934
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2935
{
2936
    int ret, clen;
2937

    
2938
    s->zstream.avail_out = len;
2939
    s->zstream.next_out = buf;
2940
    while (s->zstream.avail_out > 0) {
2941
        if (s->zstream.avail_in == 0) {
2942
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
2943
                return -1;
2944
            clen = qemu_get_be16(s->f);
2945
            if (clen > IOBUF_SIZE)
2946
                return -1;
2947
            qemu_get_buffer(s->f, s->buf, clen);
2948
            s->zstream.avail_in = clen;
2949
            s->zstream.next_in = s->buf;
2950
        }
2951
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
2952
        if (ret != Z_OK && ret != Z_STREAM_END) {
2953
            return -1;
2954
        }
2955
    }
2956
    return 0;
2957
}
2958

    
2959
static void ram_decompress_close(RamDecompressState *s)
2960
{
2961
    inflateEnd(&s->zstream);
2962
}
2963

    
2964
#define RAM_SAVE_FLAG_FULL        0x01
2965
#define RAM_SAVE_FLAG_COMPRESS        0x02
2966
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2967
#define RAM_SAVE_FLAG_PAGE        0x08
2968
#define RAM_SAVE_FLAG_EOS        0x10
2969

    
2970
static int is_dup_page(uint8_t *page, uint8_t ch)
2971
{
2972
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2973
    uint32_t *array = (uint32_t *)page;
2974
    int i;
2975

    
2976
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2977
        if (array[i] != val)
2978
            return 0;
2979
    }
2980

    
2981
    return 1;
2982
}
2983

    
2984
static int ram_save_block(QEMUFile *f)
2985
{
2986
    static ram_addr_t current_addr = 0;
2987
    ram_addr_t saved_addr = current_addr;
2988
    ram_addr_t addr = 0;
2989
    int found = 0;
2990

    
2991
    while (addr < last_ram_offset) {
2992
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2993
            uint8_t *p;
2994

    
2995
            cpu_physical_memory_reset_dirty(current_addr,
2996
                                            current_addr + TARGET_PAGE_SIZE,
2997
                                            MIGRATION_DIRTY_FLAG);
2998

    
2999
            p = qemu_get_ram_ptr(current_addr);
3000

    
3001
            if (is_dup_page(p, *p)) {
3002
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3003
                qemu_put_byte(f, *p);
3004
            } else {
3005
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3006
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3007
            }
3008

    
3009
            found = 1;
3010
            break;
3011
        }
3012
        addr += TARGET_PAGE_SIZE;
3013
        current_addr = (saved_addr + addr) % last_ram_offset;
3014
    }
3015

    
3016
    return found;
3017
}
3018

    
3019
static uint64_t bytes_transferred = 0;
3020

    
3021
static ram_addr_t ram_save_remaining(void)
3022
{
3023
    ram_addr_t addr;
3024
    ram_addr_t count = 0;
3025

    
3026
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3027
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3028
            count++;
3029
    }
3030

    
3031
    return count;
3032
}
3033

    
3034
uint64_t ram_bytes_remaining(void)
3035
{
3036
    return ram_save_remaining() * TARGET_PAGE_SIZE;
3037
}
3038

    
3039
uint64_t ram_bytes_transferred(void)
3040
{
3041
    return bytes_transferred;
3042
}
3043

    
3044
uint64_t ram_bytes_total(void)
3045
{
3046
    return last_ram_offset;
3047
}
3048

    
3049
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3050
{
3051
    ram_addr_t addr;
3052
    uint64_t bytes_transferred_last;
3053
    double bwidth = 0;
3054
    uint64_t expected_time = 0;
3055

    
3056
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3057
        qemu_file_set_error(f);
3058
        return 0;
3059
    }
3060

    
3061
    if (stage == 1) {
3062
        /* Make sure all dirty bits are set */
3063
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3064
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3065
                cpu_physical_memory_set_dirty(addr);
3066
        }
3067

    
3068
        /* Enable dirty memory tracking */
3069
        cpu_physical_memory_set_dirty_tracking(1);
3070

    
3071
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3072
    }
3073

    
3074
    bytes_transferred_last = bytes_transferred;
3075
    bwidth = get_clock();
3076

    
3077
    while (!qemu_file_rate_limit(f)) {
3078
        int ret;
3079

    
3080
        ret = ram_save_block(f);
3081
        bytes_transferred += ret * TARGET_PAGE_SIZE;
3082
        if (ret == 0) /* no more blocks */
3083
            break;
3084
    }
3085

    
3086
    bwidth = get_clock() - bwidth;
3087
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3088

    
3089
    /* if we haven't transferred anything this round, force expected_time to a
3090
     * a very high value, but without crashing */
3091
    if (bwidth == 0)
3092
        bwidth = 0.000001;
3093

    
3094
    /* try transferring iterative blocks of memory */
3095

    
3096
    if (stage == 3) {
3097

    
3098
        /* flush all remaining blocks regardless of rate limiting */
3099
        while (ram_save_block(f) != 0) {
3100
            bytes_transferred += TARGET_PAGE_SIZE;
3101
        }
3102
        cpu_physical_memory_set_dirty_tracking(0);
3103
    }
3104

    
3105
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3106

    
3107
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3108

    
3109
    return (stage == 2) && (expected_time <= migrate_max_downtime());
3110
}
3111

    
3112
static int ram_load_dead(QEMUFile *f, void *opaque)
3113
{
3114
    RamDecompressState s1, *s = &s1;
3115
    uint8_t buf[10];
3116
    ram_addr_t i;
3117

    
3118
    if (ram_decompress_open(s, f) < 0)
3119
        return -EINVAL;
3120
    for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3121
        if (ram_decompress_buf(s, buf, 1) < 0) {
3122
            fprintf(stderr, "Error while reading ram block header\n");
3123
            goto error;
3124
        }
3125
        if (buf[0] == 0) {
3126
            if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3127
                                   BDRV_HASH_BLOCK_SIZE) < 0) {
3128
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3129
                goto error;
3130
            }
3131
        } else {
3132
        error:
3133
            printf("Error block header\n");
3134
            return -EINVAL;
3135
        }
3136
    }
3137
    ram_decompress_close(s);
3138

    
3139
    return 0;
3140
}
3141

    
3142
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3143
{
3144
    ram_addr_t addr;
3145
    int flags;
3146

    
3147
    if (version_id == 1)
3148
        return ram_load_v1(f, opaque);
3149

    
3150
    if (version_id == 2) {
3151
        if (qemu_get_be32(f) != last_ram_offset)
3152
            return -EINVAL;
3153
        return ram_load_dead(f, opaque);
3154
    }
3155

    
3156
    if (version_id != 3)
3157
        return -EINVAL;
3158

    
3159
    do {
3160
        addr = qemu_get_be64(f);
3161

    
3162
        flags = addr & ~TARGET_PAGE_MASK;
3163
        addr &= TARGET_PAGE_MASK;
3164

    
3165
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3166
            if (addr != last_ram_offset)
3167
                return -EINVAL;
3168
        }
3169

    
3170
        if (flags & RAM_SAVE_FLAG_FULL) {
3171
            if (ram_load_dead(f, opaque) < 0)
3172
                return -EINVAL;
3173
        }
3174
        
3175
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3176
            uint8_t ch = qemu_get_byte(f);
3177
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3178
#ifndef _WIN32
3179
            if (ch == 0 &&
3180
                (!kvm_enabled() || kvm_has_sync_mmu())) {
3181
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3182
            }
3183
#endif
3184
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3185
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3186
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3187

    
3188
    return 0;
3189
}
3190

    
3191
void qemu_service_io(void)
3192
{
3193
    qemu_notify_event();
3194
}
3195

    
3196
/***********************************************************/
3197
/* bottom halves (can be seen as timers which expire ASAP) */
3198

    
3199
struct QEMUBH {
3200
    QEMUBHFunc *cb;
3201
    void *opaque;
3202
    int scheduled;
3203
    int idle;
3204
    int deleted;
3205
    QEMUBH *next;
3206
};
3207

    
3208
static QEMUBH *first_bh = NULL;
3209

    
3210
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3211
{
3212
    QEMUBH *bh;
3213
    bh = qemu_mallocz(sizeof(QEMUBH));
3214
    bh->cb = cb;
3215
    bh->opaque = opaque;
3216
    bh->next = first_bh;
3217
    first_bh = bh;
3218
    return bh;
3219
}
3220

    
3221
int qemu_bh_poll(void)
3222
{
3223
    QEMUBH *bh, **bhp;
3224
    int ret;
3225

    
3226
    ret = 0;
3227
    for (bh = first_bh; bh; bh = bh->next) {
3228
        if (!bh->deleted && bh->scheduled) {
3229
            bh->scheduled = 0;
3230
            if (!bh->idle)
3231
                ret = 1;
3232
            bh->idle = 0;
3233
            bh->cb(bh->opaque);
3234
        }
3235
    }
3236

    
3237
    /* remove deleted bhs */
3238
    bhp = &first_bh;
3239
    while (*bhp) {
3240
        bh = *bhp;
3241
        if (bh->deleted) {
3242
            *bhp = bh->next;
3243
            qemu_free(bh);
3244
        } else
3245
            bhp = &bh->next;
3246
    }
3247

    
3248
    return ret;
3249
}
3250

    
3251
void qemu_bh_schedule_idle(QEMUBH *bh)
3252
{
3253
    if (bh->scheduled)
3254
        return;
3255
    bh->scheduled = 1;
3256
    bh->idle = 1;
3257
}
3258

    
3259
void qemu_bh_schedule(QEMUBH *bh)
3260
{
3261
    if (bh->scheduled)
3262
        return;
3263
    bh->scheduled = 1;
3264
    bh->idle = 0;
3265
    /* stop the currently executing CPU to execute the BH ASAP */
3266
    qemu_notify_event();
3267
}
3268

    
3269
void qemu_bh_cancel(QEMUBH *bh)
3270
{
3271
    bh->scheduled = 0;
3272
}
3273

    
3274
void qemu_bh_delete(QEMUBH *bh)
3275
{
3276
    bh->scheduled = 0;
3277
    bh->deleted = 1;
3278
}
3279

    
3280
static void qemu_bh_update_timeout(int *timeout)
3281
{
3282
    QEMUBH *bh;
3283

    
3284
    for (bh = first_bh; bh; bh = bh->next) {
3285
        if (!bh->deleted && bh->scheduled) {
3286
            if (bh->idle) {
3287
                /* idle bottom halves will be polled at least
3288
                 * every 10ms */
3289
                *timeout = MIN(10, *timeout);
3290
            } else {
3291
                /* non-idle bottom halves will be executed
3292
                 * immediately */
3293
                *timeout = 0;
3294
                break;
3295
            }
3296
        }
3297
    }
3298
}
3299

    
3300
/***********************************************************/
3301
/* machine registration */
3302

    
3303
static QEMUMachine *first_machine = NULL;
3304
QEMUMachine *current_machine = NULL;
3305

    
3306
int qemu_register_machine(QEMUMachine *m)
3307
{
3308
    QEMUMachine **pm;
3309
    pm = &first_machine;
3310
    while (*pm != NULL)
3311
        pm = &(*pm)->next;
3312
    m->next = NULL;
3313
    *pm = m;
3314
    return 0;
3315
}
3316

    
3317
static QEMUMachine *find_machine(const char *name)
3318
{
3319
    QEMUMachine *m;
3320

    
3321
    for(m = first_machine; m != NULL; m = m->next) {
3322
        if (!strcmp(m->name, name))
3323
            return m;
3324
        if (m->alias && !strcmp(m->alias, name))
3325
            return m;
3326
    }
3327
    return NULL;
3328
}
3329

    
3330
static QEMUMachine *find_default_machine(void)
3331
{
3332
    QEMUMachine *m;
3333

    
3334
    for(m = first_machine; m != NULL; m = m->next) {
3335
        if (m->is_default) {
3336
            return m;
3337
        }
3338
    }
3339
    return NULL;
3340
}
3341

    
3342
/***********************************************************/
3343
/* main execution loop */
3344

    
3345
static void gui_update(void *opaque)
3346
{
3347
    uint64_t interval = GUI_REFRESH_INTERVAL;
3348
    DisplayState *ds = opaque;
3349
    DisplayChangeListener *dcl = ds->listeners;
3350

    
3351
    dpy_refresh(ds);
3352

    
3353
    while (dcl != NULL) {
3354
        if (dcl->gui_timer_interval &&
3355
            dcl->gui_timer_interval < interval)
3356
            interval = dcl->gui_timer_interval;
3357
        dcl = dcl->next;
3358
    }
3359
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3360
}
3361

    
3362
static void nographic_update(void *opaque)
3363
{
3364
    uint64_t interval = GUI_REFRESH_INTERVAL;
3365

    
3366
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3367
}
3368

    
3369
struct vm_change_state_entry {
3370
    VMChangeStateHandler *cb;
3371
    void *opaque;
3372
    LIST_ENTRY (vm_change_state_entry) entries;
3373
};
3374

    
3375
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3376

    
3377
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3378
                                                     void *opaque)
3379
{
3380
    VMChangeStateEntry *e;
3381

    
3382
    e = qemu_mallocz(sizeof (*e));
3383

    
3384
    e->cb = cb;
3385
    e->opaque = opaque;
3386
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3387
    return e;
3388
}
3389

    
3390
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3391
{
3392
    LIST_REMOVE (e, entries);
3393
    qemu_free (e);
3394
}
3395

    
3396
static void vm_state_notify(int running, int reason)
3397
{
3398
    VMChangeStateEntry *e;
3399

    
3400
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3401
        e->cb(e->opaque, running, reason);
3402
    }
3403
}
3404

    
3405
static void resume_all_vcpus(void);
3406
static void pause_all_vcpus(void);
3407

    
3408
void vm_start(void)
3409
{
3410
    if (!vm_running) {
3411
        cpu_enable_ticks();
3412
        vm_running = 1;
3413
        vm_state_notify(1, 0);
3414
        qemu_rearm_alarm_timer(alarm_timer);
3415
        resume_all_vcpus();
3416
    }
3417
}
3418

    
3419
/* reset/shutdown handler */
3420

    
3421
typedef struct QEMUResetEntry {
3422
    TAILQ_ENTRY(QEMUResetEntry) entry;
3423
    QEMUResetHandler *func;
3424
    void *opaque;
3425
} QEMUResetEntry;
3426

    
3427
static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3428
    TAILQ_HEAD_INITIALIZER(reset_handlers);
3429
static int reset_requested;
3430
static int shutdown_requested;
3431
static int powerdown_requested;
3432
static int debug_requested;
3433
static int vmstop_requested;
3434

    
3435
int qemu_shutdown_requested(void)
3436
{
3437
    int r = shutdown_requested;
3438
    shutdown_requested = 0;
3439
    return r;
3440
}
3441

    
3442
int qemu_reset_requested(void)
3443
{
3444
    int r = reset_requested;
3445
    reset_requested = 0;
3446
    return r;
3447
}
3448

    
3449
int qemu_powerdown_requested(void)
3450
{
3451
    int r = powerdown_requested;
3452
    powerdown_requested = 0;
3453
    return r;
3454
}
3455

    
3456
static int qemu_debug_requested(void)
3457
{
3458
    int r = debug_requested;
3459
    debug_requested = 0;
3460
    return r;
3461
}
3462

    
3463
static int qemu_vmstop_requested(void)
3464
{
3465
    int r = vmstop_requested;
3466
    vmstop_requested = 0;
3467
    return r;
3468
}
3469

    
3470
static void do_vm_stop(int reason)
3471
{
3472
    if (vm_running) {
3473
        cpu_disable_ticks();
3474
        vm_running = 0;
3475
        pause_all_vcpus();
3476
        vm_state_notify(0, reason);
3477
    }
3478
}
3479

    
3480
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3481
{
3482
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3483

    
3484
    re->func = func;
3485
    re->opaque = opaque;
3486
    TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3487
}
3488

    
3489
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3490
{
3491
    QEMUResetEntry *re;
3492

    
3493
    TAILQ_FOREACH(re, &reset_handlers, entry) {
3494
        if (re->func == func && re->opaque == opaque) {
3495
            TAILQ_REMOVE(&reset_handlers, re, entry);
3496
            qemu_free(re);
3497
            return;
3498
        }
3499
    }
3500
}
3501

    
3502
void qemu_system_reset(void)
3503
{
3504
    QEMUResetEntry *re, *nre;
3505

    
3506
    /* reset all devices */
3507
    TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3508
        re->func(re->opaque);
3509
    }
3510
}
3511

    
3512
void qemu_system_reset_request(void)
3513
{
3514
    if (no_reboot) {
3515
        shutdown_requested = 1;
3516
    } else {
3517
        reset_requested = 1;
3518
    }
3519
    qemu_notify_event();
3520
}
3521

    
3522
void qemu_system_shutdown_request(void)
3523
{
3524
    shutdown_requested = 1;
3525
    qemu_notify_event();
3526
}
3527

    
3528
void qemu_system_powerdown_request(void)
3529
{
3530
    powerdown_requested = 1;
3531
    qemu_notify_event();
3532
}
3533

    
3534
#ifdef CONFIG_IOTHREAD
3535
static void qemu_system_vmstop_request(int reason)
3536
{
3537
    vmstop_requested = reason;
3538
    qemu_notify_event();
3539
}
3540
#endif
3541

    
3542
#ifndef _WIN32
3543
static int io_thread_fd = -1;
3544

    
3545
static void qemu_event_increment(void)
3546
{
3547
    static const char byte = 0;
3548

    
3549
    if (io_thread_fd == -1)
3550
        return;
3551

    
3552
    write(io_thread_fd, &byte, sizeof(byte));
3553
}
3554

    
3555
static void qemu_event_read(void *opaque)
3556
{
3557
    int fd = (unsigned long)opaque;
3558
    ssize_t len;
3559

    
3560
    /* Drain the notify pipe */
3561
    do {
3562
        char buffer[512];
3563
        len = read(fd, buffer, sizeof(buffer));
3564
    } while ((len == -1 && errno == EINTR) || len > 0);
3565
}
3566

    
3567
static int qemu_event_init(void)
3568
{
3569
    int err;
3570
    int fds[2];
3571

    
3572
    err = pipe(fds);
3573
    if (err == -1)
3574
        return -errno;
3575

    
3576
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3577
    if (err < 0)
3578
        goto fail;
3579

    
3580
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3581
    if (err < 0)
3582
        goto fail;
3583

    
3584
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3585
                         (void *)(unsigned long)fds[0]);
3586

    
3587
    io_thread_fd = fds[1];
3588
    return 0;
3589

    
3590
fail:
3591
    close(fds[0]);
3592
    close(fds[1]);
3593
    return err;
3594
}
3595
#else
3596
HANDLE qemu_event_handle;
3597

    
3598
static void dummy_event_handler(void *opaque)
3599
{
3600
}
3601

    
3602
static int qemu_event_init(void)
3603
{
3604
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3605
    if (!qemu_event_handle) {
3606
        perror("Failed CreateEvent");
3607
        return -1;
3608
    }
3609
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3610
    return 0;
3611
}
3612

    
3613
static void qemu_event_increment(void)
3614
{
3615
    SetEvent(qemu_event_handle);
3616
}
3617
#endif
3618

    
3619
static int cpu_can_run(CPUState *env)
3620
{
3621
    if (env->stop)
3622
        return 0;
3623
    if (env->stopped)
3624
        return 0;
3625
    return 1;
3626
}
3627

    
3628
#ifndef CONFIG_IOTHREAD
3629
static int qemu_init_main_loop(void)
3630
{
3631
    return qemu_event_init();
3632
}
3633

    
3634
void qemu_init_vcpu(void *_env)
3635
{
3636
    CPUState *env = _env;
3637

    
3638
    if (kvm_enabled())
3639
        kvm_init_vcpu(env);
3640
    env->nr_cores = smp_cores;
3641
    env->nr_threads = smp_threads;
3642
    return;
3643
}
3644

    
3645
int qemu_cpu_self(void *env)
3646
{
3647
    return 1;
3648
}
3649

    
3650
static void resume_all_vcpus(void)
3651
{
3652
}
3653

    
3654
static void pause_all_vcpus(void)
3655
{
3656
}
3657

    
3658
void qemu_cpu_kick(void *env)
3659
{
3660
    return;
3661
}
3662

    
3663
void qemu_notify_event(void)
3664
{
3665
    CPUState *env = cpu_single_env;
3666

    
3667
    if (env) {
3668
        cpu_exit(env);
3669
    }
3670
}
3671

    
3672
#define qemu_mutex_lock_iothread() do { } while (0)
3673
#define qemu_mutex_unlock_iothread() do { } while (0)
3674

    
3675
void vm_stop(int reason)
3676
{
3677
    do_vm_stop(reason);
3678
}
3679

    
3680
#else /* CONFIG_IOTHREAD */
3681

    
3682
#include "qemu-thread.h"
3683

    
3684
QemuMutex qemu_global_mutex;
3685
static QemuMutex qemu_fair_mutex;
3686

    
3687
static QemuThread io_thread;
3688

    
3689
static QemuThread *tcg_cpu_thread;
3690
static QemuCond *tcg_halt_cond;
3691

    
3692
static int qemu_system_ready;
3693
/* cpu creation */
3694
static QemuCond qemu_cpu_cond;
3695
/* system init */
3696
static QemuCond qemu_system_cond;
3697
static QemuCond qemu_pause_cond;
3698

    
3699
static void block_io_signals(void);
3700
static void unblock_io_signals(void);
3701
static int tcg_has_work(void);
3702

    
3703
static int qemu_init_main_loop(void)
3704
{
3705
    int ret;
3706

    
3707
    ret = qemu_event_init();
3708
    if (ret)
3709
        return ret;
3710

    
3711
    qemu_cond_init(&qemu_pause_cond);
3712
    qemu_mutex_init(&qemu_fair_mutex);
3713
    qemu_mutex_init(&qemu_global_mutex);
3714
    qemu_mutex_lock(&qemu_global_mutex);
3715

    
3716
    unblock_io_signals();
3717
    qemu_thread_self(&io_thread);
3718

    
3719
    return 0;
3720
}
3721

    
3722
static void qemu_wait_io_event(CPUState *env)
3723
{
3724
    while (!tcg_has_work())
3725
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3726

    
3727
    qemu_mutex_unlock(&qemu_global_mutex);
3728

    
3729
    /*
3730
     * Users of qemu_global_mutex can be starved, having no chance
3731
     * to acquire it since this path will get to it first.
3732
     * So use another lock to provide fairness.
3733
     */
3734
    qemu_mutex_lock(&qemu_fair_mutex);
3735
    qemu_mutex_unlock(&qemu_fair_mutex);
3736

    
3737
    qemu_mutex_lock(&qemu_global_mutex);
3738
    if (env->stop) {
3739
        env->stop = 0;
3740
        env->stopped = 1;
3741
        qemu_cond_signal(&qemu_pause_cond);
3742
    }
3743
}
3744

    
3745
static int qemu_cpu_exec(CPUState *env);
3746

    
3747
static void *kvm_cpu_thread_fn(void *arg)
3748
{
3749
    CPUState *env = arg;
3750

    
3751
    block_io_signals();
3752
    qemu_thread_self(env->thread);
3753

    
3754
    /* signal CPU creation */
3755
    qemu_mutex_lock(&qemu_global_mutex);
3756
    env->created = 1;
3757
    qemu_cond_signal(&qemu_cpu_cond);
3758

    
3759
    /* and wait for machine initialization */
3760
    while (!qemu_system_ready)
3761
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3762

    
3763
    while (1) {
3764
        if (cpu_can_run(env))
3765
            qemu_cpu_exec(env);
3766
        qemu_wait_io_event(env);
3767
    }
3768

    
3769
    return NULL;
3770
}
3771

    
3772
static void tcg_cpu_exec(void);
3773

    
3774
static void *tcg_cpu_thread_fn(void *arg)
3775
{
3776
    CPUState *env = arg;
3777

    
3778
    block_io_signals();
3779
    qemu_thread_self(env->thread);
3780

    
3781
    /* signal CPU creation */
3782
    qemu_mutex_lock(&qemu_global_mutex);
3783
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3784
        env->created = 1;
3785
    qemu_cond_signal(&qemu_cpu_cond);
3786

    
3787
    /* and wait for machine initialization */
3788
    while (!qemu_system_ready)
3789
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3790

    
3791
    while (1) {
3792
        tcg_cpu_exec();
3793
        qemu_wait_io_event(cur_cpu);
3794
    }
3795

    
3796
    return NULL;
3797
}
3798

    
3799
void qemu_cpu_kick(void *_env)
3800
{
3801
    CPUState *env = _env;
3802
    qemu_cond_broadcast(env->halt_cond);
3803
    if (kvm_enabled())
3804
        qemu_thread_signal(env->thread, SIGUSR1);
3805
}
3806

    
3807
int qemu_cpu_self(void *env)
3808
{
3809
    return (cpu_single_env != NULL);
3810
}
3811

    
3812
static void cpu_signal(int sig)
3813
{
3814
    if (cpu_single_env)
3815
        cpu_exit(cpu_single_env);
3816
}
3817

    
3818
static void block_io_signals(void)
3819
{
3820
    sigset_t set;
3821
    struct sigaction sigact;
3822

    
3823
    sigemptyset(&set);
3824
    sigaddset(&set, SIGUSR2);
3825
    sigaddset(&set, SIGIO);
3826
    sigaddset(&set, SIGALRM);
3827
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3828

    
3829
    sigemptyset(&set);
3830
    sigaddset(&set, SIGUSR1);
3831
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3832

    
3833
    memset(&sigact, 0, sizeof(sigact));
3834
    sigact.sa_handler = cpu_signal;
3835
    sigaction(SIGUSR1, &sigact, NULL);
3836
}
3837

    
3838
static void unblock_io_signals(void)
3839
{
3840
    sigset_t set;
3841

    
3842
    sigemptyset(&set);
3843
    sigaddset(&set, SIGUSR2);
3844
    sigaddset(&set, SIGIO);
3845
    sigaddset(&set, SIGALRM);
3846
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3847

    
3848
    sigemptyset(&set);
3849
    sigaddset(&set, SIGUSR1);
3850
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3851
}
3852

    
3853
static void qemu_signal_lock(unsigned int msecs)
3854
{
3855
    qemu_mutex_lock(&qemu_fair_mutex);
3856

    
3857
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3858
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3859
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3860
            break;
3861
    }
3862
    qemu_mutex_unlock(&qemu_fair_mutex);
3863
}
3864

    
3865
static void qemu_mutex_lock_iothread(void)
3866
{
3867
    if (kvm_enabled()) {
3868
        qemu_mutex_lock(&qemu_fair_mutex);
3869
        qemu_mutex_lock(&qemu_global_mutex);
3870
        qemu_mutex_unlock(&qemu_fair_mutex);
3871
    } else
3872
        qemu_signal_lock(100);
3873
}
3874

    
3875
static void qemu_mutex_unlock_iothread(void)
3876
{
3877
    qemu_mutex_unlock(&qemu_global_mutex);
3878
}
3879

    
3880
static int all_vcpus_paused(void)
3881
{
3882
    CPUState *penv = first_cpu;
3883

    
3884
    while (penv) {
3885
        if (!penv->stopped)
3886
            return 0;
3887
        penv = (CPUState *)penv->next_cpu;
3888
    }
3889

    
3890
    return 1;
3891
}
3892

    
3893
static void pause_all_vcpus(void)
3894
{
3895
    CPUState *penv = first_cpu;
3896

    
3897
    while (penv) {
3898
        penv->stop = 1;
3899
        qemu_thread_signal(penv->thread, SIGUSR1);
3900
        qemu_cpu_kick(penv);
3901
        penv = (CPUState *)penv->next_cpu;
3902
    }
3903

    
3904
    while (!all_vcpus_paused()) {
3905
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3906
        penv = first_cpu;
3907
        while (penv) {
3908
            qemu_thread_signal(penv->thread, SIGUSR1);
3909
            penv = (CPUState *)penv->next_cpu;
3910
        }
3911
    }
3912
}
3913

    
3914
static void resume_all_vcpus(void)
3915
{
3916
    CPUState *penv = first_cpu;
3917

    
3918
    while (penv) {
3919
        penv->stop = 0;
3920
        penv->stopped = 0;
3921
        qemu_thread_signal(penv->thread, SIGUSR1);
3922
        qemu_cpu_kick(penv);
3923
        penv = (CPUState *)penv->next_cpu;
3924
    }
3925
}
3926

    
3927
static void tcg_init_vcpu(void *_env)
3928
{
3929
    CPUState *env = _env;
3930
    /* share a single thread for all cpus with TCG */
3931
    if (!tcg_cpu_thread) {
3932
        env->thread = qemu_mallocz(sizeof(QemuThread));
3933
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3934
        qemu_cond_init(env->halt_cond);
3935
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3936
        while (env->created == 0)
3937
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3938
        tcg_cpu_thread = env->thread;
3939
        tcg_halt_cond = env->halt_cond;
3940
    } else {
3941
        env->thread = tcg_cpu_thread;
3942
        env->halt_cond = tcg_halt_cond;
3943
    }
3944
}
3945

    
3946
static void kvm_start_vcpu(CPUState *env)
3947
{
3948
    kvm_init_vcpu(env);
3949
    env->thread = qemu_mallocz(sizeof(QemuThread));
3950
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3951
    qemu_cond_init(env->halt_cond);
3952
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3953
    while (env->created == 0)
3954
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3955
}
3956

    
3957
void qemu_init_vcpu(void *_env)
3958
{
3959
    CPUState *env = _env;
3960

    
3961
    if (kvm_enabled())
3962
        kvm_start_vcpu(env);
3963
    else
3964
        tcg_init_vcpu(env);
3965
    env->nr_cores = smp_cores;
3966
    env->nr_threads = smp_threads;
3967
}
3968

    
3969
void qemu_notify_event(void)
3970
{
3971
    qemu_event_increment();
3972
}
3973

    
3974
void vm_stop(int reason)
3975
{
3976
    QemuThread me;
3977
    qemu_thread_self(&me);
3978

    
3979
    if (!qemu_thread_equal(&me, &io_thread)) {
3980
        qemu_system_vmstop_request(reason);
3981
        /*
3982
         * FIXME: should not return to device code in case
3983
         * vm_stop() has been requested.
3984
         */
3985
        if (cpu_single_env) {
3986
            cpu_exit(cpu_single_env);
3987
            cpu_single_env->stop = 1;
3988
        }
3989
        return;
3990
    }
3991
    do_vm_stop(reason);
3992
}
3993

    
3994
#endif
3995

    
3996

    
3997
#ifdef _WIN32
3998
static void host_main_loop_wait(int *timeout)
3999
{
4000
    int ret, ret2, i;
4001
    PollingEntry *pe;
4002

    
4003

    
4004
    /* XXX: need to suppress polling by better using win32 events */
4005
    ret = 0;
4006
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4007
        ret |= pe->func(pe->opaque);
4008
    }
4009
    if (ret == 0) {
4010
        int err;
4011
        WaitObjects *w = &wait_objects;
4012

    
4013
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4014
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4015
            if (w->func[ret - WAIT_OBJECT_0])
4016
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4017

    
4018
            /* Check for additional signaled events */
4019
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4020

    
4021
                /* Check if event is signaled */
4022
                ret2 = WaitForSingleObject(w->events[i], 0);
4023
                if(ret2 == WAIT_OBJECT_0) {
4024
                    if (w->func[i])
4025
                        w->func[i](w->opaque[i]);
4026
                } else if (ret2 == WAIT_TIMEOUT) {
4027
                } else {
4028
                    err = GetLastError();
4029
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4030
                }
4031
            }
4032
        } else if (ret == WAIT_TIMEOUT) {
4033
        } else {
4034
            err = GetLastError();
4035
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4036
        }
4037
    }
4038

    
4039
    *timeout = 0;
4040
}
4041
#else
4042
static void host_main_loop_wait(int *timeout)
4043
{
4044
}
4045
#endif
4046

    
4047
void main_loop_wait(int timeout)
4048
{
4049
    IOHandlerRecord *ioh;
4050
    fd_set rfds, wfds, xfds;
4051
    int ret, nfds;
4052
    struct timeval tv;
4053

    
4054
    qemu_bh_update_timeout(&timeout);
4055

    
4056
    host_main_loop_wait(&timeout);
4057

    
4058
    /* poll any events */
4059
    /* XXX: separate device handlers from system ones */
4060
    nfds = -1;
4061
    FD_ZERO(&rfds);
4062
    FD_ZERO(&wfds);
4063
    FD_ZERO(&xfds);
4064
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4065
        if (ioh->deleted)
4066
            continue;
4067
        if (ioh->fd_read &&
4068
            (!ioh->fd_read_poll ||
4069
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4070
            FD_SET(ioh->fd, &rfds);
4071
            if (ioh->fd > nfds)
4072
                nfds = ioh->fd;
4073
        }
4074
        if (ioh->fd_write) {
4075
            FD_SET(ioh->fd, &wfds);
4076
            if (ioh->fd > nfds)
4077
                nfds = ioh->fd;
4078
        }
4079
    }
4080

    
4081
    tv.tv_sec = timeout / 1000;
4082
    tv.tv_usec = (timeout % 1000) * 1000;
4083

    
4084
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4085

    
4086
    qemu_mutex_unlock_iothread();
4087
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4088
    qemu_mutex_lock_iothread();
4089
    if (ret > 0) {
4090
        IOHandlerRecord **pioh;
4091

    
4092
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4093
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4094
                ioh->fd_read(ioh->opaque);
4095
            }
4096
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4097
                ioh->fd_write(ioh->opaque);
4098
            }
4099
        }
4100

    
4101
        /* remove deleted IO handlers */
4102
        pioh = &first_io_handler;
4103
        while (*pioh) {
4104
            ioh = *pioh;
4105
            if (ioh->deleted) {
4106
                *pioh = ioh->next;
4107
                qemu_free(ioh);
4108
            } else
4109
                pioh = &ioh->next;
4110
        }
4111
    }
4112

    
4113
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4114

    
4115
    /* rearm timer, if not periodic */
4116
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4117
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4118
        qemu_rearm_alarm_timer(alarm_timer);
4119
    }
4120

    
4121
    /* vm time timers */
4122
    if (vm_running) {
4123
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4124
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4125
                qemu_get_clock(vm_clock));
4126
    }
4127

    
4128
    /* real time timers */
4129
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4130
                    qemu_get_clock(rt_clock));
4131

    
4132
    /* Check bottom-halves last in case any of the earlier events triggered
4133
       them.  */
4134
    qemu_bh_poll();
4135

    
4136
}
4137

    
4138
static int qemu_cpu_exec(CPUState *env)
4139
{
4140
    int ret;
4141
#ifdef CONFIG_PROFILER
4142
    int64_t ti;
4143
#endif
4144

    
4145
#ifdef CONFIG_PROFILER
4146
    ti = profile_getclock();
4147
#endif
4148
    if (use_icount) {
4149
        int64_t count;
4150
        int decr;
4151
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4152
        env->icount_decr.u16.low = 0;
4153
        env->icount_extra = 0;
4154
        count = qemu_next_deadline();
4155
        count = (count + (1 << icount_time_shift) - 1)
4156
                >> icount_time_shift;
4157
        qemu_icount += count;
4158
        decr = (count > 0xffff) ? 0xffff : count;
4159
        count -= decr;
4160
        env->icount_decr.u16.low = decr;
4161
        env->icount_extra = count;
4162
    }
4163
    ret = cpu_exec(env);
4164
#ifdef CONFIG_PROFILER
4165
    qemu_time += profile_getclock() - ti;
4166
#endif
4167
    if (use_icount) {
4168
        /* Fold pending instructions back into the
4169
           instruction counter, and clear the interrupt flag.  */
4170
        qemu_icount -= (env->icount_decr.u16.low
4171
                        + env->icount_extra);
4172
        env->icount_decr.u32 = 0;
4173
        env->icount_extra = 0;
4174
    }
4175
    return ret;
4176
}
4177

    
4178
static void tcg_cpu_exec(void)
4179
{
4180
    int ret = 0;
4181

    
4182
    if (next_cpu == NULL)
4183
        next_cpu = first_cpu;
4184
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4185
        CPUState *env = cur_cpu = next_cpu;
4186

    
4187
        if (!vm_running)
4188
            break;
4189
        if (timer_alarm_pending) {
4190
            timer_alarm_pending = 0;
4191
            break;
4192
        }
4193
        if (cpu_can_run(env))
4194
            ret = qemu_cpu_exec(env);
4195
        if (ret == EXCP_DEBUG) {
4196
            gdb_set_stop_cpu(env);
4197
            debug_requested = 1;
4198
            break;
4199
        }
4200
    }
4201
}
4202

    
4203
static int cpu_has_work(CPUState *env)
4204
{
4205
    if (env->stop)
4206
        return 1;
4207
    if (env->stopped)
4208
        return 0;
4209
    if (!env->halted)
4210
        return 1;
4211
    if (qemu_cpu_has_work(env))
4212
        return 1;
4213
    return 0;
4214
}
4215

    
4216
static int tcg_has_work(void)
4217
{
4218
    CPUState *env;
4219

    
4220
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4221
        if (cpu_has_work(env))
4222
            return 1;
4223
    return 0;
4224
}
4225

    
4226
static int qemu_calculate_timeout(void)
4227
{
4228
#ifndef CONFIG_IOTHREAD
4229
    int timeout;
4230

    
4231
    if (!vm_running)
4232
        timeout = 5000;
4233
    else if (tcg_has_work())
4234
        timeout = 0;
4235
    else if (!use_icount)
4236
        timeout = 5000;
4237
    else {
4238
     /* XXX: use timeout computed from timers */
4239
        int64_t add;
4240
        int64_t delta;
4241
        /* Advance virtual time to the next event.  */
4242
        if (use_icount == 1) {
4243
            /* When not using an adaptive execution frequency
4244
               we tend to get badly out of sync with real time,
4245
               so just delay for a reasonable amount of time.  */
4246
            delta = 0;
4247
        } else {
4248
            delta = cpu_get_icount() - cpu_get_clock();
4249
        }
4250
        if (delta > 0) {
4251
            /* If virtual time is ahead of real time then just
4252
               wait for IO.  */
4253
            timeout = (delta / 1000000) + 1;
4254
        } else {
4255
            /* Wait for either IO to occur or the next
4256
               timer event.  */
4257
            add = qemu_next_deadline();
4258
            /* We advance the timer before checking for IO.
4259
               Limit the amount we advance so that early IO
4260
               activity won't get the guest too far ahead.  */
4261
            if (add > 10000000)
4262
                add = 10000000;
4263
            delta += add;
4264
            add = (add + (1 << icount_time_shift) - 1)
4265
                  >> icount_time_shift;
4266
            qemu_icount += add;
4267
            timeout = delta / 1000000;
4268
            if (timeout < 0)
4269
                timeout = 0;
4270
        }
4271
    }
4272

    
4273
    return timeout;
4274
#else /* CONFIG_IOTHREAD */
4275
    return 1000;
4276
#endif
4277
}
4278

    
4279
static int vm_can_run(void)
4280
{
4281
    if (powerdown_requested)
4282
        return 0;
4283
    if (reset_requested)
4284
        return 0;
4285
    if (shutdown_requested)
4286
        return 0;
4287
    if (debug_requested)
4288
        return 0;
4289
    return 1;
4290
}
4291

    
4292
qemu_irq qemu_system_powerdown;
4293

    
4294
static void main_loop(void)
4295
{
4296
    int r;
4297

    
4298
#ifdef CONFIG_IOTHREAD
4299
    qemu_system_ready = 1;
4300
    qemu_cond_broadcast(&qemu_system_cond);
4301
#endif
4302

    
4303
    for (;;) {
4304
        do {
4305
#ifdef CONFIG_PROFILER
4306
            int64_t ti;
4307
#endif
4308
#ifndef CONFIG_IOTHREAD
4309
            tcg_cpu_exec();
4310
#endif
4311
#ifdef CONFIG_PROFILER
4312
            ti = profile_getclock();
4313
#endif
4314
            main_loop_wait(qemu_calculate_timeout());
4315
#ifdef CONFIG_PROFILER
4316
            dev_time += profile_getclock() - ti;
4317
#endif
4318
        } while (vm_can_run());
4319

    
4320
        if (qemu_debug_requested())
4321
            vm_stop(EXCP_DEBUG);
4322
        if (qemu_shutdown_requested()) {
4323
            if (no_shutdown) {
4324
                vm_stop(0);
4325
                no_shutdown = 0;
4326
            } else
4327
                break;
4328
        }
4329
        if (qemu_reset_requested()) {
4330
            pause_all_vcpus();
4331
            qemu_system_reset();
4332
            resume_all_vcpus();
4333
        }
4334
        if (qemu_powerdown_requested()) {
4335
            qemu_irq_raise(qemu_system_powerdown);
4336
        }
4337
        if ((r = qemu_vmstop_requested()))
4338
            vm_stop(r);
4339
    }
4340
    pause_all_vcpus();
4341
}
4342

    
4343
static void version(void)
4344
{
4345
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4346
}
4347

    
4348
static void help(int exitcode)
4349
{
4350
    version();
4351
    printf("usage: %s [options] [disk_image]\n"
4352
           "\n"
4353
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4354
           "\n"
4355
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4356
           opt_help
4357
#define DEFHEADING(text) stringify(text) "\n"
4358
#include "qemu-options.h"
4359
#undef DEF
4360
#undef DEFHEADING
4361
#undef GEN_DOCS
4362
           "\n"
4363
           "During emulation, the following keys are useful:\n"
4364
           "ctrl-alt-f      toggle full screen\n"
4365
           "ctrl-alt-n      switch to virtual console 'n'\n"
4366
           "ctrl-alt        toggle mouse and keyboard grab\n"
4367
           "\n"
4368
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4369
           ,
4370
           "qemu",
4371
           DEFAULT_RAM_SIZE,
4372
#ifndef _WIN32
4373
           DEFAULT_NETWORK_SCRIPT,
4374
           DEFAULT_NETWORK_DOWN_SCRIPT,
4375
#endif
4376
           DEFAULT_GDBSTUB_PORT,
4377
           "/tmp/qemu.log");
4378
    exit(exitcode);
4379
}
4380

    
4381
#define HAS_ARG 0x0001
4382

    
4383
enum {
4384
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4385
    opt_enum,
4386
#define DEFHEADING(text)
4387
#include "qemu-options.h"
4388
#undef DEF
4389
#undef DEFHEADING
4390
#undef GEN_DOCS
4391
};
4392

    
4393
typedef struct QEMUOption {
4394
    const char *name;
4395
    int flags;
4396
    int index;
4397
} QEMUOption;
4398

    
4399
static const QEMUOption qemu_options[] = {
4400
    { "h", 0, QEMU_OPTION_h },
4401
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4402
    { option, opt_arg, opt_enum },
4403
#define DEFHEADING(text)
4404
#include "qemu-options.h"
4405
#undef DEF
4406
#undef DEFHEADING
4407
#undef GEN_DOCS
4408
    { NULL },
4409
};
4410

    
4411
#ifdef HAS_AUDIO
4412
struct soundhw soundhw[] = {
4413
#ifdef HAS_AUDIO_CHOICE
4414
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4415
    {
4416
        "pcspk",
4417
        "PC speaker",
4418
        0,
4419
        1,
4420
        { .init_isa = pcspk_audio_init }
4421
    },
4422
#endif
4423

    
4424
#ifdef CONFIG_SB16
4425
    {
4426
        "sb16",
4427
        "Creative Sound Blaster 16",
4428
        0,
4429
        1,
4430
        { .init_isa = SB16_init }
4431
    },
4432
#endif
4433

    
4434
#ifdef CONFIG_CS4231A
4435
    {
4436
        "cs4231a",
4437
        "CS4231A",
4438
        0,
4439
        1,
4440
        { .init_isa = cs4231a_init }
4441
    },
4442
#endif
4443

    
4444
#ifdef CONFIG_ADLIB
4445
    {
4446
        "adlib",
4447
#ifdef HAS_YMF262
4448
        "Yamaha YMF262 (OPL3)",
4449
#else
4450
        "Yamaha YM3812 (OPL2)",
4451
#endif
4452
        0,
4453
        1,
4454
        { .init_isa = Adlib_init }
4455
    },
4456
#endif
4457

    
4458
#ifdef CONFIG_GUS
4459
    {
4460
        "gus",
4461
        "Gravis Ultrasound GF1",
4462
        0,
4463
        1,
4464
        { .init_isa = GUS_init }
4465
    },
4466
#endif
4467

    
4468
#ifdef CONFIG_AC97
4469
    {
4470
        "ac97",
4471
        "Intel 82801AA AC97 Audio",
4472
        0,
4473
        0,
4474
        { .init_pci = ac97_init }
4475
    },
4476
#endif
4477

    
4478
#ifdef CONFIG_ES1370
4479
    {
4480
        "es1370",
4481
        "ENSONIQ AudioPCI ES1370",
4482
        0,
4483
        0,
4484
        { .init_pci = es1370_init }
4485
    },
4486
#endif
4487

    
4488
#endif /* HAS_AUDIO_CHOICE */
4489

    
4490
    { NULL, NULL, 0, 0, { NULL } }
4491
};
4492

    
4493
static void select_soundhw (const char *optarg)
4494
{
4495
    struct soundhw *c;
4496

    
4497
    if (*optarg == '?') {
4498
    show_valid_cards:
4499

    
4500
        printf ("Valid sound card names (comma separated):\n");
4501
        for (c = soundhw; c->name; ++c) {
4502
            printf ("%-11s %s\n", c->name, c->descr);
4503
        }
4504
        printf ("\n-soundhw all will enable all of the above\n");
4505
        exit (*optarg != '?');
4506
    }
4507
    else {
4508
        size_t l;
4509
        const char *p;
4510
        char *e;
4511
        int bad_card = 0;
4512

    
4513
        if (!strcmp (optarg, "all")) {
4514
            for (c = soundhw; c->name; ++c) {
4515
                c->enabled = 1;
4516
            }
4517
            return;
4518
        }
4519

    
4520
        p = optarg;
4521
        while (*p) {
4522
            e = strchr (p, ',');
4523
            l = !e ? strlen (p) : (size_t) (e - p);
4524

    
4525
            for (c = soundhw; c->name; ++c) {
4526
                if (!strncmp (c->name, p, l)) {
4527
                    c->enabled = 1;
4528
                    break;
4529
                }
4530
            }
4531

    
4532
            if (!c->name) {
4533
                if (l > 80) {
4534
                    fprintf (stderr,
4535
                             "Unknown sound card name (too big to show)\n");
4536
                }
4537
                else {
4538
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4539
                             (int) l, p);
4540
                }
4541
                bad_card = 1;
4542
            }
4543
            p += l + (e != NULL);
4544
        }
4545

    
4546
        if (bad_card)
4547
            goto show_valid_cards;
4548
    }
4549
}
4550
#endif
4551

    
4552
static void select_vgahw (const char *p)
4553
{
4554
    const char *opts;
4555

    
4556
    vga_interface_type = VGA_NONE;
4557
    if (strstart(p, "std", &opts)) {
4558
        vga_interface_type = VGA_STD;
4559
    } else if (strstart(p, "cirrus", &opts)) {
4560
        vga_interface_type = VGA_CIRRUS;
4561
    } else if (strstart(p, "vmware", &opts)) {
4562
        vga_interface_type = VGA_VMWARE;
4563
    } else if (strstart(p, "xenfb", &opts)) {
4564
        vga_interface_type = VGA_XENFB;
4565
    } else if (!strstart(p, "none", &opts)) {
4566
    invalid_vga:
4567
        fprintf(stderr, "Unknown vga type: %s\n", p);
4568
        exit(1);
4569
    }
4570
    while (*opts) {
4571
        const char *nextopt;
4572

    
4573
        if (strstart(opts, ",retrace=", &nextopt)) {
4574
            opts = nextopt;
4575
            if (strstart(opts, "dumb", &nextopt))
4576
                vga_retrace_method = VGA_RETRACE_DUMB;
4577
            else if (strstart(opts, "precise", &nextopt))
4578
                vga_retrace_method = VGA_RETRACE_PRECISE;
4579
            else goto invalid_vga;
4580
        } else goto invalid_vga;
4581
        opts = nextopt;
4582
    }
4583
}
4584

    
4585
#ifdef TARGET_I386
4586
static int balloon_parse(const char *arg)
4587
{
4588
    char buf[128];
4589
    const char *p;
4590

    
4591
    if (!strcmp(arg, "none")) {
4592
        virtio_balloon = 0;
4593
    } else if (!strncmp(arg, "virtio", 6)) {
4594
        virtio_balloon = 1;
4595
        if (arg[6] == ',')  {
4596
            p = arg + 7;
4597
            if (get_param_value(buf, sizeof(buf), "addr", p)) {
4598
                virtio_balloon_devaddr = strdup(buf);
4599
            }
4600
        }
4601
    } else {
4602
        return -1;
4603
    }
4604
    return 0;
4605
}
4606
#endif
4607

    
4608
#ifdef _WIN32
4609
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4610
{
4611
    exit(STATUS_CONTROL_C_EXIT);
4612
    return TRUE;
4613
}
4614
#endif
4615

    
4616
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4617
{
4618
    int ret;
4619

    
4620
    if(strlen(str) != 36)
4621
        return -1;
4622

    
4623
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4624
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4625
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4626

    
4627
    if(ret != 16)
4628
        return -1;
4629

    
4630
#ifdef TARGET_I386
4631
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4632
#endif
4633

    
4634
    return 0;
4635
}
4636

    
4637
#define MAX_NET_CLIENTS 32
4638

    
4639
#ifndef _WIN32
4640

    
4641
static void termsig_handler(int signal)
4642
{
4643
    qemu_system_shutdown_request();
4644
}
4645

    
4646
static void sigchld_handler(int signal)
4647
{
4648
    waitpid(-1, NULL, WNOHANG);
4649
}
4650

    
4651
static void sighandler_setup(void)
4652
{
4653
    struct sigaction act;
4654

    
4655
    memset(&act, 0, sizeof(act));
4656
    act.sa_handler = termsig_handler;
4657
    sigaction(SIGINT,  &act, NULL);
4658
    sigaction(SIGHUP,  &act, NULL);
4659
    sigaction(SIGTERM, &act, NULL);
4660

    
4661
    act.sa_handler = sigchld_handler;
4662
    act.sa_flags = SA_NOCLDSTOP;
4663
    sigaction(SIGCHLD, &act, NULL);
4664
}
4665

    
4666
#endif
4667

    
4668
#ifdef _WIN32
4669
/* Look for support files in the same directory as the executable.  */
4670
static char *find_datadir(const char *argv0)
4671
{
4672
    char *p;
4673
    char buf[MAX_PATH];
4674
    DWORD len;
4675

    
4676
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4677
    if (len == 0) {
4678
        return NULL;
4679
    }
4680

    
4681
    buf[len] = 0;
4682
    p = buf + len - 1;
4683
    while (p != buf && *p != '\\')
4684
        p--;
4685
    *p = 0;
4686
    if (access(buf, R_OK) == 0) {
4687
        return qemu_strdup(buf);
4688
    }
4689
    return NULL;
4690
}
4691
#else /* !_WIN32 */
4692

    
4693
/* Find a likely location for support files using the location of the binary.
4694
   For installed binaries this will be "$bindir/../share/qemu".  When
4695
   running from the build tree this will be "$bindir/../pc-bios".  */
4696
#define SHARE_SUFFIX "/share/qemu"
4697
#define BUILD_SUFFIX "/pc-bios"
4698
static char *find_datadir(const char *argv0)
4699
{
4700
    char *dir;
4701
    char *p = NULL;
4702
    char *res;
4703
#ifdef PATH_MAX
4704
    char buf[PATH_MAX];
4705
#endif
4706
    size_t max_len;
4707

    
4708
#if defined(__linux__)
4709
    {
4710
        int len;
4711
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4712
        if (len > 0) {
4713
            buf[len] = 0;
4714
            p = buf;
4715
        }
4716
    }
4717
#elif defined(__FreeBSD__)
4718
    {
4719
        int len;
4720
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4721
        if (len > 0) {
4722
            buf[len] = 0;
4723
            p = buf;
4724
        }
4725
    }
4726
#endif
4727
    /* If we don't have any way of figuring out the actual executable
4728
       location then try argv[0].  */
4729
    if (!p) {
4730
#ifdef PATH_MAX
4731
        p = buf;
4732
#endif
4733
        p = realpath(argv0, p);
4734
        if (!p) {
4735
            return NULL;
4736
        }
4737
    }
4738
    dir = dirname(p);
4739
    dir = dirname(dir);
4740

    
4741
    max_len = strlen(dir) +
4742
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4743
    res = qemu_mallocz(max_len);
4744
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4745
    if (access(res, R_OK)) {
4746
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4747
        if (access(res, R_OK)) {
4748
            qemu_free(res);
4749
            res = NULL;
4750
        }
4751
    }
4752
#ifndef PATH_MAX
4753
    free(p);
4754
#endif
4755
    return res;
4756
}
4757
#undef SHARE_SUFFIX
4758
#undef BUILD_SUFFIX
4759
#endif
4760

    
4761
char *qemu_find_file(int type, const char *name)
4762
{
4763
    int len;
4764
    const char *subdir;
4765
    char *buf;
4766

    
4767
    /* If name contains path separators then try it as a straight path.  */
4768
    if ((strchr(name, '/') || strchr(name, '\\'))
4769
        && access(name, R_OK) == 0) {
4770
        return strdup(name);
4771
    }
4772
    switch (type) {
4773
    case QEMU_FILE_TYPE_BIOS:
4774
        subdir = "";
4775
        break;
4776
    case QEMU_FILE_TYPE_KEYMAP:
4777
        subdir = "keymaps/";
4778
        break;
4779
    default:
4780
        abort();
4781
    }
4782
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4783
    buf = qemu_mallocz(len);
4784
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4785
    if (access(buf, R_OK)) {
4786
        qemu_free(buf);
4787
        return NULL;
4788
    }
4789
    return buf;
4790
}
4791

    
4792
static int device_init_func(QemuOpts *opts, void *opaque)
4793
{
4794
    DeviceState *dev;
4795

    
4796
    dev = qdev_device_add(opts);
4797
    if (!dev)
4798
        return -1;
4799
    return 0;
4800
}
4801

    
4802
struct device_config {
4803
    enum {
4804
        DEV_USB,       /* -usbdevice   */
4805
        DEV_BT,        /* -bt          */
4806
    } type;
4807
    const char *cmdline;
4808
    TAILQ_ENTRY(device_config) next;
4809
};
4810
TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4811

    
4812
static void add_device_config(int type, const char *cmdline)
4813
{
4814
    struct device_config *conf;
4815

    
4816
    conf = qemu_mallocz(sizeof(*conf));
4817
    conf->type = type;
4818
    conf->cmdline = cmdline;
4819
    TAILQ_INSERT_TAIL(&device_configs, conf, next);
4820
}
4821

    
4822
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4823
{
4824
    struct device_config *conf;
4825
    int rc;
4826

    
4827
    TAILQ_FOREACH(conf, &device_configs, next) {
4828
        if (conf->type != type)
4829
            continue;
4830
        rc = func(conf->cmdline);
4831
        if (0 != rc)
4832
            return rc;
4833
    }
4834
    return 0;
4835
}
4836

    
4837
int main(int argc, char **argv, char **envp)
4838
{
4839
    const char *gdbstub_dev = NULL;
4840
    uint32_t boot_devices_bitmap = 0;
4841
    int i;
4842
    int snapshot, linux_boot, net_boot;
4843
    const char *initrd_filename;
4844
    const char *kernel_filename, *kernel_cmdline;
4845
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4846
    DisplayState *ds;
4847
    DisplayChangeListener *dcl;
4848
    int cyls, heads, secs, translation;
4849
    const char *net_clients[MAX_NET_CLIENTS];
4850
    int nb_net_clients;
4851
    QemuOpts *hda_opts = NULL, *opts;
4852
    int optind;
4853
    const char *r, *optarg;
4854
    CharDriverState *monitor_hd = NULL;
4855
    const char *monitor_device;
4856
    const char *serial_devices[MAX_SERIAL_PORTS];
4857
    int serial_device_index;
4858
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4859
    int parallel_device_index;
4860
    const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4861
    int virtio_console_index;
4862
    const char *loadvm = NULL;
4863
    QEMUMachine *machine;
4864
    const char *cpu_model;
4865
#ifndef _WIN32
4866
    int fds[2];
4867
#endif
4868
    int tb_size;
4869
    const char *pid_file = NULL;
4870
    const char *incoming = NULL;
4871
#ifndef _WIN32
4872
    int fd = 0;
4873
    struct passwd *pwd = NULL;
4874
    const char *chroot_dir = NULL;
4875
    const char *run_as = NULL;
4876
#endif
4877
    CPUState *env;
4878
    int show_vnc_port = 0;
4879

    
4880
    qemu_cache_utils_init(envp);
4881

    
4882
    LIST_INIT (&vm_change_state_head);
4883
#ifndef _WIN32
4884
    {
4885
        struct sigaction act;
4886
        sigfillset(&act.sa_mask);
4887
        act.sa_flags = 0;
4888
        act.sa_handler = SIG_IGN;
4889
        sigaction(SIGPIPE, &act, NULL);
4890
    }
4891
#else
4892
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4893
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4894
       QEMU to run on a single CPU */
4895
    {
4896
        HANDLE h;
4897
        DWORD mask, smask;
4898
        int i;
4899
        h = GetCurrentProcess();
4900
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4901
            for(i = 0; i < 32; i++) {
4902
                if (mask & (1 << i))
4903
                    break;
4904
            }
4905
            if (i != 32) {
4906
                mask = 1 << i;
4907
                SetProcessAffinityMask(h, mask);
4908
            }
4909
        }
4910
    }
4911
#endif
4912

    
4913
    module_call_init(MODULE_INIT_MACHINE);
4914
    machine = find_default_machine();
4915
    cpu_model = NULL;
4916
    initrd_filename = NULL;
4917
    ram_size = 0;
4918
    snapshot = 0;
4919
    kernel_filename = NULL;
4920
    kernel_cmdline = "";
4921
    cyls = heads = secs = 0;
4922
    translation = BIOS_ATA_TRANSLATION_AUTO;
4923
    monitor_device = "vc:80Cx24C";
4924

    
4925
    serial_devices[0] = "vc:80Cx24C";
4926
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4927
        serial_devices[i] = NULL;
4928
    serial_device_index = 0;
4929

    
4930
    parallel_devices[0] = "vc:80Cx24C";
4931
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4932
        parallel_devices[i] = NULL;
4933
    parallel_device_index = 0;
4934

    
4935
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4936
        virtio_consoles[i] = NULL;
4937
    virtio_console_index = 0;
4938

    
4939
    for (i = 0; i < MAX_NODES; i++) {
4940
        node_mem[i] = 0;
4941
        node_cpumask[i] = 0;
4942
    }
4943

    
4944
    nb_net_clients = 0;
4945
    nb_numa_nodes = 0;
4946
    nb_nics = 0;
4947

    
4948
    tb_size = 0;
4949
    autostart= 1;
4950

    
4951
    register_watchdogs();
4952

    
4953
    optind = 1;
4954
    for(;;) {
4955
        if (optind >= argc)
4956
            break;
4957
        r = argv[optind];
4958
        if (r[0] != '-') {
4959
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4960
        } else {
4961
            const QEMUOption *popt;
4962

    
4963
            optind++;
4964
            /* Treat --foo the same as -foo.  */
4965
            if (r[1] == '-')
4966
                r++;
4967
            popt = qemu_options;
4968
            for(;;) {
4969
                if (!popt->name) {
4970
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4971
                            argv[0], r);
4972
                    exit(1);
4973
                }
4974
                if (!strcmp(popt->name, r + 1))
4975
                    break;
4976
                popt++;
4977
            }
4978
            if (popt->flags & HAS_ARG) {
4979
                if (optind >= argc) {
4980
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4981
                            argv[0], r);
4982
                    exit(1);
4983
                }
4984
                optarg = argv[optind++];
4985
            } else {
4986
                optarg = NULL;
4987
            }
4988

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

    
5142
                    if (!strchr(optarg, '=')) {
5143
                        legacy = 1;
5144
                        pstrcpy(buf, sizeof(buf), optarg);
5145
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5146
                        fprintf(stderr,
5147
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5148
                                buf, optarg);
5149
                        exit(1);
5150
                    }
5151

    
5152
                    if (legacy ||
5153
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
5154
                        boot_devices_bitmap = parse_bootdevices(buf);
5155
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
5156
                    }
5157
                    if (!legacy) {
5158
                        if (get_param_value(buf, sizeof(buf),
5159
                                            "once", optarg)) {
5160
                            boot_devices_bitmap |= parse_bootdevices(buf);
5161
                            standard_boot_devices = qemu_strdup(boot_devices);
5162
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
5163
                            qemu_register_reset(restore_boot_devices,
5164
                                                standard_boot_devices);
5165
                        }
5166
                        if (get_param_value(buf, sizeof(buf),
5167
                                            "menu", optarg)) {
5168
                            if (!strcmp(buf, "on")) {
5169
                                boot_menu = 1;
5170
                            } else if (!strcmp(buf, "off")) {
5171
                                boot_menu = 0;
5172
                            } else {
5173
                                fprintf(stderr,
5174
                                        "qemu: invalid option value '%s'\n",
5175
                                        buf);
5176
                                exit(1);
5177
                            }
5178
                        }
5179
                    }
5180
                }
5181
                break;
5182
            case QEMU_OPTION_fda:
5183
            case QEMU_OPTION_fdb:
5184
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5185
                break;
5186
#ifdef TARGET_I386
5187
            case QEMU_OPTION_no_fd_bootchk:
5188
                fd_bootchk = 0;
5189
                break;
5190
#endif
5191
            case QEMU_OPTION_net:
5192
                if (nb_net_clients >= MAX_NET_CLIENTS) {
5193
                    fprintf(stderr, "qemu: too many network clients\n");
5194
                    exit(1);
5195
                }
5196
                net_clients[nb_net_clients] = optarg;
5197
                nb_net_clients++;
5198
                break;
5199
#ifdef CONFIG_SLIRP
5200
            case QEMU_OPTION_tftp:
5201
                legacy_tftp_prefix = optarg;
5202
                break;
5203
            case QEMU_OPTION_bootp:
5204
                legacy_bootp_filename = optarg;
5205
                break;
5206
#ifndef _WIN32
5207
            case QEMU_OPTION_smb:
5208
                net_slirp_smb(optarg);
5209
                break;
5210
#endif
5211
            case QEMU_OPTION_redir:
5212
                net_slirp_redir(optarg);
5213
                break;
5214
#endif
5215
            case QEMU_OPTION_bt:
5216
                add_device_config(DEV_BT, optarg);
5217
                break;
5218
#ifdef HAS_AUDIO
5219
            case QEMU_OPTION_audio_help:
5220
                AUD_help ();
5221
                exit (0);
5222
                break;
5223
            case QEMU_OPTION_soundhw:
5224
                select_soundhw (optarg);
5225
                break;
5226
#endif
5227
            case QEMU_OPTION_h:
5228
                help(0);
5229
                break;
5230
            case QEMU_OPTION_version:
5231
                version();
5232
                exit(0);
5233
                break;
5234
            case QEMU_OPTION_m: {
5235
                uint64_t value;
5236
                char *ptr;
5237

    
5238
                value = strtoul(optarg, &ptr, 10);
5239
                switch (*ptr) {
5240
                case 0: case 'M': case 'm':
5241
                    value <<= 20;
5242
                    break;
5243
                case 'G': case 'g':
5244
                    value <<= 30;
5245
                    break;
5246
                default:
5247
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5248
                    exit(1);
5249
                }
5250

    
5251
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5252
                if (value > (2047 << 20) && HOST_LONG_BITS == 32) {
5253
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5254
                    exit(1);
5255
                }
5256
                if (value != (uint64_t)(ram_addr_t)value) {
5257
                    fprintf(stderr, "qemu: ram size too large\n");
5258
                    exit(1);
5259
                }
5260
                ram_size = value;
5261
                break;
5262
            }
5263
            case QEMU_OPTION_d:
5264
                {
5265
                    int mask;
5266
                    const CPULogItem *item;
5267

    
5268
                    mask = cpu_str_to_log_mask(optarg);
5269
                    if (!mask) {
5270
                        printf("Log items (comma separated):\n");
5271
                    for(item = cpu_log_items; item->mask != 0; item++) {
5272
                        printf("%-10s %s\n", item->name, item->help);
5273
                    }
5274
                    exit(1);
5275
                    }
5276
                    cpu_set_log(mask);
5277
                }
5278
                break;
5279
            case QEMU_OPTION_s:
5280
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5281
                break;
5282
            case QEMU_OPTION_gdb:
5283
                gdbstub_dev = optarg;
5284
                break;
5285
            case QEMU_OPTION_L:
5286
                data_dir = optarg;
5287
                break;
5288
            case QEMU_OPTION_bios:
5289
                bios_name = optarg;
5290
                break;
5291
            case QEMU_OPTION_singlestep:
5292
                singlestep = 1;
5293
                break;
5294
            case QEMU_OPTION_S:
5295
                autostart = 0;
5296
                break;
5297
#ifndef _WIN32
5298
            case QEMU_OPTION_k:
5299
                keyboard_layout = optarg;
5300
                break;
5301
#endif
5302
            case QEMU_OPTION_localtime:
5303
                rtc_utc = 0;
5304
                break;
5305
            case QEMU_OPTION_vga:
5306
                select_vgahw (optarg);
5307
                break;
5308
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
5309
            case QEMU_OPTION_g:
5310
                {
5311
                    const char *p;
5312
                    int w, h, depth;
5313
                    p = optarg;
5314
                    w = strtol(p, (char **)&p, 10);
5315
                    if (w <= 0) {
5316
                    graphic_error:
5317
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5318
                        exit(1);
5319
                    }
5320
                    if (*p != 'x')
5321
                        goto graphic_error;
5322
                    p++;
5323
                    h = strtol(p, (char **)&p, 10);
5324
                    if (h <= 0)
5325
                        goto graphic_error;
5326
                    if (*p == 'x') {
5327
                        p++;
5328
                        depth = strtol(p, (char **)&p, 10);
5329
                        if (depth != 8 && depth != 15 && depth != 16 &&
5330
                            depth != 24 && depth != 32)
5331
                            goto graphic_error;
5332
                    } else if (*p == '\0') {
5333
                        depth = graphic_depth;
5334
                    } else {
5335
                        goto graphic_error;
5336
                    }
5337

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

    
5630
    /* If no data_dir is specified then try to find it relative to the
5631
       executable path.  */
5632
    if (!data_dir) {
5633
        data_dir = find_datadir(argv[0]);
5634
    }
5635
    /* If all else fails use the install patch specified when building.  */
5636
    if (!data_dir) {
5637
        data_dir = CONFIG_QEMU_SHAREDIR;
5638
    }
5639

    
5640
    /*
5641
     * Default to max_cpus = smp_cpus, in case the user doesn't
5642
     * specify a max_cpus value.
5643
     */
5644
    if (!max_cpus)
5645
        max_cpus = smp_cpus;
5646

    
5647
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5648
    if (smp_cpus > machine->max_cpus) {
5649
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5650
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5651
                machine->max_cpus);
5652
        exit(1);
5653
    }
5654

    
5655
    if (display_type == DT_NOGRAPHIC) {
5656
       if (serial_device_index == 0)
5657
           serial_devices[0] = "stdio";
5658
       if (parallel_device_index == 0)
5659
           parallel_devices[0] = "null";
5660
       if (strncmp(monitor_device, "vc", 2) == 0)
5661
           monitor_device = "stdio";
5662
    }
5663

    
5664
#ifndef _WIN32
5665
    if (daemonize) {
5666
        pid_t pid;
5667

    
5668
        if (pipe(fds) == -1)
5669
            exit(1);
5670

    
5671
        pid = fork();
5672
        if (pid > 0) {
5673
            uint8_t status;
5674
            ssize_t len;
5675

    
5676
            close(fds[1]);
5677

    
5678
        again:
5679
            len = read(fds[0], &status, 1);
5680
            if (len == -1 && (errno == EINTR))
5681
                goto again;
5682

    
5683
            if (len != 1)
5684
                exit(1);
5685
            else if (status == 1) {
5686
                fprintf(stderr, "Could not acquire pidfile\n");
5687
                exit(1);
5688
            } else
5689
                exit(0);
5690
        } else if (pid < 0)
5691
            exit(1);
5692

    
5693
        setsid();
5694

    
5695
        pid = fork();
5696
        if (pid > 0)
5697
            exit(0);
5698
        else if (pid < 0)
5699
            exit(1);
5700

    
5701
        umask(027);
5702

    
5703
        signal(SIGTSTP, SIG_IGN);
5704
        signal(SIGTTOU, SIG_IGN);
5705
        signal(SIGTTIN, SIG_IGN);
5706
    }
5707

    
5708
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5709
        if (daemonize) {
5710
            uint8_t status = 1;
5711
            write(fds[1], &status, 1);
5712
        } else
5713
            fprintf(stderr, "Could not acquire pid file\n");
5714
        exit(1);
5715
    }
5716
#endif
5717

    
5718
    if (qemu_init_main_loop()) {
5719
        fprintf(stderr, "qemu_init_main_loop failed\n");
5720
        exit(1);
5721
    }
5722
    linux_boot = (kernel_filename != NULL);
5723

    
5724
    if (!linux_boot && *kernel_cmdline != '\0') {
5725
        fprintf(stderr, "-append only allowed with -kernel option\n");
5726
        exit(1);
5727
    }
5728

    
5729
    if (!linux_boot && initrd_filename != NULL) {
5730
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5731
        exit(1);
5732
    }
5733

    
5734
#ifndef _WIN32
5735
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5736
    setvbuf(stdout, NULL, _IOLBF, 0);
5737
#endif
5738

    
5739
    init_timers();
5740
    if (init_timer_alarm() < 0) {
5741
        fprintf(stderr, "could not initialize alarm timer\n");
5742
        exit(1);
5743
    }
5744
    if (use_icount && icount_time_shift < 0) {
5745
        use_icount = 2;
5746
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5747
           It will be corrected fairly quickly anyway.  */
5748
        icount_time_shift = 3;
5749
        init_icount_adjust();
5750
    }
5751

    
5752
#ifdef _WIN32
5753
    socket_init();
5754
#endif
5755

    
5756
    /* init network clients */
5757
    if (nb_net_clients == 0) {
5758
        /* if no clients, we use a default config */
5759
        net_clients[nb_net_clients++] = "nic";
5760
#ifdef CONFIG_SLIRP
5761
        net_clients[nb_net_clients++] = "user";
5762
#endif
5763
    }
5764

    
5765
    for(i = 0;i < nb_net_clients; i++) {
5766
        if (net_client_parse(net_clients[i]) < 0)
5767
            exit(1);
5768
    }
5769

    
5770
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5771
    net_set_boot_mask(net_boot);
5772

    
5773
    net_client_check();
5774

    
5775
    /* init the bluetooth world */
5776
    if (foreach_device_config(DEV_BT, bt_parse))
5777
        exit(1);
5778

    
5779
    /* init the memory */
5780
    if (ram_size == 0)
5781
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5782

    
5783
    /* init the dynamic translator */
5784
    cpu_exec_init_all(tb_size * 1024 * 1024);
5785

    
5786
    bdrv_init();
5787

    
5788
    /* we always create the cdrom drive, even if no disk is there */
5789
    drive_add(NULL, CDROM_ALIAS);
5790

    
5791
    /* we always create at least one floppy */
5792
    drive_add(NULL, FD_ALIAS, 0);
5793

    
5794
    /* we always create one sd slot, even if no card is in it */
5795
    drive_add(NULL, SD_ALIAS);
5796

    
5797
    /* open the virtual block devices */
5798
    if (snapshot)
5799
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5800
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5801
        exit(1);
5802

    
5803
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5804
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5805

    
5806
#ifndef _WIN32
5807
    /* must be after terminal init, SDL library changes signal handlers */
5808
    sighandler_setup();
5809
#endif
5810

    
5811
    /* Maintain compatibility with multiple stdio monitors */
5812
    if (!strcmp(monitor_device,"stdio")) {
5813
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5814
            const char *devname = serial_devices[i];
5815
            if (devname && !strcmp(devname,"mon:stdio")) {
5816
                monitor_device = NULL;
5817
                break;
5818
            } else if (devname && !strcmp(devname,"stdio")) {
5819
                monitor_device = NULL;
5820
                serial_devices[i] = "mon:stdio";
5821
                break;
5822
            }
5823
        }
5824
    }
5825

    
5826
    if (nb_numa_nodes > 0) {
5827
        int i;
5828

    
5829
        if (nb_numa_nodes > smp_cpus) {
5830
            nb_numa_nodes = smp_cpus;
5831
        }
5832

    
5833
        /* If no memory size if given for any node, assume the default case
5834
         * and distribute the available memory equally across all nodes
5835
         */
5836
        for (i = 0; i < nb_numa_nodes; i++) {
5837
            if (node_mem[i] != 0)
5838
                break;
5839
        }
5840
        if (i == nb_numa_nodes) {
5841
            uint64_t usedmem = 0;
5842

    
5843
            /* On Linux, the each node's border has to be 8MB aligned,
5844
             * the final node gets the rest.
5845
             */
5846
            for (i = 0; i < nb_numa_nodes - 1; i++) {
5847
                node_mem[i] = (ram_size / nb_numa_nodes) & ~((1 << 23UL) - 1);
5848
                usedmem += node_mem[i];
5849
            }
5850
            node_mem[i] = ram_size - usedmem;
5851
        }
5852

    
5853
        for (i = 0; i < nb_numa_nodes; i++) {
5854
            if (node_cpumask[i] != 0)
5855
                break;
5856
        }
5857
        /* assigning the VCPUs round-robin is easier to implement, guest OSes
5858
         * must cope with this anyway, because there are BIOSes out there in
5859
         * real machines which also use this scheme.
5860
         */
5861
        if (i == nb_numa_nodes) {
5862
            for (i = 0; i < smp_cpus; i++) {
5863
                node_cpumask[i % nb_numa_nodes] |= 1 << i;
5864
            }
5865
        }
5866
    }
5867

    
5868
    if (kvm_enabled()) {
5869
        int ret;
5870

    
5871
        ret = kvm_init(smp_cpus);
5872
        if (ret < 0) {
5873
            fprintf(stderr, "failed to initialize KVM\n");
5874
            exit(1);
5875
        }
5876
    }
5877

    
5878
    if (monitor_device) {
5879
        monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5880
        if (!monitor_hd) {
5881
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5882
            exit(1);
5883
        }
5884
    }
5885

    
5886
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5887
        const char *devname = serial_devices[i];
5888
        if (devname && strcmp(devname, "none")) {
5889
            char label[32];
5890
            snprintf(label, sizeof(label), "serial%d", i);
5891
            serial_hds[i] = qemu_chr_open(label, devname, NULL);
5892
            if (!serial_hds[i]) {
5893
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5894
                        devname);
5895
                exit(1);
5896
            }
5897
        }
5898
    }
5899

    
5900
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5901
        const char *devname = parallel_devices[i];
5902
        if (devname && strcmp(devname, "none")) {
5903
            char label[32];
5904
            snprintf(label, sizeof(label), "parallel%d", i);
5905
            parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5906
            if (!parallel_hds[i]) {
5907
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5908
                        devname);
5909
                exit(1);
5910
            }
5911
        }
5912
    }
5913

    
5914
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5915
        const char *devname = virtio_consoles[i];
5916
        if (devname && strcmp(devname, "none")) {
5917
            char label[32];
5918
            snprintf(label, sizeof(label), "virtcon%d", i);
5919
            virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5920
            if (!virtcon_hds[i]) {
5921
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5922
                        devname);
5923
                exit(1);
5924
            }
5925
        }
5926
    }
5927

    
5928
    module_call_init(MODULE_INIT_DEVICE);
5929

    
5930
    if (machine->compat_props) {
5931
        qdev_prop_register_compat(machine->compat_props);
5932
    }
5933
    machine->init(ram_size, boot_devices,
5934
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5935

    
5936

    
5937
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5938
        for (i = 0; i < nb_numa_nodes; i++) {
5939
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5940
                env->numa_node = i;
5941
            }
5942
        }
5943
    }
5944

    
5945
    current_machine = machine;
5946

    
5947
    /* init USB devices */
5948
    if (usb_enabled) {
5949
        foreach_device_config(DEV_USB, usb_parse);
5950
    }
5951

    
5952
    /* init generic devices */
5953
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5954
        exit(1);
5955

    
5956
    if (!display_state)
5957
        dumb_display_init();
5958
    /* just use the first displaystate for the moment */
5959
    ds = display_state;
5960

    
5961
    if (display_type == DT_DEFAULT) {
5962
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5963
        display_type = DT_SDL;
5964
#else
5965
        display_type = DT_VNC;
5966
        vnc_display = "localhost:0,to=99";
5967
        show_vnc_port = 1;
5968
#endif
5969
    }
5970
        
5971

    
5972
    switch (display_type) {
5973
    case DT_NOGRAPHIC:
5974
        break;
5975
#if defined(CONFIG_CURSES)
5976
    case DT_CURSES:
5977
        curses_display_init(ds, full_screen);
5978
        break;
5979
#endif
5980
#if defined(CONFIG_SDL)
5981
    case DT_SDL:
5982
        sdl_display_init(ds, full_screen, no_frame);
5983
        break;
5984
#elif defined(CONFIG_COCOA)
5985
    case DT_SDL:
5986
        cocoa_display_init(ds, full_screen);
5987
        break;
5988
#endif
5989
    case DT_VNC:
5990
        vnc_display_init(ds);
5991
        if (vnc_display_open(ds, vnc_display) < 0)
5992
            exit(1);
5993

    
5994
        if (show_vnc_port) {
5995
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
5996
        }
5997
        break;
5998
    default:
5999
        break;
6000
    }
6001
    dpy_resize(ds);
6002

    
6003
    dcl = ds->listeners;
6004
    while (dcl != NULL) {
6005
        if (dcl->dpy_refresh != NULL) {
6006
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6007
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6008
        }
6009
        dcl = dcl->next;
6010
    }
6011

    
6012
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6013
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6014
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6015
    }
6016

    
6017
    text_consoles_set_display(display_state);
6018
    qemu_chr_initial_reset();
6019

    
6020
    if (monitor_device && monitor_hd)
6021
        monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6022

    
6023
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6024
        const char *devname = serial_devices[i];
6025
        if (devname && strcmp(devname, "none")) {
6026
            if (strstart(devname, "vc", 0))
6027
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6028
        }
6029
    }
6030

    
6031
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6032
        const char *devname = parallel_devices[i];
6033
        if (devname && strcmp(devname, "none")) {
6034
            if (strstart(devname, "vc", 0))
6035
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6036
        }
6037
    }
6038

    
6039
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6040
        const char *devname = virtio_consoles[i];
6041
        if (virtcon_hds[i] && devname) {
6042
            if (strstart(devname, "vc", 0))
6043
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6044
        }
6045
    }
6046

    
6047
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6048
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6049
                gdbstub_dev);
6050
        exit(1);
6051
    }
6052

    
6053
    if (loadvm) {
6054
        if (load_vmstate(cur_mon, loadvm) < 0) {
6055
            autostart = 0;
6056
        }
6057
    }
6058

    
6059
    if (incoming) {
6060
        qemu_start_incoming_migration(incoming);
6061
    } else if (autostart) {
6062
        vm_start();
6063
    }
6064

    
6065
#ifndef _WIN32
6066
    if (daemonize) {
6067
        uint8_t status = 0;
6068
        ssize_t len;
6069

    
6070
    again1:
6071
        len = write(fds[1], &status, 1);
6072
        if (len == -1 && (errno == EINTR))
6073
            goto again1;
6074

    
6075
        if (len != 1)
6076
            exit(1);
6077

    
6078
        chdir("/");
6079
        TFR(fd = open("/dev/null", O_RDWR));
6080
        if (fd == -1)
6081
            exit(1);
6082
    }
6083

    
6084
    if (run_as) {
6085
        pwd = getpwnam(run_as);
6086
        if (!pwd) {
6087
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6088
            exit(1);
6089
        }
6090
    }
6091

    
6092
    if (chroot_dir) {
6093
        if (chroot(chroot_dir) < 0) {
6094
            fprintf(stderr, "chroot failed\n");
6095
            exit(1);
6096
        }
6097
        chdir("/");
6098
    }
6099

    
6100
    if (run_as) {
6101
        if (setgid(pwd->pw_gid) < 0) {
6102
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
6103
            exit(1);
6104
        }
6105
        if (setuid(pwd->pw_uid) < 0) {
6106
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
6107
            exit(1);
6108
        }
6109
        if (setuid(0) != -1) {
6110
            fprintf(stderr, "Dropping privileges failed\n");
6111
            exit(1);
6112
        }
6113
    }
6114

    
6115
    if (daemonize) {
6116
        dup2(fd, 0);
6117
        dup2(fd, 1);
6118
        dup2(fd, 2);
6119

    
6120
        close(fd);
6121
    }
6122
#endif
6123

    
6124
    main_loop();
6125
    quit_timers();
6126
    net_cleanup();
6127

    
6128
    return 0;
6129
}