Statistics
| Branch: | Revision:

root / vl.c @ 72cf2d4f

History | View | Annotate | Download (151.8 kB)

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

    
32
/* Needed early for CONFIG_BSD etc. */
33
#include "config-host.h"
34

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

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

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

    
99
#if defined(__OpenBSD__)
100
#include <util.h>
101
#endif
102

    
103
#if defined(CONFIG_VDE)
104
#include <libvdeplug.h>
105
#endif
106

    
107
#ifdef _WIN32
108
#include <windows.h>
109
#include <mmsystem.h>
110
#endif
111

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

    
125
#ifdef CONFIG_COCOA
126
#undef main
127
#define main qemu_main
128
#endif /* CONFIG_COCOA */
129

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

    
161
#include "disas.h"
162

    
163
#include "exec-all.h"
164

    
165
#include "qemu_socket.h"
166

    
167
#include "slirp/libslirp.h"
168

    
169
#include "qemu-queue.h"
170

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

    
174
#define DEFAULT_RAM_SIZE 128
175

    
176
/* Maximum number of monitor devices */
177
#define MAX_MONITOR_DEVICES 10
178

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

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

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

    
268
uint8_t qemu_uuid[16];
269

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

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

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

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

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

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

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

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

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

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

    
340
/***********************************************************/
341
/* keyboard/mouse */
342

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

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

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

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

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

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

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

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

    
380
    return s;
381
}
382

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

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

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

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

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

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

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

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

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

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

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

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

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

    
457
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
458
}
459

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

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

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

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

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

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

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

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

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

    
528
/***********************************************************/
529
/* real time host monotonic timer */
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, get_ticks_per_sec(), 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
typedef struct TimersState {
610
    int64_t cpu_ticks_prev;
611
    int64_t cpu_ticks_offset;
612
    int64_t cpu_clock_offset;
613
    int32_t cpu_ticks_enabled;
614
    int64_t dummy;
615
} TimersState;
616

    
617
TimersState timers_state;
618

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

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

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

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

    
673
/***********************************************************/
674
/* timers */
675

    
676
#define QEMU_TIMER_REALTIME 0
677
#define QEMU_TIMER_VIRTUAL  1
678

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

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

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

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

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

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

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

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

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

    
721
static struct qemu_alarm_timer *alarm_timer;
722

    
723
#ifdef _WIN32
724

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

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

    
734
#else
735

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

    
739
#ifdef __linux__
740

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

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

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

    
751
#endif /* __linux__ */
752

    
753
#endif /* _WIN32 */
754

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

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

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

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

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

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

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

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

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

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

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

    
863
    arg = qemu_strdup(opt);
864

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

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

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

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

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

    
892
    qemu_free(arg);
893

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

    
904
QEMUClock *rt_clock;
905
QEMUClock *vm_clock;
906

    
907
static QEMUTimer *active_timers[2];
908

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

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

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

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

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

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

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

    
959
    qemu_del_timer(ts);
960

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1082
static void qemu_event_increment(void);
1083

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

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

    
1141
static int64_t qemu_next_deadline(void)
1142
{
1143
    int64_t delta;
1144

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

    
1153
    if (delta < 0)
1154
        delta = 0;
1155

    
1156
    return delta;
1157
}
1158

    
1159
#if defined(__linux__) || defined(_WIN32)
1160
static uint64_t qemu_next_deadline_dyntick(void)
1161
{
1162
    int64_t delta;
1163
    int64_t rtdelta;
1164

    
1165
    if (use_icount)
1166
        delta = INT32_MAX;
1167
    else
1168
        delta = (qemu_next_deadline() + 999) / 1000;
1169

    
1170
    if (active_timers[QEMU_TIMER_REALTIME]) {
1171
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1172
                 qemu_get_clock(rt_clock))*1000;
1173
        if (rtdelta < delta)
1174
            delta = rtdelta;
1175
    }
1176

    
1177
    if (delta < MIN_TIMER_REARM_US)
1178
        delta = MIN_TIMER_REARM_US;
1179

    
1180
    return delta;
1181
}
1182
#endif
1183

    
1184
#ifndef _WIN32
1185

    
1186
/* Sets a specific flag */
1187
static int fcntl_setfl(int fd, int flag)
1188
{
1189
    int flags;
1190

    
1191
    flags = fcntl(fd, F_GETFL);
1192
    if (flags == -1)
1193
        return -errno;
1194

    
1195
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1196
        return -errno;
1197

    
1198
    return 0;
1199
}
1200

    
1201
#if defined(__linux__)
1202

    
1203
#define RTC_FREQ 1024
1204

    
1205
static void enable_sigio_timer(int fd)
1206
{
1207
    struct sigaction act;
1208

    
1209
    /* timer signal */
1210
    sigfillset(&act.sa_mask);
1211
    act.sa_flags = 0;
1212
    act.sa_handler = host_alarm_handler;
1213

    
1214
    sigaction(SIGIO, &act, NULL);
1215
    fcntl_setfl(fd, O_ASYNC);
1216
    fcntl(fd, F_SETOWN, getpid());
1217
}
1218

    
1219
static int hpet_start_timer(struct qemu_alarm_timer *t)
1220
{
1221
    struct hpet_info info;
1222
    int r, fd;
1223

    
1224
    fd = open("/dev/hpet", O_RDONLY);
1225
    if (fd < 0)
1226
        return -1;
1227

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

    
1237
    /* Check capabilities */
1238
    r = ioctl(fd, HPET_INFO, &info);
1239
    if (r < 0)
1240
        goto fail;
1241

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

    
1247
    /* Enable interrupt */
1248
    r = ioctl(fd, HPET_IE_ON, 0);
1249
    if (r < 0)
1250
        goto fail;
1251

    
1252
    enable_sigio_timer(fd);
1253
    t->priv = (void *)(long)fd;
1254

    
1255
    return 0;
1256
fail:
1257
    close(fd);
1258
    return -1;
1259
}
1260

    
1261
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1262
{
1263
    int fd = (long)t->priv;
1264

    
1265
    close(fd);
1266
}
1267

    
1268
static int rtc_start_timer(struct qemu_alarm_timer *t)
1269
{
1270
    int rtc_fd;
1271
    unsigned long current_rtc_freq = 0;
1272

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

    
1290
    enable_sigio_timer(rtc_fd);
1291

    
1292
    t->priv = (void *)(long)rtc_fd;
1293

    
1294
    return 0;
1295
}
1296

    
1297
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1298
{
1299
    int rtc_fd = (long)t->priv;
1300

    
1301
    close(rtc_fd);
1302
}
1303

    
1304
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1305
{
1306
    struct sigevent ev;
1307
    timer_t host_timer;
1308
    struct sigaction act;
1309

    
1310
    sigfillset(&act.sa_mask);
1311
    act.sa_flags = 0;
1312
    act.sa_handler = host_alarm_handler;
1313

    
1314
    sigaction(SIGALRM, &act, NULL);
1315

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

    
1325
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1326
        perror("timer_create");
1327

    
1328
        /* disable dynticks */
1329
        fprintf(stderr, "Dynamic Ticks disabled\n");
1330

    
1331
        return -1;
1332
    }
1333

    
1334
    t->priv = (void *)(long)host_timer;
1335

    
1336
    return 0;
1337
}
1338

    
1339
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1340
{
1341
    timer_t host_timer = (timer_t)(long)t->priv;
1342

    
1343
    timer_delete(host_timer);
1344
}
1345

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

    
1353
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1354
                !active_timers[QEMU_TIMER_VIRTUAL])
1355
        return;
1356

    
1357
    nearest_delta_us = qemu_next_deadline_dyntick();
1358

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

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

    
1380
#endif /* defined(__linux__) */
1381

    
1382
static int unix_start_timer(struct qemu_alarm_timer *t)
1383
{
1384
    struct sigaction act;
1385
    struct itimerval itv;
1386
    int err;
1387

    
1388
    /* timer signal */
1389
    sigfillset(&act.sa_mask);
1390
    act.sa_flags = 0;
1391
    act.sa_handler = host_alarm_handler;
1392

    
1393
    sigaction(SIGALRM, &act, NULL);
1394

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

    
1401
    err = setitimer(ITIMER_REAL, &itv, NULL);
1402
    if (err)
1403
        return -1;
1404

    
1405
    return 0;
1406
}
1407

    
1408
static void unix_stop_timer(struct qemu_alarm_timer *t)
1409
{
1410
    struct itimerval itv;
1411

    
1412
    memset(&itv, 0, sizeof(itv));
1413
    setitimer(ITIMER_REAL, &itv, NULL);
1414
}
1415

    
1416
#endif /* !defined(_WIN32) */
1417

    
1418

    
1419
#ifdef _WIN32
1420

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

    
1427
    memset(&tc, 0, sizeof(tc));
1428
    timeGetDevCaps(&tc, sizeof(tc));
1429

    
1430
    if (data->period < tc.wPeriodMin)
1431
        data->period = tc.wPeriodMin;
1432

    
1433
    timeBeginPeriod(data->period);
1434

    
1435
    flags = TIME_CALLBACK_FUNCTION;
1436
    if (alarm_has_dynticks(t))
1437
        flags |= TIME_ONESHOT;
1438
    else
1439
        flags |= TIME_PERIODIC;
1440

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

    
1447
    if (!data->timerId) {
1448
        perror("Failed to initialize win32 alarm timer");
1449
        timeEndPeriod(data->period);
1450
        return -1;
1451
    }
1452

    
1453
    return 0;
1454
}
1455

    
1456
static void win32_stop_timer(struct qemu_alarm_timer *t)
1457
{
1458
    struct qemu_alarm_win32 *data = t->priv;
1459

    
1460
    timeKillEvent(data->timerId);
1461
    timeEndPeriod(data->period);
1462
}
1463

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

    
1469
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1470
                !active_timers[QEMU_TIMER_VIRTUAL])
1471
        return;
1472

    
1473
    nearest_delta_us = qemu_next_deadline_dyntick();
1474
    nearest_delta_us /= 1000;
1475

    
1476
    timeKillEvent(data->timerId);
1477

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

    
1484
    if (!data->timerId) {
1485
        perror("Failed to re-arm win32 alarm timer");
1486

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

    
1492
#endif /* _WIN32 */
1493

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

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

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

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

    
1512
    alarm_timer = t;
1513

    
1514
    return 0;
1515

    
1516
fail:
1517
    return err;
1518
}
1519

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1665
    return 0;
1666
}
1667

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

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

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

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

    
1690
    hci_table[nb_hcis++] = hci;
1691

    
1692
    return 0;
1693
}
1694

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

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

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

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

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

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

    
1724
    vlan = qemu_find_bt_vlan(vlan_id);
1725

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

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

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

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

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

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

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

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

    
1776
/***********************************************************/
1777
/* QEMU Block devices */
1778

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

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

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

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

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

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

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

    
1820
    return NULL;
1821
}
1822

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

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

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

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

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

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

    
1858
    return "\0";
1859
}
1860

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

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

    
1870
    return BLOCK_ERR_STOP_ENOSPC;
1871
}
1872

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

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

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

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

    
1915
    *fatal_error = 1;
1916

    
1917
    translation = BIOS_ATA_TRANSLATION_AUTO;
1918
    cache = 1;
1919

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2130
    /* check unit id */
2131

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

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

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

    
2147
    /* init */
2148

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2311
    qemu_boot_set(standard_boot_devices);
2312

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

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

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

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

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

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

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

    
2423
/***********************************************************/
2424
/* USB devices */
2425

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

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

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

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

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

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

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

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

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

    
2513
done:
2514
    return 0;
2515
}
2516

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

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

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

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

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

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

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

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

    
2552
/***********************************************************/
2553
/* PCMCIA/Cardbus */
2554

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

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

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

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

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

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

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

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

    
2595
/***********************************************************/
2596
/* register display */
2597

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

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

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

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

    
2625
/* dumb display */
2626

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

    
2635
/***********************************************************/
2636
/* I/O handling */
2637

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

    
2650
static IOHandlerRecord *first_io_handler;
2651

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

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

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

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

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

    
2711
static PollingEntry *first_polling_entry;
2712

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

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

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

    
2746
static WaitObjects wait_objects = {0};
2747

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

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

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

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

    
2781
/***********************************************************/
2782
/* ram save/restore */
2783

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

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

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

    
2801
    return 1;
2802
}
2803

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

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

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

    
2819
            p = qemu_get_ram_ptr(current_addr);
2820

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

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

    
2836
    return found;
2837
}
2838

    
2839
static uint64_t bytes_transferred = 0;
2840

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

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

    
2851
    return count;
2852
}
2853

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2916
    if (stage == 3) {
2917

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

    
2925
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
2926

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

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

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

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

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

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

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

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

    
2964
    return 0;
2965
}
2966

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

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

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

    
2984
static QEMUBH *first_bh = NULL;
2985

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

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

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

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

    
3024
    return ret;
3025
}
3026

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

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

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

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

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

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

    
3076
/***********************************************************/
3077
/* machine registration */
3078

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

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

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

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

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

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

    
3118
/***********************************************************/
3119
/* main execution loop */
3120

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

    
3127
    dpy_refresh(ds);
3128

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

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

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

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

    
3151
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3152

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

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

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

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

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

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

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

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

    
3195
/* reset/shutdown handler */
3196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3378
static int qemu_event_init(void)
3379
{
3380
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3381
    if (!qemu_event_handle) {
3382
        perror("Failed CreateEvent");
3383
        return -1;
3384
    }
3385
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3386
    return 0;
3387
}
3388

    
3389
static void qemu_event_increment(void)
3390
{
3391
    SetEvent(qemu_event_handle);
3392
}
3393
#endif
3394

    
3395
static int cpu_can_run(CPUState *env)
3396
{
3397
    if (env->stop)
3398
        return 0;
3399
    if (env->stopped)
3400
        return 0;
3401
    return 1;
3402
}
3403

    
3404
#ifndef CONFIG_IOTHREAD
3405
static int qemu_init_main_loop(void)
3406
{
3407
    return qemu_event_init();
3408
}
3409

    
3410
void qemu_init_vcpu(void *_env)
3411
{
3412
    CPUState *env = _env;
3413

    
3414
    if (kvm_enabled())
3415
        kvm_init_vcpu(env);
3416
    env->nr_cores = smp_cores;
3417
    env->nr_threads = smp_threads;
3418
    return;
3419
}
3420

    
3421
int qemu_cpu_self(void *env)
3422
{
3423
    return 1;
3424
}
3425

    
3426
static void resume_all_vcpus(void)
3427
{
3428
}
3429

    
3430
static void pause_all_vcpus(void)
3431
{
3432
}
3433

    
3434
void qemu_cpu_kick(void *env)
3435
{
3436
    return;
3437
}
3438

    
3439
void qemu_notify_event(void)
3440
{
3441
    CPUState *env = cpu_single_env;
3442

    
3443
    if (env) {
3444
        cpu_exit(env);
3445
    }
3446
}
3447

    
3448
#define qemu_mutex_lock_iothread() do { } while (0)
3449
#define qemu_mutex_unlock_iothread() do { } while (0)
3450

    
3451
void vm_stop(int reason)
3452
{
3453
    do_vm_stop(reason);
3454
}
3455

    
3456
#else /* CONFIG_IOTHREAD */
3457

    
3458
#include "qemu-thread.h"
3459

    
3460
QemuMutex qemu_global_mutex;
3461
static QemuMutex qemu_fair_mutex;
3462

    
3463
static QemuThread io_thread;
3464

    
3465
static QemuThread *tcg_cpu_thread;
3466
static QemuCond *tcg_halt_cond;
3467

    
3468
static int qemu_system_ready;
3469
/* cpu creation */
3470
static QemuCond qemu_cpu_cond;
3471
/* system init */
3472
static QemuCond qemu_system_cond;
3473
static QemuCond qemu_pause_cond;
3474

    
3475
static void block_io_signals(void);
3476
static void unblock_io_signals(void);
3477
static int tcg_has_work(void);
3478

    
3479
static int qemu_init_main_loop(void)
3480
{
3481
    int ret;
3482

    
3483
    ret = qemu_event_init();
3484
    if (ret)
3485
        return ret;
3486

    
3487
    qemu_cond_init(&qemu_pause_cond);
3488
    qemu_mutex_init(&qemu_fair_mutex);
3489
    qemu_mutex_init(&qemu_global_mutex);
3490
    qemu_mutex_lock(&qemu_global_mutex);
3491

    
3492
    unblock_io_signals();
3493
    qemu_thread_self(&io_thread);
3494

    
3495
    return 0;
3496
}
3497

    
3498
static void qemu_wait_io_event(CPUState *env)
3499
{
3500
    while (!tcg_has_work())
3501
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3502

    
3503
    qemu_mutex_unlock(&qemu_global_mutex);
3504

    
3505
    /*
3506
     * Users of qemu_global_mutex can be starved, having no chance
3507
     * to acquire it since this path will get to it first.
3508
     * So use another lock to provide fairness.
3509
     */
3510
    qemu_mutex_lock(&qemu_fair_mutex);
3511
    qemu_mutex_unlock(&qemu_fair_mutex);
3512

    
3513
    qemu_mutex_lock(&qemu_global_mutex);
3514
    if (env->stop) {
3515
        env->stop = 0;
3516
        env->stopped = 1;
3517
        qemu_cond_signal(&qemu_pause_cond);
3518
    }
3519
}
3520

    
3521
static int qemu_cpu_exec(CPUState *env);
3522

    
3523
static void *kvm_cpu_thread_fn(void *arg)
3524
{
3525
    CPUState *env = arg;
3526

    
3527
    block_io_signals();
3528
    qemu_thread_self(env->thread);
3529
    if (kvm_enabled())
3530
        kvm_init_vcpu(env);
3531

    
3532
    /* signal CPU creation */
3533
    qemu_mutex_lock(&qemu_global_mutex);
3534
    env->created = 1;
3535
    qemu_cond_signal(&qemu_cpu_cond);
3536

    
3537
    /* and wait for machine initialization */
3538
    while (!qemu_system_ready)
3539
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3540

    
3541
    while (1) {
3542
        if (cpu_can_run(env))
3543
            qemu_cpu_exec(env);
3544
        qemu_wait_io_event(env);
3545
    }
3546

    
3547
    return NULL;
3548
}
3549

    
3550
static void tcg_cpu_exec(void);
3551

    
3552
static void *tcg_cpu_thread_fn(void *arg)
3553
{
3554
    CPUState *env = arg;
3555

    
3556
    block_io_signals();
3557
    qemu_thread_self(env->thread);
3558

    
3559
    /* signal CPU creation */
3560
    qemu_mutex_lock(&qemu_global_mutex);
3561
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3562
        env->created = 1;
3563
    qemu_cond_signal(&qemu_cpu_cond);
3564

    
3565
    /* and wait for machine initialization */
3566
    while (!qemu_system_ready)
3567
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3568

    
3569
    while (1) {
3570
        tcg_cpu_exec();
3571
        qemu_wait_io_event(cur_cpu);
3572
    }
3573

    
3574
    return NULL;
3575
}
3576

    
3577
void qemu_cpu_kick(void *_env)
3578
{
3579
    CPUState *env = _env;
3580
    qemu_cond_broadcast(env->halt_cond);
3581
    if (kvm_enabled())
3582
        qemu_thread_signal(env->thread, SIGUSR1);
3583
}
3584

    
3585
int qemu_cpu_self(void *env)
3586
{
3587
    return (cpu_single_env != NULL);
3588
}
3589

    
3590
static void cpu_signal(int sig)
3591
{
3592
    if (cpu_single_env)
3593
        cpu_exit(cpu_single_env);
3594
}
3595

    
3596
static void block_io_signals(void)
3597
{
3598
    sigset_t set;
3599
    struct sigaction sigact;
3600

    
3601
    sigemptyset(&set);
3602
    sigaddset(&set, SIGUSR2);
3603
    sigaddset(&set, SIGIO);
3604
    sigaddset(&set, SIGALRM);
3605
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3606

    
3607
    sigemptyset(&set);
3608
    sigaddset(&set, SIGUSR1);
3609
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3610

    
3611
    memset(&sigact, 0, sizeof(sigact));
3612
    sigact.sa_handler = cpu_signal;
3613
    sigaction(SIGUSR1, &sigact, NULL);
3614
}
3615

    
3616
static void unblock_io_signals(void)
3617
{
3618
    sigset_t set;
3619

    
3620
    sigemptyset(&set);
3621
    sigaddset(&set, SIGUSR2);
3622
    sigaddset(&set, SIGIO);
3623
    sigaddset(&set, SIGALRM);
3624
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3625

    
3626
    sigemptyset(&set);
3627
    sigaddset(&set, SIGUSR1);
3628
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3629
}
3630

    
3631
static void qemu_signal_lock(unsigned int msecs)
3632
{
3633
    qemu_mutex_lock(&qemu_fair_mutex);
3634

    
3635
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3636
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3637
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3638
            break;
3639
    }
3640
    qemu_mutex_unlock(&qemu_fair_mutex);
3641
}
3642

    
3643
static void qemu_mutex_lock_iothread(void)
3644
{
3645
    if (kvm_enabled()) {
3646
        qemu_mutex_lock(&qemu_fair_mutex);
3647
        qemu_mutex_lock(&qemu_global_mutex);
3648
        qemu_mutex_unlock(&qemu_fair_mutex);
3649
    } else
3650
        qemu_signal_lock(100);
3651
}
3652

    
3653
static void qemu_mutex_unlock_iothread(void)
3654
{
3655
    qemu_mutex_unlock(&qemu_global_mutex);
3656
}
3657

    
3658
static int all_vcpus_paused(void)
3659
{
3660
    CPUState *penv = first_cpu;
3661

    
3662
    while (penv) {
3663
        if (!penv->stopped)
3664
            return 0;
3665
        penv = (CPUState *)penv->next_cpu;
3666
    }
3667

    
3668
    return 1;
3669
}
3670

    
3671
static void pause_all_vcpus(void)
3672
{
3673
    CPUState *penv = first_cpu;
3674

    
3675
    while (penv) {
3676
        penv->stop = 1;
3677
        qemu_thread_signal(penv->thread, SIGUSR1);
3678
        qemu_cpu_kick(penv);
3679
        penv = (CPUState *)penv->next_cpu;
3680
    }
3681

    
3682
    while (!all_vcpus_paused()) {
3683
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3684
        penv = first_cpu;
3685
        while (penv) {
3686
            qemu_thread_signal(penv->thread, SIGUSR1);
3687
            penv = (CPUState *)penv->next_cpu;
3688
        }
3689
    }
3690
}
3691

    
3692
static void resume_all_vcpus(void)
3693
{
3694
    CPUState *penv = first_cpu;
3695

    
3696
    while (penv) {
3697
        penv->stop = 0;
3698
        penv->stopped = 0;
3699
        qemu_thread_signal(penv->thread, SIGUSR1);
3700
        qemu_cpu_kick(penv);
3701
        penv = (CPUState *)penv->next_cpu;
3702
    }
3703
}
3704

    
3705
static void tcg_init_vcpu(void *_env)
3706
{
3707
    CPUState *env = _env;
3708
    /* share a single thread for all cpus with TCG */
3709
    if (!tcg_cpu_thread) {
3710
        env->thread = qemu_mallocz(sizeof(QemuThread));
3711
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3712
        qemu_cond_init(env->halt_cond);
3713
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3714
        while (env->created == 0)
3715
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3716
        tcg_cpu_thread = env->thread;
3717
        tcg_halt_cond = env->halt_cond;
3718
    } else {
3719
        env->thread = tcg_cpu_thread;
3720
        env->halt_cond = tcg_halt_cond;
3721
    }
3722
}
3723

    
3724
static void kvm_start_vcpu(CPUState *env)
3725
{
3726
    env->thread = qemu_mallocz(sizeof(QemuThread));
3727
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3728
    qemu_cond_init(env->halt_cond);
3729
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3730
    while (env->created == 0)
3731
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3732
}
3733

    
3734
void qemu_init_vcpu(void *_env)
3735
{
3736
    CPUState *env = _env;
3737

    
3738
    if (kvm_enabled())
3739
        kvm_start_vcpu(env);
3740
    else
3741
        tcg_init_vcpu(env);
3742
    env->nr_cores = smp_cores;
3743
    env->nr_threads = smp_threads;
3744
}
3745

    
3746
void qemu_notify_event(void)
3747
{
3748
    qemu_event_increment();
3749
}
3750

    
3751
void vm_stop(int reason)
3752
{
3753
    QemuThread me;
3754
    qemu_thread_self(&me);
3755

    
3756
    if (!qemu_thread_equal(&me, &io_thread)) {
3757
        qemu_system_vmstop_request(reason);
3758
        /*
3759
         * FIXME: should not return to device code in case
3760
         * vm_stop() has been requested.
3761
         */
3762
        if (cpu_single_env) {
3763
            cpu_exit(cpu_single_env);
3764
            cpu_single_env->stop = 1;
3765
        }
3766
        return;
3767
    }
3768
    do_vm_stop(reason);
3769
}
3770

    
3771
#endif
3772

    
3773

    
3774
#ifdef _WIN32
3775
static void host_main_loop_wait(int *timeout)
3776
{
3777
    int ret, ret2, i;
3778
    PollingEntry *pe;
3779

    
3780

    
3781
    /* XXX: need to suppress polling by better using win32 events */
3782
    ret = 0;
3783
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3784
        ret |= pe->func(pe->opaque);
3785
    }
3786
    if (ret == 0) {
3787
        int err;
3788
        WaitObjects *w = &wait_objects;
3789

    
3790
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3791
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3792
            if (w->func[ret - WAIT_OBJECT_0])
3793
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3794

    
3795
            /* Check for additional signaled events */
3796
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3797

    
3798
                /* Check if event is signaled */
3799
                ret2 = WaitForSingleObject(w->events[i], 0);
3800
                if(ret2 == WAIT_OBJECT_0) {
3801
                    if (w->func[i])
3802
                        w->func[i](w->opaque[i]);
3803
                } else if (ret2 == WAIT_TIMEOUT) {
3804
                } else {
3805
                    err = GetLastError();
3806
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3807
                }
3808
            }
3809
        } else if (ret == WAIT_TIMEOUT) {
3810
        } else {
3811
            err = GetLastError();
3812
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3813
        }
3814
    }
3815

    
3816
    *timeout = 0;
3817
}
3818
#else
3819
static void host_main_loop_wait(int *timeout)
3820
{
3821
}
3822
#endif
3823

    
3824
void main_loop_wait(int timeout)
3825
{
3826
    IOHandlerRecord *ioh;
3827
    fd_set rfds, wfds, xfds;
3828
    int ret, nfds;
3829
    struct timeval tv;
3830

    
3831
    qemu_bh_update_timeout(&timeout);
3832

    
3833
    host_main_loop_wait(&timeout);
3834

    
3835
    /* poll any events */
3836
    /* XXX: separate device handlers from system ones */
3837
    nfds = -1;
3838
    FD_ZERO(&rfds);
3839
    FD_ZERO(&wfds);
3840
    FD_ZERO(&xfds);
3841
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3842
        if (ioh->deleted)
3843
            continue;
3844
        if (ioh->fd_read &&
3845
            (!ioh->fd_read_poll ||
3846
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3847
            FD_SET(ioh->fd, &rfds);
3848
            if (ioh->fd > nfds)
3849
                nfds = ioh->fd;
3850
        }
3851
        if (ioh->fd_write) {
3852
            FD_SET(ioh->fd, &wfds);
3853
            if (ioh->fd > nfds)
3854
                nfds = ioh->fd;
3855
        }
3856
    }
3857

    
3858
    tv.tv_sec = timeout / 1000;
3859
    tv.tv_usec = (timeout % 1000) * 1000;
3860

    
3861
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3862

    
3863
    qemu_mutex_unlock_iothread();
3864
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3865
    qemu_mutex_lock_iothread();
3866
    if (ret > 0) {
3867
        IOHandlerRecord **pioh;
3868

    
3869
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3870
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3871
                ioh->fd_read(ioh->opaque);
3872
            }
3873
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3874
                ioh->fd_write(ioh->opaque);
3875
            }
3876
        }
3877

    
3878
        /* remove deleted IO handlers */
3879
        pioh = &first_io_handler;
3880
        while (*pioh) {
3881
            ioh = *pioh;
3882
            if (ioh->deleted) {
3883
                *pioh = ioh->next;
3884
                qemu_free(ioh);
3885
            } else
3886
                pioh = &ioh->next;
3887
        }
3888
    }
3889

    
3890
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3891

    
3892
    /* rearm timer, if not periodic */
3893
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3894
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3895
        qemu_rearm_alarm_timer(alarm_timer);
3896
    }
3897

    
3898
    /* vm time timers */
3899
    if (vm_running) {
3900
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3901
            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3902
                qemu_get_clock(vm_clock));
3903
    }
3904

    
3905
    /* real time timers */
3906
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3907
                    qemu_get_clock(rt_clock));
3908

    
3909
    /* Check bottom-halves last in case any of the earlier events triggered
3910
       them.  */
3911
    qemu_bh_poll();
3912

    
3913
}
3914

    
3915
static int qemu_cpu_exec(CPUState *env)
3916
{
3917
    int ret;
3918
#ifdef CONFIG_PROFILER
3919
    int64_t ti;
3920
#endif
3921

    
3922
#ifdef CONFIG_PROFILER
3923
    ti = profile_getclock();
3924
#endif
3925
    if (use_icount) {
3926
        int64_t count;
3927
        int decr;
3928
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3929
        env->icount_decr.u16.low = 0;
3930
        env->icount_extra = 0;
3931
        count = qemu_next_deadline();
3932
        count = (count + (1 << icount_time_shift) - 1)
3933
                >> icount_time_shift;
3934
        qemu_icount += count;
3935
        decr = (count > 0xffff) ? 0xffff : count;
3936
        count -= decr;
3937
        env->icount_decr.u16.low = decr;
3938
        env->icount_extra = count;
3939
    }
3940
    ret = cpu_exec(env);
3941
#ifdef CONFIG_PROFILER
3942
    qemu_time += profile_getclock() - ti;
3943
#endif
3944
    if (use_icount) {
3945
        /* Fold pending instructions back into the
3946
           instruction counter, and clear the interrupt flag.  */
3947
        qemu_icount -= (env->icount_decr.u16.low
3948
                        + env->icount_extra);
3949
        env->icount_decr.u32 = 0;
3950
        env->icount_extra = 0;
3951
    }
3952
    return ret;
3953
}
3954

    
3955
static void tcg_cpu_exec(void)
3956
{
3957
    int ret = 0;
3958

    
3959
    if (next_cpu == NULL)
3960
        next_cpu = first_cpu;
3961
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
3962
        CPUState *env = cur_cpu = next_cpu;
3963

    
3964
        if (!vm_running)
3965
            break;
3966
        if (timer_alarm_pending) {
3967
            timer_alarm_pending = 0;
3968
            break;
3969
        }
3970
        if (cpu_can_run(env))
3971
            ret = qemu_cpu_exec(env);
3972
        if (ret == EXCP_DEBUG) {
3973
            gdb_set_stop_cpu(env);
3974
            debug_requested = 1;
3975
            break;
3976
        }
3977
    }
3978
}
3979

    
3980
static int cpu_has_work(CPUState *env)
3981
{
3982
    if (env->stop)
3983
        return 1;
3984
    if (env->stopped)
3985
        return 0;
3986
    if (!env->halted)
3987
        return 1;
3988
    if (qemu_cpu_has_work(env))
3989
        return 1;
3990
    return 0;
3991
}
3992

    
3993
static int tcg_has_work(void)
3994
{
3995
    CPUState *env;
3996

    
3997
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3998
        if (cpu_has_work(env))
3999
            return 1;
4000
    return 0;
4001
}
4002

    
4003
static int qemu_calculate_timeout(void)
4004
{
4005
#ifndef CONFIG_IOTHREAD
4006
    int timeout;
4007

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

    
4050
    return timeout;
4051
#else /* CONFIG_IOTHREAD */
4052
    return 1000;
4053
#endif
4054
}
4055

    
4056
static int vm_can_run(void)
4057
{
4058
    if (powerdown_requested)
4059
        return 0;
4060
    if (reset_requested)
4061
        return 0;
4062
    if (shutdown_requested)
4063
        return 0;
4064
    if (debug_requested)
4065
        return 0;
4066
    return 1;
4067
}
4068

    
4069
qemu_irq qemu_system_powerdown;
4070

    
4071
static void main_loop(void)
4072
{
4073
    int r;
4074

    
4075
#ifdef CONFIG_IOTHREAD
4076
    qemu_system_ready = 1;
4077
    qemu_cond_broadcast(&qemu_system_cond);
4078
#endif
4079

    
4080
    for (;;) {
4081
        do {
4082
#ifdef CONFIG_PROFILER
4083
            int64_t ti;
4084
#endif
4085
#ifndef CONFIG_IOTHREAD
4086
            tcg_cpu_exec();
4087
#endif
4088
#ifdef CONFIG_PROFILER
4089
            ti = profile_getclock();
4090
#endif
4091
            main_loop_wait(qemu_calculate_timeout());
4092
#ifdef CONFIG_PROFILER
4093
            dev_time += profile_getclock() - ti;
4094
#endif
4095
        } while (vm_can_run());
4096

    
4097
        if (qemu_debug_requested())
4098
            vm_stop(EXCP_DEBUG);
4099
        if (qemu_shutdown_requested()) {
4100
            if (no_shutdown) {
4101
                vm_stop(0);
4102
                no_shutdown = 0;
4103
            } else
4104
                break;
4105
        }
4106
        if (qemu_reset_requested()) {
4107
            pause_all_vcpus();
4108
            qemu_system_reset();
4109
            resume_all_vcpus();
4110
        }
4111
        if (qemu_powerdown_requested()) {
4112
            qemu_irq_raise(qemu_system_powerdown);
4113
        }
4114
        if ((r = qemu_vmstop_requested()))
4115
            vm_stop(r);
4116
    }
4117
    pause_all_vcpus();
4118
}
4119

    
4120
static void version(void)
4121
{
4122
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4123
}
4124

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

    
4158
#define HAS_ARG 0x0001
4159

    
4160
enum {
4161
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4162
    opt_enum,
4163
#define DEFHEADING(text)
4164
#include "qemu-options.h"
4165
#undef DEF
4166
#undef DEFHEADING
4167
#undef GEN_DOCS
4168
};
4169

    
4170
typedef struct QEMUOption {
4171
    const char *name;
4172
    int flags;
4173
    int index;
4174
} QEMUOption;
4175

    
4176
static const QEMUOption qemu_options[] = {
4177
    { "h", 0, QEMU_OPTION_h },
4178
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4179
    { option, opt_arg, opt_enum },
4180
#define DEFHEADING(text)
4181
#include "qemu-options.h"
4182
#undef DEF
4183
#undef DEFHEADING
4184
#undef GEN_DOCS
4185
    { NULL },
4186
};
4187

    
4188
#ifdef HAS_AUDIO
4189
struct soundhw soundhw[] = {
4190
#ifdef HAS_AUDIO_CHOICE
4191
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4192
    {
4193
        "pcspk",
4194
        "PC speaker",
4195
        0,
4196
        1,
4197
        { .init_isa = pcspk_audio_init }
4198
    },
4199
#endif
4200

    
4201
#ifdef CONFIG_SB16
4202
    {
4203
        "sb16",
4204
        "Creative Sound Blaster 16",
4205
        0,
4206
        1,
4207
        { .init_isa = SB16_init }
4208
    },
4209
#endif
4210

    
4211
#ifdef CONFIG_CS4231A
4212
    {
4213
        "cs4231a",
4214
        "CS4231A",
4215
        0,
4216
        1,
4217
        { .init_isa = cs4231a_init }
4218
    },
4219
#endif
4220

    
4221
#ifdef CONFIG_ADLIB
4222
    {
4223
        "adlib",
4224
#ifdef HAS_YMF262
4225
        "Yamaha YMF262 (OPL3)",
4226
#else
4227
        "Yamaha YM3812 (OPL2)",
4228
#endif
4229
        0,
4230
        1,
4231
        { .init_isa = Adlib_init }
4232
    },
4233
#endif
4234

    
4235
#ifdef CONFIG_GUS
4236
    {
4237
        "gus",
4238
        "Gravis Ultrasound GF1",
4239
        0,
4240
        1,
4241
        { .init_isa = GUS_init }
4242
    },
4243
#endif
4244

    
4245
#ifdef CONFIG_AC97
4246
    {
4247
        "ac97",
4248
        "Intel 82801AA AC97 Audio",
4249
        0,
4250
        0,
4251
        { .init_pci = ac97_init }
4252
    },
4253
#endif
4254

    
4255
#ifdef CONFIG_ES1370
4256
    {
4257
        "es1370",
4258
        "ENSONIQ AudioPCI ES1370",
4259
        0,
4260
        0,
4261
        { .init_pci = es1370_init }
4262
    },
4263
#endif
4264

    
4265
#endif /* HAS_AUDIO_CHOICE */
4266

    
4267
    { NULL, NULL, 0, 0, { NULL } }
4268
};
4269

    
4270
static void select_soundhw (const char *optarg)
4271
{
4272
    struct soundhw *c;
4273

    
4274
    if (*optarg == '?') {
4275
    show_valid_cards:
4276

    
4277
        printf ("Valid sound card names (comma separated):\n");
4278
        for (c = soundhw; c->name; ++c) {
4279
            printf ("%-11s %s\n", c->name, c->descr);
4280
        }
4281
        printf ("\n-soundhw all will enable all of the above\n");
4282
        exit (*optarg != '?');
4283
    }
4284
    else {
4285
        size_t l;
4286
        const char *p;
4287
        char *e;
4288
        int bad_card = 0;
4289

    
4290
        if (!strcmp (optarg, "all")) {
4291
            for (c = soundhw; c->name; ++c) {
4292
                c->enabled = 1;
4293
            }
4294
            return;
4295
        }
4296

    
4297
        p = optarg;
4298
        while (*p) {
4299
            e = strchr (p, ',');
4300
            l = !e ? strlen (p) : (size_t) (e - p);
4301

    
4302
            for (c = soundhw; c->name; ++c) {
4303
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4304
                    c->enabled = 1;
4305
                    break;
4306
                }
4307
            }
4308

    
4309
            if (!c->name) {
4310
                if (l > 80) {
4311
                    fprintf (stderr,
4312
                             "Unknown sound card name (too big to show)\n");
4313
                }
4314
                else {
4315
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4316
                             (int) l, p);
4317
                }
4318
                bad_card = 1;
4319
            }
4320
            p += l + (e != NULL);
4321
        }
4322

    
4323
        if (bad_card)
4324
            goto show_valid_cards;
4325
    }
4326
}
4327
#endif
4328

    
4329
static void select_vgahw (const char *p)
4330
{
4331
    const char *opts;
4332

    
4333
    vga_interface_type = VGA_NONE;
4334
    if (strstart(p, "std", &opts)) {
4335
        vga_interface_type = VGA_STD;
4336
    } else if (strstart(p, "cirrus", &opts)) {
4337
        vga_interface_type = VGA_CIRRUS;
4338
    } else if (strstart(p, "vmware", &opts)) {
4339
        vga_interface_type = VGA_VMWARE;
4340
    } else if (strstart(p, "xenfb", &opts)) {
4341
        vga_interface_type = VGA_XENFB;
4342
    } else if (!strstart(p, "none", &opts)) {
4343
    invalid_vga:
4344
        fprintf(stderr, "Unknown vga type: %s\n", p);
4345
        exit(1);
4346
    }
4347
    while (*opts) {
4348
        const char *nextopt;
4349

    
4350
        if (strstart(opts, ",retrace=", &nextopt)) {
4351
            opts = nextopt;
4352
            if (strstart(opts, "dumb", &nextopt))
4353
                vga_retrace_method = VGA_RETRACE_DUMB;
4354
            else if (strstart(opts, "precise", &nextopt))
4355
                vga_retrace_method = VGA_RETRACE_PRECISE;
4356
            else goto invalid_vga;
4357
        } else goto invalid_vga;
4358
        opts = nextopt;
4359
    }
4360
}
4361

    
4362
#ifdef TARGET_I386
4363
static int balloon_parse(const char *arg)
4364
{
4365
    QemuOpts *opts;
4366

    
4367
    if (strcmp(arg, "none") == 0) {
4368
        return 0;
4369
    }
4370

    
4371
    if (!strncmp(arg, "virtio", 6)) {
4372
        if (arg[6] == ',') {
4373
            /* have params -> parse them */
4374
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4375
            if (!opts)
4376
                return  -1;
4377
        } else {
4378
            /* create empty opts */
4379
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4380
        }
4381
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4382
        return 0;
4383
    }
4384

    
4385
    return -1;
4386
}
4387
#endif
4388

    
4389
#ifdef _WIN32
4390
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4391
{
4392
    exit(STATUS_CONTROL_C_EXIT);
4393
    return TRUE;
4394
}
4395
#endif
4396

    
4397
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4398
{
4399
    int ret;
4400

    
4401
    if(strlen(str) != 36)
4402
        return -1;
4403

    
4404
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4405
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4406
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4407

    
4408
    if(ret != 16)
4409
        return -1;
4410

    
4411
#ifdef TARGET_I386
4412
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4413
#endif
4414

    
4415
    return 0;
4416
}
4417

    
4418
#define MAX_NET_CLIENTS 32
4419

    
4420
#ifndef _WIN32
4421

    
4422
static void termsig_handler(int signal)
4423
{
4424
    qemu_system_shutdown_request();
4425
}
4426

    
4427
static void sigchld_handler(int signal)
4428
{
4429
    waitpid(-1, NULL, WNOHANG);
4430
}
4431

    
4432
static void sighandler_setup(void)
4433
{
4434
    struct sigaction act;
4435

    
4436
    memset(&act, 0, sizeof(act));
4437
    act.sa_handler = termsig_handler;
4438
    sigaction(SIGINT,  &act, NULL);
4439
    sigaction(SIGHUP,  &act, NULL);
4440
    sigaction(SIGTERM, &act, NULL);
4441

    
4442
    act.sa_handler = sigchld_handler;
4443
    act.sa_flags = SA_NOCLDSTOP;
4444
    sigaction(SIGCHLD, &act, NULL);
4445
}
4446

    
4447
#endif
4448

    
4449
#ifdef _WIN32
4450
/* Look for support files in the same directory as the executable.  */
4451
static char *find_datadir(const char *argv0)
4452
{
4453
    char *p;
4454
    char buf[MAX_PATH];
4455
    DWORD len;
4456

    
4457
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4458
    if (len == 0) {
4459
        return NULL;
4460
    }
4461

    
4462
    buf[len] = 0;
4463
    p = buf + len - 1;
4464
    while (p != buf && *p != '\\')
4465
        p--;
4466
    *p = 0;
4467
    if (access(buf, R_OK) == 0) {
4468
        return qemu_strdup(buf);
4469
    }
4470
    return NULL;
4471
}
4472
#else /* !_WIN32 */
4473

    
4474
/* Find a likely location for support files using the location of the binary.
4475
   For installed binaries this will be "$bindir/../share/qemu".  When
4476
   running from the build tree this will be "$bindir/../pc-bios".  */
4477
#define SHARE_SUFFIX "/share/qemu"
4478
#define BUILD_SUFFIX "/pc-bios"
4479
static char *find_datadir(const char *argv0)
4480
{
4481
    char *dir;
4482
    char *p = NULL;
4483
    char *res;
4484
    char buf[PATH_MAX];
4485
    size_t max_len;
4486

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

    
4517
    max_len = strlen(dir) +
4518
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4519
    res = qemu_mallocz(max_len);
4520
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4521
    if (access(res, R_OK)) {
4522
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4523
        if (access(res, R_OK)) {
4524
            qemu_free(res);
4525
            res = NULL;
4526
        }
4527
    }
4528

    
4529
    return res;
4530
}
4531
#undef SHARE_SUFFIX
4532
#undef BUILD_SUFFIX
4533
#endif
4534

    
4535
char *qemu_find_file(int type, const char *name)
4536
{
4537
    int len;
4538
    const char *subdir;
4539
    char *buf;
4540

    
4541
    /* If name contains path separators then try it as a straight path.  */
4542
    if ((strchr(name, '/') || strchr(name, '\\'))
4543
        && access(name, R_OK) == 0) {
4544
        return qemu_strdup(name);
4545
    }
4546
    switch (type) {
4547
    case QEMU_FILE_TYPE_BIOS:
4548
        subdir = "";
4549
        break;
4550
    case QEMU_FILE_TYPE_KEYMAP:
4551
        subdir = "keymaps/";
4552
        break;
4553
    default:
4554
        abort();
4555
    }
4556
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4557
    buf = qemu_mallocz(len);
4558
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4559
    if (access(buf, R_OK)) {
4560
        qemu_free(buf);
4561
        return NULL;
4562
    }
4563
    return buf;
4564
}
4565

    
4566
static int device_init_func(QemuOpts *opts, void *opaque)
4567
{
4568
    DeviceState *dev;
4569

    
4570
    dev = qdev_device_add(opts);
4571
    if (!dev)
4572
        return -1;
4573
    return 0;
4574
}
4575

    
4576
struct device_config {
4577
    enum {
4578
        DEV_USB,       /* -usbdevice   */
4579
        DEV_BT,        /* -bt          */
4580
    } type;
4581
    const char *cmdline;
4582
    QTAILQ_ENTRY(device_config) next;
4583
};
4584
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4585

    
4586
static void add_device_config(int type, const char *cmdline)
4587
{
4588
    struct device_config *conf;
4589

    
4590
    conf = qemu_mallocz(sizeof(*conf));
4591
    conf->type = type;
4592
    conf->cmdline = cmdline;
4593
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4594
}
4595

    
4596
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4597
{
4598
    struct device_config *conf;
4599
    int rc;
4600

    
4601
    QTAILQ_FOREACH(conf, &device_configs, next) {
4602
        if (conf->type != type)
4603
            continue;
4604
        rc = func(conf->cmdline);
4605
        if (0 != rc)
4606
            return rc;
4607
    }
4608
    return 0;
4609
}
4610

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

    
4655
    qemu_errors_to_file(stderr);
4656
    qemu_cache_utils_init(envp);
4657

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

    
4689
    module_call_init(MODULE_INIT_MACHINE);
4690
    machine = find_default_machine();
4691
    cpu_model = NULL;
4692
    initrd_filename = NULL;
4693
    ram_size = 0;
4694
    snapshot = 0;
4695
    kernel_filename = NULL;
4696
    kernel_cmdline = "";
4697
    cyls = heads = secs = 0;
4698
    translation = BIOS_ATA_TRANSLATION_AUTO;
4699

    
4700
    serial_devices[0] = "vc:80Cx24C";
4701
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4702
        serial_devices[i] = NULL;
4703
    serial_device_index = 0;
4704

    
4705
    parallel_devices[0] = "vc:80Cx24C";
4706
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4707
        parallel_devices[i] = NULL;
4708
    parallel_device_index = 0;
4709

    
4710
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4711
        virtio_consoles[i] = NULL;
4712
    virtio_console_index = 0;
4713

    
4714
    monitor_devices[0] = "vc:80Cx24C";
4715
    for (i = 1; i < MAX_MONITOR_DEVICES; i++) {
4716
        monitor_devices[i] = NULL;
4717
    }
4718
    monitor_device_index = 0;
4719

    
4720
    for (i = 0; i < MAX_NODES; i++) {
4721
        node_mem[i] = 0;
4722
        node_cpumask[i] = 0;
4723
    }
4724

    
4725
    nb_net_clients = 0;
4726
    nb_numa_nodes = 0;
4727
    nb_nics = 0;
4728

    
4729
    tb_size = 0;
4730
    autostart= 1;
4731

    
4732
    optind = 1;
4733
    for(;;) {
4734
        if (optind >= argc)
4735
            break;
4736
        r = argv[optind];
4737
        if (r[0] != '-') {
4738
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4739
        } else {
4740
            const QEMUOption *popt;
4741

    
4742
            optind++;
4743
            /* Treat --foo the same as -foo.  */
4744
            if (r[1] == '-')
4745
                r++;
4746
            popt = qemu_options;
4747
            for(;;) {
4748
                if (!popt->name) {
4749
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4750
                            argv[0], r);
4751
                    exit(1);
4752
                }
4753
                if (!strcmp(popt->name, r + 1))
4754
                    break;
4755
                popt++;
4756
            }
4757
            if (popt->flags & HAS_ARG) {
4758
                if (optind >= argc) {
4759
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4760
                            argv[0], r);
4761
                    exit(1);
4762
                }
4763
                optarg = argv[optind++];
4764
            } else {
4765
                optarg = NULL;
4766
            }
4767

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

    
4921
                    if (!strchr(optarg, '=')) {
4922
                        legacy = 1;
4923
                        pstrcpy(buf, sizeof(buf), optarg);
4924
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
4925
                        fprintf(stderr,
4926
                                "qemu: unknown boot parameter '%s' in '%s'\n",
4927
                                buf, optarg);
4928
                        exit(1);
4929
                    }
4930

    
4931
                    if (legacy ||
4932
                        get_param_value(buf, sizeof(buf), "order", optarg)) {
4933
                        boot_devices_bitmap = parse_bootdevices(buf);
4934
                        pstrcpy(boot_devices, sizeof(boot_devices), buf);
4935
                    }
4936
                    if (!legacy) {
4937
                        if (get_param_value(buf, sizeof(buf),
4938
                                            "once", optarg)) {
4939
                            boot_devices_bitmap |= parse_bootdevices(buf);
4940
                            standard_boot_devices = qemu_strdup(boot_devices);
4941
                            pstrcpy(boot_devices, sizeof(boot_devices), buf);
4942
                            qemu_register_reset(restore_boot_devices,
4943
                                                standard_boot_devices);
4944
                        }
4945
                        if (get_param_value(buf, sizeof(buf),
4946
                                            "menu", optarg)) {
4947
                            if (!strcmp(buf, "on")) {
4948
                                boot_menu = 1;
4949
                            } else if (!strcmp(buf, "off")) {
4950
                                boot_menu = 0;
4951
                            } else {
4952
                                fprintf(stderr,
4953
                                        "qemu: invalid option value '%s'\n",
4954
                                        buf);
4955
                                exit(1);
4956
                            }
4957
                        }
4958
                    }
4959
                }
4960
                break;
4961
            case QEMU_OPTION_fda:
4962
            case QEMU_OPTION_fdb:
4963
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4964
                break;
4965
#ifdef TARGET_I386
4966
            case QEMU_OPTION_no_fd_bootchk:
4967
                fd_bootchk = 0;
4968
                break;
4969
#endif
4970
            case QEMU_OPTION_net:
4971
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4972
                    fprintf(stderr, "qemu: too many network clients\n");
4973
                    exit(1);
4974
                }
4975
                net_clients[nb_net_clients] = optarg;
4976
                nb_net_clients++;
4977
                break;
4978
#ifdef CONFIG_SLIRP
4979
            case QEMU_OPTION_tftp:
4980
                legacy_tftp_prefix = optarg;
4981
                break;
4982
            case QEMU_OPTION_bootp:
4983
                legacy_bootp_filename = optarg;