Statistics
| Branch: | Revision:

root / vl.c @ bf65f53f

History | View | Annotate | Download (156 kB)

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

    
32
/* Needed early for HOST_BSD etc. */
33
#include "config-host.h"
34
/* Needed early to override system queue definitions on BSD */
35
#include "sys-queue.h"
36

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

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

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

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

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

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

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

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

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

    
166
#include "disas.h"
167

    
168
#include "exec-all.h"
169

    
170
#include "qemu_socket.h"
171

    
172
#include "slirp/libslirp.h"
173

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

    
177
#define DEFAULT_RAM_SIZE 128
178

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

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

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

    
272
uint8_t qemu_uuid[16];
273

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

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

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

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

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

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

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

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

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

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

    
344
/***********************************************************/
345
/* keyboard/mouse */
346

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

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

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

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

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

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

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

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

    
384
    return s;
385
}
386

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

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

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

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

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

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

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

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

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

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

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

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

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

    
461
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
462
}
463

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

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

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

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

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

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

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

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

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

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

    
534
#define QEMU_TIMER_BASE 1000000000LL
535

    
536
#ifdef WIN32
537

    
538
static int64_t clock_freq;
539

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

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

    
559
#else
560

    
561
static int use_rt_clock;
562

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

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

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

    
611
/***********************************************************/
612
/* guest cycle counter */
613

    
614
static int64_t cpu_ticks_prev;
615
static int64_t cpu_ticks_offset;
616
static int64_t cpu_clock_offset;
617
static int cpu_ticks_enabled;
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 (!cpu_ticks_enabled) {
626
        return cpu_ticks_offset;
627
    } else {
628
        int64_t ticks;
629
        ticks = cpu_get_real_ticks();
630
        if (cpu_ticks_prev > ticks) {
631
            /* Note: non increasing ticks may happen if the host uses
632
               software suspend */
633
            cpu_ticks_offset += cpu_ticks_prev - ticks;
634
        }
635
        cpu_ticks_prev = ticks;
636
        return ticks + 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 (!cpu_ticks_enabled) {
645
        return cpu_clock_offset;
646
    } else {
647
        ti = get_clock();
648
        return ti + cpu_clock_offset;
649
    }
650
}
651

    
652
/* enable cpu_get_ticks() */
653
void cpu_enable_ticks(void)
654
{
655
    if (!cpu_ticks_enabled) {
656
        cpu_ticks_offset -= cpu_get_real_ticks();
657
        cpu_clock_offset -= get_clock();
658
        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 (cpu_ticks_enabled) {
667
        cpu_ticks_offset = cpu_get_ticks();
668
        cpu_clock_offset = cpu_get_clock();
669
        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 (QEMU_TIMER_BASE / 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) + QEMU_TIMER_BASE / 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) + QEMU_TIMER_BASE / 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 = 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
    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
static inline 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
    ticks_per_sec = QEMU_TIMER_BASE;
1041
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1042
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1043
}
1044

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

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

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

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

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

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

    
1095
static void qemu_event_increment(void);
1096

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

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

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

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

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

    
1174
    return delta;
1175
}
1176

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

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

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

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

    
1198
    return delta;
1199
}
1200
#endif
1201

    
1202
#ifndef _WIN32
1203

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

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

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

    
1216
    return 0;
1217
}
1218

    
1219
#if defined(__linux__)
1220

    
1221
#define RTC_FREQ 1024
1222

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

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

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

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

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

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

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

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

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

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

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

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

    
1283
    close(fd);
1284
}
1285

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

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

    
1308
    enable_sigio_timer(rtc_fd);
1309

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

    
1312
    return 0;
1313
}
1314

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

    
1319
    close(rtc_fd);
1320
}
1321

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

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

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

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

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

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

    
1349
        return -1;
1350
    }
1351

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

    
1354
    return 0;
1355
}
1356

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

    
1361
    timer_delete(host_timer);
1362
}
1363

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

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

    
1375
    nearest_delta_us = qemu_next_deadline_dyntick();
1376

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

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

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

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

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

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

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

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

    
1423
    return 0;
1424
}
1425

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

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

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

    
1436

    
1437
#ifdef _WIN32
1438

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

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

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

    
1451
    timeBeginPeriod(data->period);
1452

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

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

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

    
1471
    return 0;
1472
}
1473

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

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

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

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

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

    
1494
    timeKillEvent(data->timerId);
1495

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

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

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

    
1510
#endif /* _WIN32 */
1511

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

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

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

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

    
1530
    alarm_timer = t;
1531

    
1532
    return 0;
1533

    
1534
fail:
1535
    return err;
1536
}
1537

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

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

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

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

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

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

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

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

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

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

    
1603
/***********************************************************/
1604
/* Bluetooth support */
1605
static int nb_hcis;
1606
static int cur_hci;
1607
static struct HCIInfo *hci_table[MAX_NICS];
1608

    
1609
static struct bt_vlan_s {
1610
    struct bt_scatternet_s net;
1611
    int id;
1612
    struct bt_vlan_s *next;
1613
} *first_bt_vlan;
1614

    
1615
/* find or alloc a new bluetooth "VLAN" */
1616
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1617
{
1618
    struct bt_vlan_s **pvlan, *vlan;
1619
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1620
        if (vlan->id == id)
1621
            return &vlan->net;
1622
    }
1623
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1624
    vlan->id = id;
1625
    pvlan = &first_bt_vlan;
1626
    while (*pvlan != NULL)
1627
        pvlan = &(*pvlan)->next;
1628
    *pvlan = vlan;
1629
    return &vlan->net;
1630
}
1631

    
1632
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1633
{
1634
}
1635

    
1636
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1637
{
1638
    return -ENOTSUP;
1639
}
1640

    
1641
static struct HCIInfo null_hci = {
1642
    .cmd_send = null_hci_send,
1643
    .sco_send = null_hci_send,
1644
    .acl_send = null_hci_send,
1645
    .bdaddr_set = null_hci_addr_set,
1646
};
1647

    
1648
struct HCIInfo *qemu_next_hci(void)
1649
{
1650
    if (cur_hci == nb_hcis)
1651
        return &null_hci;
1652

    
1653
    return hci_table[cur_hci++];
1654
}
1655

    
1656
static struct HCIInfo *hci_init(const char *str)
1657
{
1658
    char *endp;
1659
    struct bt_scatternet_s *vlan = 0;
1660

    
1661
    if (!strcmp(str, "null"))
1662
        /* null */
1663
        return &null_hci;
1664
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1665
        /* host[:hciN] */
1666
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1667
    else if (!strncmp(str, "hci", 3)) {
1668
        /* hci[,vlan=n] */
1669
        if (str[3]) {
1670
            if (!strncmp(str + 3, ",vlan=", 6)) {
1671
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1672
                if (*endp)
1673
                    vlan = 0;
1674
            }
1675
        } else
1676
            vlan = qemu_find_bt_vlan(0);
1677
        if (vlan)
1678
           return bt_new_hci(vlan);
1679
    }
1680

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

    
1683
    return 0;
1684
}
1685

    
1686
static int bt_hci_parse(const char *str)
1687
{
1688
    struct HCIInfo *hci;
1689
    bdaddr_t bdaddr;
1690

    
1691
    if (nb_hcis >= MAX_NICS) {
1692
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1693
        return -1;
1694
    }
1695

    
1696
    hci = hci_init(str);
1697
    if (!hci)
1698
        return -1;
1699

    
1700
    bdaddr.b[0] = 0x52;
1701
    bdaddr.b[1] = 0x54;
1702
    bdaddr.b[2] = 0x00;
1703
    bdaddr.b[3] = 0x12;
1704
    bdaddr.b[4] = 0x34;
1705
    bdaddr.b[5] = 0x56 + nb_hcis;
1706
    hci->bdaddr_set(hci, bdaddr.b);
1707

    
1708
    hci_table[nb_hcis++] = hci;
1709

    
1710
    return 0;
1711
}
1712

    
1713
static void bt_vhci_add(int vlan_id)
1714
{
1715
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1716

    
1717
    if (!vlan->slave)
1718
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1719
                        "an empty scatternet %i\n", vlan_id);
1720

    
1721
    bt_vhci_init(bt_new_hci(vlan));
1722
}
1723

    
1724
static struct bt_device_s *bt_device_add(const char *opt)
1725
{
1726
    struct bt_scatternet_s *vlan;
1727
    int vlan_id = 0;
1728
    char *endp = strstr(opt, ",vlan=");
1729
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1730
    char devname[10];
1731

    
1732
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1733

    
1734
    if (endp) {
1735
        vlan_id = strtol(endp + 6, &endp, 0);
1736
        if (*endp) {
1737
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1738
            return 0;
1739
        }
1740
    }
1741

    
1742
    vlan = qemu_find_bt_vlan(vlan_id);
1743

    
1744
    if (!vlan->slave)
1745
        fprintf(stderr, "qemu: warning: adding a slave device to "
1746
                        "an empty scatternet %i\n", vlan_id);
1747

    
1748
    if (!strcmp(devname, "keyboard"))
1749
        return bt_keyboard_init(vlan);
1750

    
1751
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1752
    return 0;
1753
}
1754

    
1755
static int bt_parse(const char *opt)
1756
{
1757
    const char *endp, *p;
1758
    int vlan;
1759

    
1760
    if (strstart(opt, "hci", &endp)) {
1761
        if (!*endp || *endp == ',') {
1762
            if (*endp)
1763
                if (!strstart(endp, ",vlan=", 0))
1764
                    opt = endp + 1;
1765

    
1766
            return bt_hci_parse(opt);
1767
       }
1768
    } else if (strstart(opt, "vhci", &endp)) {
1769
        if (!*endp || *endp == ',') {
1770
            if (*endp) {
1771
                if (strstart(endp, ",vlan=", &p)) {
1772
                    vlan = strtol(p, (char **) &endp, 0);
1773
                    if (*endp) {
1774
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1775
                        return 1;
1776
                    }
1777
                } else {
1778
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1779
                    return 1;
1780
                }
1781
            } else
1782
                vlan = 0;
1783

    
1784
            bt_vhci_add(vlan);
1785
            return 0;
1786
        }
1787
    } else if (strstart(opt, "device:", &endp))
1788
        return !bt_device_add(endp);
1789

    
1790
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1791
    return 1;
1792
}
1793

    
1794
/***********************************************************/
1795
/* QEMU Block devices */
1796

    
1797
#define HD_ALIAS "index=%d,media=disk"
1798
#define CDROM_ALIAS "index=2,media=cdrom"
1799
#define FD_ALIAS "index=%d,if=floppy"
1800
#define PFLASH_ALIAS "if=pflash"
1801
#define MTD_ALIAS "if=mtd"
1802
#define SD_ALIAS "index=0,if=sd"
1803

    
1804
static QemuOptsList drive_opt_list = {
1805
    .name = "drive",
1806
    .head = TAILQ_HEAD_INITIALIZER(drive_opt_list.head),
1807
    .desc = {
1808
        {
1809
            .name = "bus",
1810
            .type = QEMU_OPT_NUMBER,
1811
            .help = "bus number",
1812
        },{
1813
            .name = "unit",
1814
            .type = QEMU_OPT_NUMBER,
1815
            .help = "unit number (i.e. lun for scsi)",
1816
        },{
1817
            .name = "if",
1818
            .type = QEMU_OPT_STRING,
1819
            .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1820
        },{
1821
            .name = "index",
1822
            .type = QEMU_OPT_NUMBER,
1823
        },{
1824
            .name = "cyls",
1825
            .type = QEMU_OPT_NUMBER,
1826
            .help = "number of cylinders (ide disk geometry)",
1827
        },{
1828
            .name = "heads",
1829
            .type = QEMU_OPT_NUMBER,
1830
            .help = "number of heads (ide disk geometry)",
1831
        },{
1832
            .name = "secs",
1833
            .type = QEMU_OPT_NUMBER,
1834
            .help = "number of sectors (ide disk geometry)",
1835
        },{
1836
            .name = "trans",
1837
            .type = QEMU_OPT_STRING,
1838
            .help = "chs translation (auto, lba. none)",
1839
        },{
1840
            .name = "media",
1841
            .type = QEMU_OPT_STRING,
1842
            .help = "media type (disk, cdrom)",
1843
        },{
1844
            .name = "snapshot",
1845
            .type = QEMU_OPT_BOOL,
1846
        },{
1847
            .name = "file",
1848
            .type = QEMU_OPT_STRING,
1849
            .help = "disk image",
1850
        },{
1851
            .name = "cache",
1852
            .type = QEMU_OPT_STRING,
1853
            .help = "host cache usage (none, writeback, writethrough)",
1854
        },{
1855
            .name = "format",
1856
            .type = QEMU_OPT_STRING,
1857
            .help = "disk format (raw, qcow2, ...)",
1858
        },{
1859
            .name = "serial",
1860
            .type = QEMU_OPT_STRING,
1861
        },{
1862
            .name = "werror",
1863
            .type = QEMU_OPT_STRING,
1864
        },{
1865
            .name = "addr",
1866
            .type = QEMU_OPT_STRING,
1867
            .help = "pci address (virtio only)",
1868
        },
1869
        { /* end if list */ }
1870
    },
1871
};
1872

    
1873
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1874
{
1875
    va_list ap;
1876
    char optstr[1024];
1877
    QemuOpts *opts;
1878

    
1879
    va_start(ap, fmt);
1880
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1881
    va_end(ap);
1882

    
1883
    opts = qemu_opts_parse(&drive_opt_list, optstr, NULL);
1884
    if (!opts) {
1885
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1886
                __FUNCTION__, optstr);
1887
        return NULL;
1888
    }
1889
    if (file)
1890
        qemu_opt_set(opts, "file", file);
1891
    return opts;
1892
}
1893

    
1894
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1895
{
1896
    DriveInfo *dinfo;
1897

    
1898
    /* seek interface, bus and unit */
1899

    
1900
    TAILQ_FOREACH(dinfo, &drives, next) {
1901
        if (dinfo->type == type &&
1902
            dinfo->bus == bus &&
1903
            dinfo->unit == unit)
1904
            return dinfo;
1905
    }
1906

    
1907
    return NULL;
1908
}
1909

    
1910
DriveInfo *drive_get_by_id(char *id)
1911
{
1912
    DriveInfo *dinfo;
1913

    
1914
    TAILQ_FOREACH(dinfo, &drives, next) {
1915
        if (strcmp(id, dinfo->id))
1916
            continue;
1917
        return dinfo;
1918
    }
1919
    return NULL;
1920
}
1921

    
1922
int drive_get_max_bus(BlockInterfaceType type)
1923
{
1924
    int max_bus;
1925
    DriveInfo *dinfo;
1926

    
1927
    max_bus = -1;
1928
    TAILQ_FOREACH(dinfo, &drives, next) {
1929
        if(dinfo->type == type &&
1930
           dinfo->bus > max_bus)
1931
            max_bus = dinfo->bus;
1932
    }
1933
    return max_bus;
1934
}
1935

    
1936
const char *drive_get_serial(BlockDriverState *bdrv)
1937
{
1938
    DriveInfo *dinfo;
1939

    
1940
    TAILQ_FOREACH(dinfo, &drives, next) {
1941
        if (dinfo->bdrv == bdrv)
1942
            return dinfo->serial;
1943
    }
1944

    
1945
    return "\0";
1946
}
1947

    
1948
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
1949
{
1950
    DriveInfo *dinfo;
1951

    
1952
    TAILQ_FOREACH(dinfo, &drives, next) {
1953
        if (dinfo->bdrv == bdrv)
1954
            return dinfo->onerror;
1955
    }
1956

    
1957
    return BLOCK_ERR_STOP_ENOSPC;
1958
}
1959

    
1960
static void bdrv_format_print(void *opaque, const char *name)
1961
{
1962
    fprintf(stderr, " %s", name);
1963
}
1964

    
1965
void drive_uninit(BlockDriverState *bdrv)
1966
{
1967
    DriveInfo *dinfo;
1968

    
1969
    TAILQ_FOREACH(dinfo, &drives, next) {
1970
        if (dinfo->bdrv != bdrv)
1971
            continue;
1972
        qemu_opts_del(dinfo->opts);
1973
        TAILQ_REMOVE(&drives, dinfo, next);
1974
        qemu_free(dinfo);
1975
        break;
1976
    }
1977
}
1978

    
1979
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
1980
                      int *fatal_error)
1981
{
1982
    const char *buf;
1983
    const char *file = NULL;
1984
    char devname[128];
1985
    const char *serial;
1986
    const char *mediastr = "";
1987
    BlockInterfaceType type;
1988
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1989
    int bus_id, unit_id;
1990
    int cyls, heads, secs, translation;
1991
    BlockDriver *drv = NULL;
1992
    QEMUMachine *machine = opaque;
1993
    int max_devs;
1994
    int index;
1995
    int cache;
1996
    int bdrv_flags, onerror;
1997
    const char *devaddr;
1998
    DriveInfo *dinfo;
1999
    int snapshot = 0;
2000

    
2001
    *fatal_error = 1;
2002

    
2003
    translation = BIOS_ATA_TRANSLATION_AUTO;
2004
    cache = 1;
2005

    
2006
    if (machine->use_scsi) {
2007
        type = IF_SCSI;
2008
        max_devs = MAX_SCSI_DEVS;
2009
        pstrcpy(devname, sizeof(devname), "scsi");
2010
    } else {
2011
        type = IF_IDE;
2012
        max_devs = MAX_IDE_DEVS;
2013
        pstrcpy(devname, sizeof(devname), "ide");
2014
    }
2015
    media = MEDIA_DISK;
2016

    
2017
    /* extract parameters */
2018
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
2019
    unit_id = qemu_opt_get_number(opts, "unit", -1);
2020
    index   = qemu_opt_get_number(opts, "index", -1);
2021

    
2022
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
2023
    heads = qemu_opt_get_number(opts, "heads", 0);
2024
    secs  = qemu_opt_get_number(opts, "secs", 0);
2025

    
2026
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2027

    
2028
    file = qemu_opt_get(opts, "file");
2029
    serial = qemu_opt_get(opts, "serial");
2030

    
2031
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2032
        pstrcpy(devname, sizeof(devname), buf);
2033
        if (!strcmp(buf, "ide")) {
2034
            type = IF_IDE;
2035
            max_devs = MAX_IDE_DEVS;
2036
        } else if (!strcmp(buf, "scsi")) {
2037
            type = IF_SCSI;
2038
            max_devs = MAX_SCSI_DEVS;
2039
        } else if (!strcmp(buf, "floppy")) {
2040
            type = IF_FLOPPY;
2041
            max_devs = 0;
2042
        } else if (!strcmp(buf, "pflash")) {
2043
            type = IF_PFLASH;
2044
            max_devs = 0;
2045
        } else if (!strcmp(buf, "mtd")) {
2046
            type = IF_MTD;
2047
            max_devs = 0;
2048
        } else if (!strcmp(buf, "sd")) {
2049
            type = IF_SD;
2050
            max_devs = 0;
2051
        } else if (!strcmp(buf, "virtio")) {
2052
            type = IF_VIRTIO;
2053
            max_devs = 0;
2054
        } else if (!strcmp(buf, "xen")) {
2055
            type = IF_XEN;
2056
            max_devs = 0;
2057
        } else {
2058
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2059
            return NULL;
2060
        }
2061
    }
2062

    
2063
    if (cyls || heads || secs) {
2064
        if (cyls < 1 || cyls > 16383) {
2065
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2066
            return NULL;
2067
        }
2068
        if (heads < 1 || heads > 16) {
2069
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2070
            return NULL;
2071
        }
2072
        if (secs < 1 || secs > 63) {
2073
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2074
            return NULL;
2075
        }
2076
    }
2077

    
2078
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2079
        if (!cyls) {
2080
            fprintf(stderr,
2081
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2082
                    buf);
2083
            return NULL;
2084
        }
2085
        if (!strcmp(buf, "none"))
2086
            translation = BIOS_ATA_TRANSLATION_NONE;
2087
        else if (!strcmp(buf, "lba"))
2088
            translation = BIOS_ATA_TRANSLATION_LBA;
2089
        else if (!strcmp(buf, "auto"))
2090
            translation = BIOS_ATA_TRANSLATION_AUTO;
2091
        else {
2092
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2093
            return NULL;
2094
        }
2095
    }
2096

    
2097
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2098
        if (!strcmp(buf, "disk")) {
2099
            media = MEDIA_DISK;
2100
        } else if (!strcmp(buf, "cdrom")) {
2101
            if (cyls || secs || heads) {
2102
                fprintf(stderr,
2103
                        "qemu: '%s' invalid physical CHS format\n", buf);
2104
                return NULL;
2105
            }
2106
            media = MEDIA_CDROM;
2107
        } else {
2108
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2109
            return NULL;
2110
        }
2111
    }
2112

    
2113
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2114
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2115
            cache = 0;
2116
        else if (!strcmp(buf, "writethrough"))
2117
            cache = 1;
2118
        else if (!strcmp(buf, "writeback"))
2119
            cache = 2;
2120
        else {
2121
           fprintf(stderr, "qemu: invalid cache option\n");
2122
           return NULL;
2123
        }
2124
    }
2125

    
2126
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2127
       if (strcmp(buf, "?") == 0) {
2128
            fprintf(stderr, "qemu: Supported formats:");
2129
            bdrv_iterate_format(bdrv_format_print, NULL);
2130
            fprintf(stderr, "\n");
2131
            return NULL;
2132
        }
2133
        drv = bdrv_find_format(buf);
2134
        if (!drv) {
2135
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2136
            return NULL;
2137
        }
2138
    }
2139

    
2140
    onerror = BLOCK_ERR_STOP_ENOSPC;
2141
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2142
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2143
            fprintf(stderr, "werror is no supported by this format\n");
2144
            return NULL;
2145
        }
2146
        if (!strcmp(buf, "ignore"))
2147
            onerror = BLOCK_ERR_IGNORE;
2148
        else if (!strcmp(buf, "enospc"))
2149
            onerror = BLOCK_ERR_STOP_ENOSPC;
2150
        else if (!strcmp(buf, "stop"))
2151
            onerror = BLOCK_ERR_STOP_ANY;
2152
        else if (!strcmp(buf, "report"))
2153
            onerror = BLOCK_ERR_REPORT;
2154
        else {
2155
            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2156
            return NULL;
2157
        }
2158
    }
2159

    
2160
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2161
        if (type != IF_VIRTIO) {
2162
            fprintf(stderr, "addr is not supported\n");
2163
            return NULL;
2164
        }
2165
    }
2166

    
2167
    /* compute bus and unit according index */
2168

    
2169
    if (index != -1) {
2170
        if (bus_id != 0 || unit_id != -1) {
2171
            fprintf(stderr,
2172
                    "qemu: index cannot be used with bus and unit\n");
2173
            return NULL;
2174
        }
2175
        if (max_devs == 0)
2176
        {
2177
            unit_id = index;
2178
            bus_id = 0;
2179
        } else {
2180
            unit_id = index % max_devs;
2181
            bus_id = index / max_devs;
2182
        }
2183
    }
2184

    
2185
    /* if user doesn't specify a unit_id,
2186
     * try to find the first free
2187
     */
2188

    
2189
    if (unit_id == -1) {
2190
       unit_id = 0;
2191
       while (drive_get(type, bus_id, unit_id) != NULL) {
2192
           unit_id++;
2193
           if (max_devs && unit_id >= max_devs) {
2194
               unit_id -= max_devs;
2195
               bus_id++;
2196
           }
2197
       }
2198
    }
2199

    
2200
    /* check unit id */
2201

    
2202
    if (max_devs && unit_id >= max_devs) {
2203
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2204
                unit_id, max_devs - 1);
2205
        return NULL;
2206
    }
2207

    
2208
    /*
2209
     * ignore multiple definitions
2210
     */
2211

    
2212
    if (drive_get(type, bus_id, unit_id) != NULL) {
2213
        *fatal_error = 0;
2214
        return NULL;
2215
    }
2216

    
2217
    /* init */
2218

    
2219
    dinfo = qemu_mallocz(sizeof(*dinfo));
2220
    if ((buf = qemu_opt_get(opts, "id")) != NULL) {
2221
        dinfo->id = qemu_strdup(buf);
2222
    } else {
2223
        /* no id supplied -> create one */
2224
        dinfo->id = qemu_mallocz(32);
2225
        if (type == IF_IDE || type == IF_SCSI)
2226
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2227
        if (max_devs)
2228
            snprintf(dinfo->id, 32, "%s%i%s%i",
2229
                     devname, bus_id, mediastr, unit_id);
2230
        else
2231
            snprintf(dinfo->id, 32, "%s%s%i",
2232
                     devname, mediastr, unit_id);
2233
    }
2234
    dinfo->bdrv = bdrv_new(dinfo->id);
2235
    dinfo->devaddr = devaddr;
2236
    dinfo->type = type;
2237
    dinfo->bus = bus_id;
2238
    dinfo->unit = unit_id;
2239
    dinfo->onerror = onerror;
2240
    dinfo->opts = opts;
2241
    if (serial)
2242
        strncpy(dinfo->serial, serial, sizeof(serial));
2243
    TAILQ_INSERT_TAIL(&drives, dinfo, next);
2244

    
2245
    switch(type) {
2246
    case IF_IDE:
2247
    case IF_SCSI:
2248
    case IF_XEN:
2249
        switch(media) {
2250
        case MEDIA_DISK:
2251
            if (cyls != 0) {
2252
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2253
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2254
            }
2255
            break;
2256
        case MEDIA_CDROM:
2257
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2258
            break;
2259
        }
2260
        break;
2261
    case IF_SD:
2262
        /* FIXME: This isn't really a floppy, but it's a reasonable
2263
           approximation.  */
2264
    case IF_FLOPPY:
2265
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2266
        break;
2267
    case IF_PFLASH:
2268
    case IF_MTD:
2269
    case IF_VIRTIO:
2270
        break;
2271
    case IF_COUNT:
2272
        abort();
2273
    }
2274
    if (!file) {
2275
        *fatal_error = 0;
2276
        return NULL;
2277
    }
2278
    bdrv_flags = 0;
2279
    if (snapshot) {
2280
        bdrv_flags |= BDRV_O_SNAPSHOT;
2281
        cache = 2; /* always use write-back with snapshot */
2282
    }
2283
    if (cache == 0) /* no caching */
2284
        bdrv_flags |= BDRV_O_NOCACHE;
2285
    else if (cache == 2) /* write-back */
2286
        bdrv_flags |= BDRV_O_CACHE_WB;
2287
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2288
        fprintf(stderr, "qemu: could not open disk image %s\n",
2289
                        file);
2290
        return NULL;
2291
    }
2292
    if (bdrv_key_required(dinfo->bdrv))
2293
        autostart = 0;
2294
    *fatal_error = 0;
2295
    return dinfo;
2296
}
2297

    
2298
static int drive_init_func(QemuOpts *opts, void *opaque)
2299
{
2300
    QEMUMachine *machine = opaque;
2301
    int fatal_error = 0;
2302

    
2303
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2304
        if (fatal_error)
2305
            return 1;
2306
    }
2307
    return 0;
2308
}
2309

    
2310
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2311
{
2312
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2313
        qemu_opt_set(opts, "snapshot", "on");
2314
    }
2315
    return 0;
2316
}
2317

    
2318
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2319
{
2320
    boot_set_handler = func;
2321
    boot_set_opaque = opaque;
2322
}
2323

    
2324
int qemu_boot_set(const char *boot_devices)
2325
{
2326
    if (!boot_set_handler) {
2327
        return -EINVAL;
2328
    }
2329
    return boot_set_handler(boot_set_opaque, boot_devices);
2330
}
2331

    
2332
static int parse_bootdevices(char *devices)
2333
{
2334
    /* We just do some generic consistency checks */
2335
    const char *p;
2336
    int bitmap = 0;
2337

    
2338
    for (p = devices; *p != '\0'; p++) {
2339
        /* Allowed boot devices are:
2340
         * a-b: floppy disk drives
2341
         * c-f: IDE disk drives
2342
         * g-m: machine implementation dependant drives
2343
         * n-p: network devices
2344
         * It's up to each machine implementation to check if the given boot
2345
         * devices match the actual hardware implementation and firmware
2346
         * features.
2347
         */
2348
        if (*p < 'a' || *p > 'p') {
2349
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2350
            exit(1);
2351
        }
2352
        if (bitmap & (1 << (*p - 'a'))) {
2353
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2354
            exit(1);
2355
        }
2356
        bitmap |= 1 << (*p - 'a');
2357
    }
2358
    return bitmap;
2359
}
2360

    
2361
static void restore_boot_devices(void *opaque)
2362
{
2363
    char *standard_boot_devices = opaque;
2364

    
2365
    qemu_boot_set(standard_boot_devices);
2366

    
2367
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2368
    qemu_free(standard_boot_devices);
2369
}
2370

    
2371
static void numa_add(const char *optarg)
2372
{
2373
    char option[128];
2374
    char *endptr;
2375
    unsigned long long value, endvalue;
2376
    int nodenr;
2377

    
2378
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2379
    if (!strcmp(option, "node")) {
2380
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2381
            nodenr = nb_numa_nodes;
2382
        } else {
2383
            nodenr = strtoull(option, NULL, 10);
2384
        }
2385

    
2386
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2387
            node_mem[nodenr] = 0;
2388
        } else {
2389
            value = strtoull(option, &endptr, 0);
2390
            switch (*endptr) {
2391
            case 0: case 'M': case 'm':
2392
                value <<= 20;
2393
                break;
2394
            case 'G': case 'g':
2395
                value <<= 30;
2396
                break;
2397
            }
2398
            node_mem[nodenr] = value;
2399
        }
2400
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2401
            node_cpumask[nodenr] = 0;
2402
        } else {
2403
            value = strtoull(option, &endptr, 10);
2404
            if (value >= 64) {
2405
                value = 63;
2406
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2407
            } else {
2408
                if (*endptr == '-') {
2409
                    endvalue = strtoull(endptr+1, &endptr, 10);
2410
                    if (endvalue >= 63) {
2411
                        endvalue = 62;
2412
                        fprintf(stderr,
2413
                            "only 63 CPUs in NUMA mode supported.\n");
2414
                    }
2415
                    value = (1 << (endvalue + 1)) - (1 << value);
2416
                } else {
2417
                    value = 1 << value;
2418
                }
2419
            }
2420
            node_cpumask[nodenr] = value;
2421
        }
2422
        nb_numa_nodes++;
2423
    }
2424
    return;
2425
}
2426

    
2427
/***********************************************************/
2428
/* USB devices */
2429

    
2430
static USBPort *used_usb_ports;
2431
static USBPort *free_usb_ports;
2432

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

    
2444
int usb_device_add_dev(USBDevice *dev)
2445
{
2446
    USBPort *port;
2447

    
2448
    /* Find a USB port to add the device to.  */
2449
    port = free_usb_ports;
2450
    if (!port->next) {
2451
        USBDevice *hub;
2452

    
2453
        /* Create a new hub and chain it on.  */
2454
        free_usb_ports = NULL;
2455
        port->next = used_usb_ports;
2456
        used_usb_ports = port;
2457

    
2458
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2459
        usb_attach(port, hub);
2460
        port = free_usb_ports;
2461
    }
2462

    
2463
    free_usb_ports = port->next;
2464
    port->next = used_usb_ports;
2465
    used_usb_ports = port;
2466
    usb_attach(port, dev);
2467
    return 0;
2468
}
2469

    
2470
static void usb_msd_password_cb(void *opaque, int err)
2471
{
2472
    USBDevice *dev = opaque;
2473

    
2474
    if (!err)
2475
        usb_device_add_dev(dev);
2476
    else
2477
        dev->handle_destroy(dev);
2478
}
2479

    
2480
static int usb_device_add(const char *devname, int is_hotplug)
2481
{
2482
    const char *p;
2483
    USBDevice *dev;
2484

    
2485
    if (!free_usb_ports)
2486
        return -1;
2487

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

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

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

    
2535
    return usb_device_add_dev(dev);
2536
}
2537

    
2538
int usb_device_del_addr(int bus_num, int addr)
2539
{
2540
    USBPort *port;
2541
    USBPort **lastp;
2542
    USBDevice *dev;
2543

    
2544
    if (!used_usb_ports)
2545
        return -1;
2546

    
2547
    if (bus_num != 0)
2548
        return -1;
2549

    
2550
    lastp = &used_usb_ports;
2551
    port = used_usb_ports;
2552
    while (port && port->dev->addr != addr) {
2553
        lastp = &port->next;
2554
        port = port->next;
2555
    }
2556

    
2557
    if (!port)
2558
        return -1;
2559

    
2560
    dev = port->dev;
2561
    *lastp = port->next;
2562
    usb_attach(port, NULL);
2563
    dev->handle_destroy(dev);
2564
    port->next = free_usb_ports;
2565
    free_usb_ports = port;
2566
    return 0;
2567
}
2568

    
2569
static int usb_device_del(const char *devname)
2570
{
2571
    int bus_num, addr;
2572
    const char *p;
2573

    
2574
    if (strstart(devname, "host:", &p))
2575
        return usb_host_device_close(p);
2576

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

    
2580
    p = strchr(devname, '.');
2581
    if (!p)
2582
        return -1;
2583
    bus_num = strtoul(devname, NULL, 0);
2584
    addr = strtoul(p + 1, NULL, 0);
2585

    
2586
    return usb_device_del_addr(bus_num, addr);
2587
}
2588

    
2589
static int usb_parse(const char *cmdline)
2590
{
2591
    return usb_device_add(cmdline, 0);
2592
}
2593

    
2594
void do_usb_add(Monitor *mon, const char *devname)
2595
{
2596
    usb_device_add(devname, 1);
2597
}
2598

    
2599
void do_usb_del(Monitor *mon, const char *devname)
2600
{
2601
    usb_device_del(devname);
2602
}
2603

    
2604
void usb_info(Monitor *mon)
2605
{
2606
    USBDevice *dev;
2607
    USBPort *port;
2608
    const char *speed_str;
2609

    
2610
    if (!usb_enabled) {
2611
        monitor_printf(mon, "USB support not enabled\n");
2612
        return;
2613
    }
2614

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

    
2638
/***********************************************************/
2639
/* PCMCIA/Cardbus */
2640

    
2641
static struct pcmcia_socket_entry_s {
2642
    PCMCIASocket *socket;
2643
    struct pcmcia_socket_entry_s *next;
2644
} *pcmcia_sockets = 0;
2645

    
2646
void pcmcia_socket_register(PCMCIASocket *socket)
2647
{
2648
    struct pcmcia_socket_entry_s *entry;
2649

    
2650
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2651
    entry->socket = socket;
2652
    entry->next = pcmcia_sockets;
2653
    pcmcia_sockets = entry;
2654
}
2655

    
2656
void pcmcia_socket_unregister(PCMCIASocket *socket)
2657
{
2658
    struct pcmcia_socket_entry_s *entry, **ptr;
2659

    
2660
    ptr = &pcmcia_sockets;
2661
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2662
        if (entry->socket == socket) {
2663
            *ptr = entry->next;
2664
            qemu_free(entry);
2665
        }
2666
}
2667

    
2668
void pcmcia_info(Monitor *mon)
2669
{
2670
    struct pcmcia_socket_entry_s *iter;
2671

    
2672
    if (!pcmcia_sockets)
2673
        monitor_printf(mon, "No PCMCIA sockets\n");
2674

    
2675
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2676
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2677
                       iter->socket->attached ? iter->socket->card_string :
2678
                       "Empty");
2679
}
2680

    
2681
/***********************************************************/
2682
/* register display */
2683

    
2684
struct DisplayAllocator default_allocator = {
2685
    defaultallocator_create_displaysurface,
2686
    defaultallocator_resize_displaysurface,
2687
    defaultallocator_free_displaysurface
2688
};
2689

    
2690
void register_displaystate(DisplayState *ds)
2691
{
2692
    DisplayState **s;
2693
    s = &display_state;
2694
    while (*s != NULL)
2695
        s = &(*s)->next;
2696
    ds->next = NULL;
2697
    *s = ds;
2698
}
2699

    
2700
DisplayState *get_displaystate(void)
2701
{
2702
    return display_state;
2703
}
2704

    
2705
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2706
{
2707
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2708
    return ds->allocator;
2709
}
2710

    
2711
/* dumb display */
2712

    
2713
static void dumb_display_init(void)
2714
{
2715
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2716
    ds->allocator = &default_allocator;
2717
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2718
    register_displaystate(ds);
2719
}
2720

    
2721
/***********************************************************/
2722
/* I/O handling */
2723

    
2724
typedef struct IOHandlerRecord {
2725
    int fd;
2726
    IOCanRWHandler *fd_read_poll;
2727
    IOHandler *fd_read;
2728
    IOHandler *fd_write;
2729
    int deleted;
2730
    void *opaque;
2731
    /* temporary data */
2732
    struct pollfd *ufd;
2733
    struct IOHandlerRecord *next;
2734
} IOHandlerRecord;
2735

    
2736
static IOHandlerRecord *first_io_handler;
2737

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

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

    
2779
int qemu_set_fd_handler(int fd,
2780
                        IOHandler *fd_read,
2781
                        IOHandler *fd_write,
2782
                        void *opaque)
2783
{
2784
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2785
}
2786

    
2787
#ifdef _WIN32
2788
/***********************************************************/
2789
/* Polling handling */
2790

    
2791
typedef struct PollingEntry {
2792
    PollingFunc *func;
2793
    void *opaque;
2794
    struct PollingEntry *next;
2795
} PollingEntry;
2796

    
2797
static PollingEntry *first_polling_entry;
2798

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

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

    
2823
/***********************************************************/
2824
/* Wait objects support */
2825
typedef struct WaitObjects {
2826
    int num;
2827
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2828
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2829
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2830
} WaitObjects;
2831

    
2832
static WaitObjects wait_objects = {0};
2833

    
2834
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2835
{
2836
    WaitObjects *w = &wait_objects;
2837

    
2838
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2839
        return -1;
2840
    w->events[w->num] = handle;
2841
    w->func[w->num] = func;
2842
    w->opaque[w->num] = opaque;
2843
    w->num++;
2844
    return 0;
2845
}
2846

    
2847
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2848
{
2849
    int i, found;
2850
    WaitObjects *w = &wait_objects;
2851

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

    
2867
/***********************************************************/
2868
/* ram save/restore */
2869

    
2870
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2871
{
2872
    int v;
2873

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

    
2888
    if (qemu_file_has_error(f))
2889
        return -EIO;
2890

    
2891
    return 0;
2892
}
2893

    
2894
static int ram_load_v1(QEMUFile *f, void *opaque)
2895
{
2896
    int ret;
2897
    ram_addr_t i;
2898

    
2899
    if (qemu_get_be32(f) != last_ram_offset)
2900
        return -EINVAL;
2901
    for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
2902
        ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
2903
        if (ret)
2904
            return ret;
2905
    }
2906
    return 0;
2907
}
2908

    
2909
#define BDRV_HASH_BLOCK_SIZE 1024
2910
#define IOBUF_SIZE 4096
2911
#define RAM_CBLOCK_MAGIC 0xfabe
2912

    
2913
typedef struct RamDecompressState {
2914
    z_stream zstream;
2915
    QEMUFile *f;
2916
    uint8_t buf[IOBUF_SIZE];
2917
} RamDecompressState;
2918

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

    
2930
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2931
{
2932
    int ret, clen;
2933

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

    
2955
static void ram_decompress_close(RamDecompressState *s)
2956
{
2957
    inflateEnd(&s->zstream);
2958
}
2959

    
2960
#define RAM_SAVE_FLAG_FULL        0x01
2961
#define RAM_SAVE_FLAG_COMPRESS        0x02
2962
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2963
#define RAM_SAVE_FLAG_PAGE        0x08
2964
#define RAM_SAVE_FLAG_EOS        0x10
2965

    
2966
static int is_dup_page(uint8_t *page, uint8_t ch)
2967
{
2968
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2969
    uint32_t *array = (uint32_t *)page;
2970
    int i;
2971

    
2972
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2973
        if (array[i] != val)
2974
            return 0;
2975
    }
2976

    
2977
    return 1;
2978
}
2979

    
2980
static int ram_save_block(QEMUFile *f)
2981
{
2982
    static ram_addr_t current_addr = 0;
2983
    ram_addr_t saved_addr = current_addr;
2984
    ram_addr_t addr = 0;
2985
    int found = 0;
2986

    
2987
    while (addr < last_ram_offset) {
2988
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2989
            uint8_t *p;
2990

    
2991
            cpu_physical_memory_reset_dirty(current_addr,
2992
                                            current_addr + TARGET_PAGE_SIZE,
2993
                                            MIGRATION_DIRTY_FLAG);
2994

    
2995
            p = qemu_get_ram_ptr(current_addr);
2996

    
2997
            if (is_dup_page(p, *p)) {
2998
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2999
                qemu_put_byte(f, *p);
3000
            } else {
3001
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3002
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3003
            }
3004

    
3005
            found = 1;
3006
            break;
3007
        }
3008
        addr += TARGET_PAGE_SIZE;
3009
        current_addr = (saved_addr + addr) % last_ram_offset;
3010
    }
3011

    
3012
    return found;
3013
}
3014

    
3015
static uint64_t bytes_transferred = 0;
3016

    
3017
static ram_addr_t ram_save_remaining(void)
3018
{
3019
    ram_addr_t addr;
3020
    ram_addr_t count = 0;
3021

    
3022
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3023
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3024
            count++;
3025
    }
3026

    
3027
    return count;
3028
}
3029

    
3030
uint64_t ram_bytes_remaining(void)
3031
{
3032
    return ram_save_remaining() * TARGET_PAGE_SIZE;
3033
}
3034

    
3035
uint64_t ram_bytes_transferred(void)
3036
{
3037
    return bytes_transferred;
3038
}
3039

    
3040
uint64_t ram_bytes_total(void)
3041
{
3042
    return last_ram_offset;
3043
}
3044

    
3045
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3046
{
3047
    ram_addr_t addr;
3048
    uint64_t bytes_transferred_last;
3049
    double bwidth = 0;
3050
    uint64_t expected_time = 0;
3051

    
3052
    if (cpu_physical_sync_dirty_bitmap(0, TARGET_PHYS_ADDR_MAX) != 0) {
3053
        qemu_file_set_error(f);
3054
        return 0;
3055
    }
3056

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

    
3064
        /* Enable dirty memory tracking */
3065
        cpu_physical_memory_set_dirty_tracking(1);
3066

    
3067
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3068
    }
3069

    
3070
    bytes_transferred_last = bytes_transferred;
3071
    bwidth = get_clock();
3072

    
3073
    while (!qemu_file_rate_limit(f)) {
3074
        int ret;
3075

    
3076
        ret = ram_save_block(f);
3077
        bytes_transferred += ret * TARGET_PAGE_SIZE;
3078
        if (ret == 0) /* no more blocks */
3079
            break;
3080
    }
3081

    
3082
    bwidth = get_clock() - bwidth;
3083
    bwidth = (bytes_transferred - bytes_transferred_last) / bwidth;
3084

    
3085
    /* if we haven't transferred anything this round, force expected_time to a
3086
     * a very high value, but without crashing */
3087
    if (bwidth == 0)
3088
        bwidth = 0.000001;
3089

    
3090
    /* try transferring iterative blocks of memory */
3091

    
3092
    if (stage == 3) {
3093

    
3094
        /* flush all remaining blocks regardless of rate limiting */
3095
        while (ram_save_block(f) != 0) {
3096
            bytes_transferred += TARGET_PAGE_SIZE;
3097
        }
3098
        cpu_physical_memory_set_dirty_tracking(0);
3099
    }
3100

    
3101
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3102

    
3103
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3104

    
3105
    return (stage == 2) && (expected_time <= migrate_max_downtime());
3106
}
3107

    
3108
static int ram_load_dead(QEMUFile *f, void *opaque)
3109
{
3110
    RamDecompressState s1, *s = &s1;
3111
    uint8_t buf[10];
3112
    ram_addr_t i;
3113

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

    
3135
    return 0;
3136
}
3137

    
3138
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3139
{
3140
    ram_addr_t addr;
3141
    int flags;
3142

    
3143
    if (version_id == 1)
3144
        return ram_load_v1(f, opaque);
3145

    
3146
    if (version_id == 2) {
3147
        if (qemu_get_be32(f) != last_ram_offset)
3148
            return -EINVAL;
3149
        return ram_load_dead(f, opaque);
3150
    }
3151

    
3152
    if (version_id != 3)
3153
        return -EINVAL;
3154

    
3155
    do {
3156
        addr = qemu_get_be64(f);
3157

    
3158
        flags = addr & ~TARGET_PAGE_MASK;
3159
        addr &= TARGET_PAGE_MASK;
3160

    
3161
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3162
            if (addr != last_ram_offset)
3163
                return -EINVAL;
3164
        }
3165

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

    
3184
    return 0;
3185
}
3186

    
3187
void qemu_service_io(void)
3188
{
3189
    qemu_notify_event();
3190
}
3191

    
3192
/***********************************************************/
3193
/* bottom halves (can be seen as timers which expire ASAP) */
3194

    
3195
struct QEMUBH {
3196
    QEMUBHFunc *cb;
3197
    void *opaque;
3198
    int scheduled;
3199
    int idle;
3200
    int deleted;
3201
    QEMUBH *next;
3202
};
3203

    
3204
static QEMUBH *first_bh = NULL;
3205

    
3206
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3207
{
3208
    QEMUBH *bh;
3209
    bh = qemu_mallocz(sizeof(QEMUBH));
3210
    bh->cb = cb;
3211
    bh->opaque = opaque;
3212
    bh->next = first_bh;
3213
    first_bh = bh;
3214
    return bh;
3215
}
3216

    
3217
int qemu_bh_poll(void)
3218
{
3219
    QEMUBH *bh, **bhp;
3220
    int ret;
3221

    
3222
    ret = 0;
3223
    for (bh = first_bh; bh; bh = bh->next) {
3224
        if (!bh->deleted && bh->scheduled) {
3225
            bh->scheduled = 0;
3226
            if (!bh->idle)
3227
                ret = 1;
3228
            bh->idle = 0;
3229
            bh->cb(bh->opaque);
3230
        }
3231
    }
3232

    
3233
    /* remove deleted bhs */
3234
    bhp = &first_bh;
3235
    while (*bhp) {
3236
        bh = *bhp;
3237
        if (bh->deleted) {
3238
            *bhp = bh->next;
3239
            qemu_free(bh);
3240
        } else
3241
            bhp = &bh->next;
3242
    }
3243

    
3244
    return ret;
3245
}
3246

    
3247
void qemu_bh_schedule_idle(QEMUBH *bh)
3248
{
3249
    if (bh->scheduled)
3250
        return;
3251
    bh->scheduled = 1;
3252
    bh->idle = 1;
3253
}
3254

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

    
3265
void qemu_bh_cancel(QEMUBH *bh)
3266
{
3267
    bh->scheduled = 0;
3268
}
3269

    
3270
void qemu_bh_delete(QEMUBH *bh)
3271
{
3272
    bh->scheduled = 0;
3273
    bh->deleted = 1;
3274
}
3275

    
3276
static void qemu_bh_update_timeout(int *timeout)
3277
{
3278
    QEMUBH *bh;
3279

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

    
3296
/***********************************************************/
3297
/* machine registration */
3298

    
3299
static QEMUMachine *first_machine = NULL;
3300
QEMUMachine *current_machine = NULL;
3301

    
3302
int qemu_register_machine(QEMUMachine *m)
3303
{
3304
    QEMUMachine **pm;
3305
    pm = &first_machine;
3306
    while (*pm != NULL)
3307
        pm = &(*pm)->next;
3308
    m->next = NULL;
3309
    *pm = m;
3310
    return 0;
3311
}
3312

    
3313
static QEMUMachine *find_machine(const char *name)
3314
{
3315
    QEMUMachine *m;
3316

    
3317
    for(m = first_machine; m != NULL; m = m->next) {
3318
        if (!strcmp(m->name, name))
3319
            return m;
3320
        if (m->alias && !strcmp(m->alias, name))
3321
            return m;
3322
    }
3323
    return NULL;
3324
}
3325

    
3326
static QEMUMachine *find_default_machine(void)
3327
{
3328
    QEMUMachine *m;
3329

    
3330
    for(m = first_machine; m != NULL; m = m->next) {
3331
        if (m->is_default) {
3332
            return m;
3333
        }
3334
    }
3335
    return NULL;
3336
}
3337

    
3338
/***********************************************************/
3339
/* main execution loop */
3340

    
3341
static void gui_update(void *opaque)
3342
{
3343
    uint64_t interval = GUI_REFRESH_INTERVAL;
3344
    DisplayState *ds = opaque;
3345
    DisplayChangeListener *dcl = ds->listeners;
3346

    
3347
    dpy_refresh(ds);
3348

    
3349
    while (dcl != NULL) {
3350
        if (dcl->gui_timer_interval &&
3351
            dcl->gui_timer_interval < interval)
3352
            interval = dcl->gui_timer_interval;
3353
        dcl = dcl->next;
3354
    }
3355
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3356
}
3357

    
3358
static void nographic_update(void *opaque)
3359
{
3360
    uint64_t interval = GUI_REFRESH_INTERVAL;
3361

    
3362
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3363
}
3364

    
3365
struct vm_change_state_entry {
3366
    VMChangeStateHandler *cb;
3367
    void *opaque;
3368
    LIST_ENTRY (vm_change_state_entry) entries;
3369
};
3370

    
3371
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3372

    
3373
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3374
                                                     void *opaque)
3375
{
3376
    VMChangeStateEntry *e;
3377

    
3378
    e = qemu_mallocz(sizeof (*e));
3379

    
3380
    e->cb = cb;
3381
    e->opaque = opaque;
3382
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3383
    return e;
3384
}
3385

    
3386
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3387
{
3388
    LIST_REMOVE (e, entries);
3389
    qemu_free (e);
3390
}
3391

    
3392
static void vm_state_notify(int running, int reason)
3393
{
3394
    VMChangeStateEntry *e;
3395

    
3396
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3397
        e->cb(e->opaque, running, reason);
3398
    }
3399
}
3400

    
3401
static void resume_all_vcpus(void);
3402
static void pause_all_vcpus(void);
3403

    
3404
void vm_start(void)
3405
{
3406
    if (!vm_running) {
3407
        cpu_enable_ticks();
3408
        vm_running = 1;
3409
        vm_state_notify(1, 0);
3410
        qemu_rearm_alarm_timer(alarm_timer);
3411
        resume_all_vcpus();
3412
    }
3413
}
3414

    
3415
/* reset/shutdown handler */
3416

    
3417
typedef struct QEMUResetEntry {
3418
    TAILQ_ENTRY(QEMUResetEntry) entry;
3419
    QEMUResetHandler *func;
3420
    void *opaque;
3421
} QEMUResetEntry;
3422

    
3423
static TAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3424
    TAILQ_HEAD_INITIALIZER(reset_handlers);
3425
static int reset_requested;
3426
static int shutdown_requested;
3427
static int powerdown_requested;
3428
static int debug_requested;
3429
static int vmstop_requested;
3430

    
3431
int qemu_shutdown_requested(void)
3432
{
3433
    int r = shutdown_requested;
3434
    shutdown_requested = 0;
3435
    return r;
3436
}
3437

    
3438
int qemu_reset_requested(void)
3439
{
3440
    int r = reset_requested;
3441
    reset_requested = 0;
3442
    return r;
3443
}
3444

    
3445
int qemu_powerdown_requested(void)
3446
{
3447
    int r = powerdown_requested;
3448
    powerdown_requested = 0;
3449
    return r;
3450
}
3451

    
3452
static int qemu_debug_requested(void)
3453
{
3454
    int r = debug_requested;
3455
    debug_requested = 0;
3456
    return r;
3457
}
3458

    
3459
static int qemu_vmstop_requested(void)
3460
{
3461
    int r = vmstop_requested;
3462
    vmstop_requested = 0;
3463
    return r;
3464
}
3465

    
3466
static void do_vm_stop(int reason)
3467
{
3468
    if (vm_running) {
3469
        cpu_disable_ticks();
3470
        vm_running = 0;
3471
        pause_all_vcpus();
3472
        vm_state_notify(0, reason);
3473
    }
3474
}
3475

    
3476
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3477
{
3478
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3479

    
3480
    re->func = func;
3481
    re->opaque = opaque;
3482
    TAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3483
}
3484

    
3485
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3486
{
3487
    QEMUResetEntry *re;
3488

    
3489
    TAILQ_FOREACH(re, &reset_handlers, entry) {
3490
        if (re->func == func && re->opaque == opaque) {
3491
            TAILQ_REMOVE(&reset_handlers, re, entry);
3492
            qemu_free(re);
3493
            return;
3494
        }
3495
    }
3496
}
3497

    
3498
void qemu_system_reset(void)
3499
{
3500
    QEMUResetEntry *re, *nre;
3501

    
3502
    /* reset all devices */
3503
    TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3504
        re->func(re->opaque);
3505
    }
3506
}
3507

    
3508
void qemu_system_reset_request(void)
3509
{
3510
    if (no_reboot) {
3511
        shutdown_requested = 1;
3512
    } else {
3513
        reset_requested = 1;
3514
    }
3515
    qemu_notify_event();
3516
}
3517

    
3518
void qemu_system_shutdown_request(void)
3519
{
3520
    shutdown_requested = 1;
3521
    qemu_notify_event();
3522
}
3523

    
3524
void qemu_system_powerdown_request(void)
3525
{
3526
    powerdown_requested = 1;
3527
    qemu_notify_event();
3528
}
3529

    
3530
#ifdef CONFIG_IOTHREAD
3531
static void qemu_system_vmstop_request(int reason)
3532
{
3533
    vmstop_requested = reason;
3534
    qemu_notify_event();
3535
}
3536
#endif
3537

    
3538
#ifndef _WIN32
3539
static int io_thread_fd = -1;
3540

    
3541
static void qemu_event_increment(void)
3542
{
3543
    static const char byte = 0;
3544

    
3545
    if (io_thread_fd == -1)
3546
        return;
3547

    
3548
    write(io_thread_fd, &byte, sizeof(byte));
3549
}
3550

    
3551
static void qemu_event_read(void *opaque)
3552
{
3553
    int fd = (unsigned long)opaque;
3554
    ssize_t len;
3555

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

    
3563
static int qemu_event_init(void)
3564
{
3565
    int err;
3566
    int fds[2];
3567

    
3568
    err = pipe(fds);
3569
    if (err == -1)
3570
        return -errno;
3571

    
3572
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3573
    if (err < 0)
3574
        goto fail;
3575

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

    
3580
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3581
                         (void *)(unsigned long)fds[0]);
3582

    
3583
    io_thread_fd = fds[1];
3584
    return 0;
3585

    
3586
fail:
3587
    close(fds[0]);
3588
    close(fds[1]);
3589
    return err;
3590
}
3591
#else
3592
HANDLE qemu_event_handle;
3593

    
3594
static void dummy_event_handler(void *opaque)
3595
{
3596
}
3597

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

    
3609
static void qemu_event_increment(void)
3610
{
3611
    SetEvent(qemu_event_handle);
3612
}
3613
#endif
3614

    
3615
static int cpu_can_run(CPUState *env)
3616
{
3617
    if (env->stop)
3618
        return 0;
3619
    if (env->stopped)
3620
        return 0;
3621
    return 1;
3622
}
3623

    
3624
#ifndef CONFIG_IOTHREAD
3625
static int qemu_init_main_loop(void)
3626
{
3627
    return qemu_event_init();
3628
}
3629

    
3630
void qemu_init_vcpu(void *_env)
3631
{
3632
    CPUState *env = _env;
3633

    
3634
    if (kvm_enabled())
3635
        kvm_init_vcpu(env);
3636
    return;
3637
}
3638

    
3639
int qemu_cpu_self(void *env)
3640
{
3641
    return 1;
3642
}
3643

    
3644
static void resume_all_vcpus(void)
3645
{
3646
}
3647

    
3648
static void pause_all_vcpus(void)
3649
{
3650
}
3651

    
3652
void qemu_cpu_kick(void *env)
3653
{
3654
    return;
3655
}
3656

    
3657
void qemu_notify_event(void)
3658
{
3659
    CPUState *env = cpu_single_env;
3660

    
3661
    if (env) {
3662
        cpu_exit(env);
3663
#ifdef USE_KQEMU
3664
        if (env->kqemu_enabled)
3665
            kqemu_cpu_interrupt(env);
3666
#endif
3667
     }
3668
}
3669

    
3670
#define qemu_mutex_lock_iothread() do { } while (0)
3671
#define qemu_mutex_unlock_iothread() do { } while (0)
3672

    
3673
void vm_stop(int reason)
3674
{
3675
    do_vm_stop(reason);
3676
}
3677

    
3678
#else /* CONFIG_IOTHREAD */
3679

    
3680
#include "qemu-thread.h"
3681

    
3682
QemuMutex qemu_global_mutex;
3683
static QemuMutex qemu_fair_mutex;
3684

    
3685
static QemuThread io_thread;
3686

    
3687
static QemuThread *tcg_cpu_thread;
3688
static QemuCond *tcg_halt_cond;
3689

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

    
3697
static void block_io_signals(void);
3698
static void unblock_io_signals(void);
3699
static int tcg_has_work(void);
3700

    
3701
static int qemu_init_main_loop(void)
3702
{
3703
    int ret;
3704

    
3705
    ret = qemu_event_init();
3706
    if (ret)
3707
        return ret;
3708

    
3709
    qemu_cond_init(&qemu_pause_cond);
3710
    qemu_mutex_init(&qemu_fair_mutex);
3711
    qemu_mutex_init(&qemu_global_mutex);
3712
    qemu_mutex_lock(&qemu_global_mutex);
3713

    
3714
    unblock_io_signals();
3715
    qemu_thread_self(&io_thread);
3716

    
3717
    return 0;
3718
}
3719

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

    
3725
    qemu_mutex_unlock(&qemu_global_mutex);
3726

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

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

    
3743
static int qemu_cpu_exec(CPUState *env);
3744

    
3745
static void *kvm_cpu_thread_fn(void *arg)
3746
{
3747
    CPUState *env = arg;
3748

    
3749
    block_io_signals();
3750
    qemu_thread_self(env->thread);
3751

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

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

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

    
3767
    return NULL;
3768
}
3769

    
3770
static void tcg_cpu_exec(void);
3771

    
3772
static void *tcg_cpu_thread_fn(void *arg)
3773
{
3774
    CPUState *env = arg;
3775

    
3776
    block_io_signals();
3777
    qemu_thread_self(env->thread);
3778

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

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

    
3789
    while (1) {
3790
        tcg_cpu_exec();
3791
        qemu_wait_io_event(cur_cpu);
3792
    }
3793

    
3794
    return NULL;
3795
}
3796

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

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

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

    
3816
static void block_io_signals(void)
3817
{
3818
    sigset_t set;
3819
    struct sigaction sigact;
3820

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

    
3827
    sigemptyset(&set);
3828
    sigaddset(&set, SIGUSR1);
3829
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3830

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

    
3836
static void unblock_io_signals(void)
3837
{
3838
    sigset_t set;
3839

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

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

    
3851
static void qemu_signal_lock(unsigned int msecs)
3852
{
3853
    qemu_mutex_lock(&qemu_fair_mutex);
3854

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

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

    
3873
static void qemu_mutex_unlock_iothread(void)
3874
{
3875
    qemu_mutex_unlock(&qemu_global_mutex);
3876
}
3877

    
3878
static int all_vcpus_paused(void)
3879
{
3880
    CPUState *penv = first_cpu;
3881

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

    
3888
    return 1;
3889
}
3890

    
3891
static void pause_all_vcpus(void)
3892
{
3893
    CPUState *penv = first_cpu;
3894

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

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

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

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

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

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

    
3955
void qemu_init_vcpu(void *_env)
3956
{
3957
    CPUState *env = _env;
3958

    
3959
    if (kvm_enabled())
3960
        kvm_start_vcpu(env);
3961
    else
3962
        tcg_init_vcpu(env);
3963
}
3964

    
3965
void qemu_notify_event(void)
3966
{
3967
    qemu_event_increment();
3968
}
3969

    
3970
void vm_stop(int reason)
3971
{
3972
    QemuThread me;
3973
    qemu_thread_self(&me);
3974

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

    
3990
#endif
3991

    
3992

    
3993
#ifdef _WIN32
3994
static void host_main_loop_wait(int *timeout)
3995
{
3996
    int ret, ret2, i;
3997
    PollingEntry *pe;
3998

    
3999

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

    
4009
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4010
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4011
            if (w->func[ret - WAIT_OBJECT_0])
4012
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4013

    
4014
            /* Check for additional signaled events */
4015
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4016

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

    
4035
    *timeout = 0;
4036
}
4037
#else
4038
static void host_main_loop_wait(int *timeout)
4039
{
4040
}
4041
#endif
4042

    
4043
void main_loop_wait(int timeout)
4044
{
4045
    IOHandlerRecord *ioh;
4046
    fd_set rfds, wfds, xfds;
4047
    int ret, nfds;
4048
    struct timeval tv;
4049

    
4050
    qemu_bh_update_timeout(&timeout);
4051

    
4052
    host_main_loop_wait(&timeout);
4053

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

    
4077
    tv.tv_sec = timeout / 1000;
4078
    tv.tv_usec = (timeout % 1000) * 1000;
4079

    
4080
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4081

    
4082
    qemu_mutex_unlock_iothread();
4083
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4084
    qemu_mutex_lock_iothread();
4085
    if (ret > 0) {
4086
        IOHandlerRecord **pioh;
4087

    
4088
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4089
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4090
                ioh->fd_read(ioh->opaque);
4091
            }
4092
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4093
                ioh->fd_write(ioh->opaque);
4094
            }
4095
        }
4096

    
4097
        /* remove deleted IO handlers */
4098
        pioh = &first_io_handler;
4099
        while (*pioh) {
4100
            ioh = *pioh;
4101
            if (ioh->deleted) {
4102
                *pioh = ioh->next;
4103
                qemu_free(ioh);
4104
            } else
4105
                pioh = &ioh->next;
4106
        }
4107
    }
4108

    
4109
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
4110

    
4111
    /* rearm timer, if not periodic */
4112
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4113
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
4114
        qemu_rearm_alarm_timer(alarm_timer);
4115
    }
4116

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

    
4124
    /* real time timers */
4125
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4126
                    qemu_get_clock(rt_clock));
4127

    
4128
    /* Check bottom-halves last in case any of the earlier events triggered
4129
       them.  */
4130
    qemu_bh_poll();
4131

    
4132
}
4133

    
4134
static int qemu_cpu_exec(CPUState *env)
4135
{
4136
    int ret;
4137
#ifdef CONFIG_PROFILER
4138
    int64_t ti;
4139
#endif
4140

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

    
4174
static void tcg_cpu_exec(void)
4175
{
4176
    int ret = 0;
4177

    
4178
    if (next_cpu == NULL)
4179
        next_cpu = first_cpu;
4180
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4181
        CPUState *env = cur_cpu = next_cpu;
4182

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

    
4199
static int cpu_has_work(CPUState *env)
4200
{
4201
    if (env->stop)
4202
        return 1;
4203
    if (env->stopped)
4204
        return 0;
4205
    if (!env->halted)
4206
        return 1;
4207
    if (qemu_cpu_has_work(env))
4208
        return 1;
4209
    return 0;
4210
}
4211

    
4212
static int tcg_has_work(void)
4213
{
4214
    CPUState *env;
4215

    
4216
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4217
        if (cpu_has_work(env))
4218
            return 1;
4219
    return 0;
4220
}
4221

    
4222
static int qemu_calculate_timeout(void)
4223
{
4224
#ifndef CONFIG_IOTHREAD
4225
    int timeout;
4226

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

    
4269
    return timeout;
4270
#else /* CONFIG_IOTHREAD */
4271
    return 1000;
4272
#endif
4273
}
4274

    
4275
static int vm_can_run(void)
4276
{
4277
    if (powerdown_requested)
4278
        return 0;
4279
    if (reset_requested)
4280
        return 0;
4281
    if (shutdown_requested)
4282
        return 0;
4283
    if (debug_requested)
4284
        return 0;
4285
    return 1;
4286
}
4287

    
4288
static void main_loop(void)
4289
{
4290
    int r;
4291

    
4292
#ifdef CONFIG_IOTHREAD
4293
    qemu_system_ready = 1;
4294
    qemu_cond_broadcast(&qemu_system_cond);
4295
#endif
4296

    
4297
    for (;;) {
4298
        do {
4299
#ifdef CONFIG_PROFILER
4300
            int64_t ti;
4301
#endif
4302
#ifndef CONFIG_IOTHREAD
4303
            tcg_cpu_exec();
4304
#endif
4305
#ifdef CONFIG_PROFILER
4306
            ti = profile_getclock();
4307
#endif
4308
            main_loop_wait(qemu_calculate_timeout());
4309
#ifdef CONFIG_PROFILER
4310
            dev_time += profile_getclock() - ti;
4311
#endif
4312
        } while (vm_can_run());
4313

    
4314
        if (qemu_debug_requested())
4315
            vm_stop(EXCP_DEBUG);
4316
        if (qemu_shutdown_requested()) {
4317
            if (no_shutdown) {
4318
                vm_stop(0);
4319
                no_shutdown = 0;
4320
            } else
4321
                break;
4322
        }
4323
        if (qemu_reset_requested()) {
4324
            pause_all_vcpus();
4325
            qemu_system_reset();
4326
            resume_all_vcpus();
4327
        }
4328
        if (qemu_powerdown_requested())
4329
            qemu_system_powerdown();
4330
        if ((r = qemu_vmstop_requested()))
4331
            vm_stop(r);
4332
    }
4333
    pause_all_vcpus();
4334
}
4335

    
4336
static void version(void)
4337
{
4338
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4339
}
4340

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

    
4374
#define HAS_ARG 0x0001
4375

    
4376
enum {
4377
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4378
    opt_enum,
4379
#define DEFHEADING(text)
4380
#include "qemu-options.h"
4381
#undef DEF
4382
#undef DEFHEADING
4383
#undef GEN_DOCS
4384
};
4385

    
4386
typedef struct QEMUOption {
4387
    const char *name;
4388
    int flags;
4389
    int index;
4390
} QEMUOption;
4391

    
4392
static const QEMUOption qemu_options[] = {
4393
    { "h", 0, QEMU_OPTION_h },
4394
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4395
    { option, opt_arg, opt_enum },
4396
#define DEFHEADING(text)
4397
#include "qemu-options.h"
4398
#undef DEF
4399
#undef DEFHEADING
4400
#undef GEN_DOCS
4401
    { NULL },
4402
};
4403

    
4404
#ifdef HAS_AUDIO
4405
struct soundhw soundhw[] = {
4406
#ifdef HAS_AUDIO_CHOICE
4407
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4408
    {
4409
        "pcspk",
4410
        "PC speaker",
4411
        0,
4412
        1,
4413
        { .init_isa = pcspk_audio_init }
4414
    },
4415
#endif
4416

    
4417
#ifdef CONFIG_SB16
4418
    {
4419
        "sb16",
4420
        "Creative Sound Blaster 16",
4421
        0,
4422
        1,
4423
        { .init_isa = SB16_init }
4424
    },
4425
#endif
4426

    
4427
#ifdef CONFIG_CS4231A
4428
    {
4429
        "cs4231a",
4430
        "CS4231A",
4431
        0,
4432
        1,
4433
        { .init_isa = cs4231a_init }
4434
    },
4435
#endif
4436

    
4437
#ifdef CONFIG_ADLIB
4438
    {
4439
        "adlib",
4440
#ifdef HAS_YMF262
4441
        "Yamaha YMF262 (OPL3)",
4442
#else
4443
        "Yamaha YM3812 (OPL2)",
4444
#endif
4445
        0,
4446
        1,
4447
        { .init_isa = Adlib_init }
4448
    },
4449
#endif
4450

    
4451
#ifdef CONFIG_GUS
4452
    {
4453
        "gus",
4454
        "Gravis Ultrasound GF1",
4455
        0,
4456
        1,
4457
        { .init_isa = GUS_init }
4458
    },
4459
#endif
4460

    
4461
#ifdef CONFIG_AC97
4462
    {
4463
        "ac97",
4464
        "Intel 82801AA AC97 Audio",
4465
        0,
4466
        0,
4467
        { .init_pci = ac97_init }
4468
    },
4469
#endif
4470

    
4471
#ifdef CONFIG_ES1370
4472
    {
4473
        "es1370",
4474
        "ENSONIQ AudioPCI ES1370",
4475
        0,
4476
        0,
4477
        { .init_pci = es1370_init }
4478
    },
4479
#endif
4480

    
4481
#endif /* HAS_AUDIO_CHOICE */
4482

    
4483
    { NULL, NULL, 0, 0, { NULL } }
4484
};
4485

    
4486
static void select_soundhw (const char *optarg)
4487
{
4488
    struct soundhw *c;
4489

    
4490
    if (*optarg == '?') {
4491
    show_valid_cards:
4492

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

    
4506
        if (!strcmp (optarg, "all")) {
4507
            for (c = soundhw; c->name; ++c) {
4508
                c->enabled = 1;
4509
            }
4510
            return;
4511
        }
4512

    
4513
        p = optarg;
4514
        while (*p) {
4515
            e = strchr (p, ',');
4516
            l = !e ? strlen (p) : (size_t) (e - p);
4517

    
4518
            for (c = soundhw; c->name; ++c) {
4519
                if (!strncmp (c->name, p, l)) {
4520
                    c->enabled = 1;
4521
                    break;
4522
                }
4523
            }
4524

    
4525
            if (!c->name) {
4526
                if (l > 80) {
4527
                    fprintf (stderr,
4528
                             "Unknown sound card name (too big to show)\n");
4529
                }
4530
                else {
4531
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4532
                             (int) l, p);
4533
                }
4534
                bad_card = 1;
4535
            }
4536
            p += l + (e != NULL);
4537
        }
4538

    
4539
        if (bad_card)
4540
            goto show_valid_cards;
4541
    }
4542
}
4543
#endif
4544

    
4545
static void select_vgahw (const char *p)
4546
{
4547
    const char *opts;
4548

    
4549
    cirrus_vga_enabled = 0;
4550
    std_vga_enabled = 0;
4551
    vmsvga_enabled = 0;
4552
    xenfb_enabled = 0;
4553
    if (strstart(p, "std", &opts)) {
4554
        std_vga_enabled = 1;
4555
    } else if (strstart(p, "cirrus", &opts)) {
4556
        cirrus_vga_enabled = 1;
4557
    } else if (strstart(p, "vmware", &opts)) {
4558
        vmsvga_enabled = 1;
4559
    } else if (strstart(p, "xenfb", &opts)) {
4560
        xenfb_enabled = 1;
4561
    } else if (!strstart(p, "none", &opts)) {
4562
    invalid_vga:
4563
        fprintf(stderr, "Unknown vga type: %s\n", p);
4564
        exit(1);
4565
    }
4566
    while (*opts) {
4567
        const char *nextopt;
4568

    
4569
        if (strstart(opts, ",retrace=", &nextopt)) {
4570
            opts = nextopt;
4571
            if (strstart(opts, "dumb", &nextopt))
4572
                vga_retrace_method = VGA_RETRACE_DUMB;
4573
            else if (strstart(opts, "precise", &nextopt))
4574
                vga_retrace_method = VGA_RETRACE_PRECISE;
4575
            else goto invalid_vga;
4576
        } else goto invalid_vga;
4577
        opts = nextopt;
4578
    }
4579
}
4580

    
4581
#ifdef TARGET_I386
4582
static int balloon_parse(const char *arg)
4583
{
4584
    char buf[128];
4585
    const char *p;
4586

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

    
4604
#ifdef _WIN32
4605
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4606
{
4607
    exit(STATUS_CONTROL_C_EXIT);
4608
    return TRUE;
4609
}
4610
#endif
4611

    
4612
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4613
{
4614
    int ret;
4615

    
4616
    if(strlen(str) != 36)
4617
        return -1;
4618

    
4619
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4620
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4621
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4622

    
4623
    if(ret != 16)
4624
        return -1;
4625

    
4626
#ifdef TARGET_I386
4627
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4628
#endif
4629

    
4630
    return 0;
4631
}
4632

    
4633
#define MAX_NET_CLIENTS 32
4634

    
4635
#ifndef _WIN32
4636

    
4637
static void termsig_handler(int signal)
4638
{
4639
    qemu_system_shutdown_request();
4640
}
4641

    
4642
static void sigchld_handler(int signal)
4643
{
4644
    waitpid(-1, NULL, WNOHANG);
4645
}
4646

    
4647
static void sighandler_setup(void)
4648
{
4649
    struct sigaction act;
4650

    
4651
    memset(&act, 0, sizeof(act));
4652
    act.sa_handler = termsig_handler;
4653
    sigaction(SIGINT,  &act, NULL);
4654
    sigaction(SIGHUP,  &act, NULL);
4655
    sigaction(SIGTERM, &act, NULL);
4656

    
4657
    act.sa_handler = sigchld_handler;
4658
    act.sa_flags = SA_NOCLDSTOP;
4659
    sigaction(SIGCHLD, &act, NULL);
4660
}
4661

    
4662
#endif
4663

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

    
4672
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4673
    if (len == 0) {
4674
        return NULL;
4675
    }
4676

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

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

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

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

    
4757
char *qemu_find_file(int type, const char *name)
4758
{
4759
    int len;
4760
    const char *subdir;
4761
    char *buf;
4762

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

    
4788
struct device_config {
4789
    enum {
4790
        DEV_GENERIC,   /* -device      */
4791
        DEV_USB,       /* -usbdevice   */
4792
        DEV_BT,        /* -bt          */
4793
    } type;
4794
    const char *cmdline;
4795
    TAILQ_ENTRY(device_config) next;
4796
};
4797
TAILQ_HEAD(, device_config) device_configs = TAILQ_HEAD_INITIALIZER(device_configs);
4798

    
4799
static void add_device_config(int type, const char *cmdline)
4800
{
4801
    struct device_config *conf;
4802

    
4803
    conf = qemu_mallocz(sizeof(*conf));
4804
    conf->type = type;
4805
    conf->cmdline = cmdline;
4806
    TAILQ_INSERT_TAIL(&device_configs, conf, next);
4807
}
4808

    
4809
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4810
{
4811
    struct device_config *conf;
4812
    int rc;
4813

    
4814
    TAILQ_FOREACH(conf, &device_configs, next) {
4815
        if (conf->type != type)
4816
            continue;
4817
        rc = func(conf->cmdline);
4818
        if (0 != rc)
4819
            return rc;
4820
    }
4821
    return 0;
4822
}
4823

    
4824
static int generic_parse(const char *cmdline)
4825
{
4826
    DeviceState *dev;
4827

    
4828
    dev = qdev_device_add(cmdline);
4829
    if (!dev)
4830
        return -1;
4831
    return 0;
4832
}
4833

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

    
4877
    qemu_cache_utils_init(envp);
4878

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

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

    
4922
    serial_devices[0] = "vc:80Cx24C";
4923
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4924
        serial_devices[i] = NULL;
4925
    serial_device_index = 0;
4926

    
4927
    parallel_devices[0] = "vc:80Cx24C";
4928
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4929
        parallel_devices[i] = NULL;
4930
    parallel_device_index = 0;
4931

    
4932
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4933
        virtio_consoles[i] = NULL;
4934
    virtio_console_index = 0;
4935

    
4936
    for (i = 0; i < MAX_NODES; i++) {
4937
        node_mem[i] = 0;
4938
        node_cpumask[i] = 0;
4939
    }
4940

    
4941
    nb_net_clients = 0;
4942
    nb_numa_nodes = 0;
4943
    nb_nics = 0;
4944

    
4945
    tb_size = 0;
4946
    autostart= 1;
4947

    
4948
    register_watchdogs();
4949

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

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

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

    
5135
                    if (!strchr(optarg, '=')) {
5136
                        legacy = 1;
5137
                        pstrcpy(buf, sizeof(buf), optarg);
5138
                    } else if (check_params(buf, sizeof(buf), params, optarg) < 0) {
5139
                        fprintf(stderr,
5140
                                "qemu: unknown boot parameter '%s' in '%s'\n",
5141
                                buf, optarg);
5142
                        exit(1);
5143
                    }
5144

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

    
5231
                value = strtoul(optarg, &ptr, 10);
5232
                switch (*ptr) {
5233
                case 0: case 'M': case 'm':
5234
                    value <<= 20;
5235
                    break;
5236
                case 'G': case 'g':
5237
                    value <<= 30;
5238
                    break;
5239
                default:
5240
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5241
                    exit(1);
5242
                }
5243

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

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

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

    
5642
    /* If no data_dir is specified then try to find it relative to the
5643
       executable path.  */
5644
    if (!data_dir) {
5645
        data_dir = find_datadir(argv[0]);
5646
    }
5647
    /* If all else fails use the install patch specified when building.  */
5648
    if (!data_dir) {
5649
        data_dir = CONFIG_QEMU_SHAREDIR;
5650
    }
5651

    
5652
#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
5653
    if (kvm_allowed && kqemu_allowed) {
5654
        fprintf(stderr,
5655
                "You can not enable both KVM and kqemu at the same time\n");
5656
        exit(1);
5657
    }
5658
#endif
5659

    
5660
    /*
5661
     * Default to max_cpus = smp_cpus, in case the user doesn't
5662
     * specify a max_cpus value.
5663
     */
5664
    if (!max_cpus)
5665
        max_cpus = smp_cpus;
5666

    
5667
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5668
    if (smp_cpus > machine->max_cpus) {
5669
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5670
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5671
                machine->max_cpus);
5672
        exit(1);
5673
    }
5674

    
5675
    if (display_type == DT_NOGRAPHIC) {
5676
       if (serial_device_index == 0)
5677
           serial_devices[0] = "stdio";
5678
       if (parallel_device_index == 0)
5679
           parallel_devices[0] = "null";
5680
       if (strncmp(monitor_device, "vc", 2) == 0)
5681
           monitor_device = "stdio";
5682
    }
5683

    
5684
#ifndef _WIN32
5685
    if (daemonize) {
5686
        pid_t pid;
5687

    
5688
        if (pipe(fds) == -1)
5689
            exit(1);
5690

    
5691
        pid = fork();
5692
        if (pid > 0) {
5693
            uint8_t status;
5694
            ssize_t len;
5695

    
5696
            close(fds[1]);
5697

    
5698
        again:
5699
            len = read(fds[0], &status, 1);
5700
            if (len == -1 && (errno == EINTR))
5701
                goto again;
5702

    
5703
            if (len != 1)
5704
                exit(1);
5705
            else if (status == 1) {
5706
                fprintf(stderr, "Could not acquire pidfile\n");
5707
                exit(1);
5708
            } else
5709
                exit(0);
5710
        } else if (pid < 0)
5711
            exit(1);
5712

    
5713
        setsid();
5714

    
5715
        pid = fork();
5716
        if (pid > 0)
5717
            exit(0);
5718
        else if (pid < 0)
5719
            exit(1);
5720

    
5721
        umask(027);
5722

    
5723
        signal(SIGTSTP, SIG_IGN);
5724
        signal(SIGTTOU, SIG_IGN);
5725
        signal(SIGTTIN, SIG_IGN);
5726
    }
5727

    
5728
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5729
        if (daemonize) {
5730
            uint8_t status = 1;
5731
            write(fds[1], &status, 1);
5732
        } else
5733
            fprintf(stderr, "Could not acquire pid file\n");
5734
        exit(1);
5735
    }
5736
#endif
5737

    
5738
#ifdef CONFIG_KQEMU
5739
    if (smp_cpus > 1)
5740
        kqemu_allowed = 0;
5741
#endif
5742
    if (qemu_init_main_loop()) {
5743
        fprintf(stderr, "qemu_init_main_loop failed\n");
5744
        exit(1);
5745
    }
5746
    linux_boot = (kernel_filename != NULL);
5747

    
5748
    if (!linux_boot && *kernel_cmdline != '\0') {
5749
        fprintf(stderr, "-append only allowed with -kernel option\n");
5750
        exit(1);
5751
    }
5752

    
5753
    if (!linux_boot && initrd_filename != NULL) {
5754
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5755
        exit(1);
5756
    }
5757

    
5758
#ifndef _WIN32
5759
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5760
    setvbuf(stdout, NULL, _IOLBF, 0);
5761
#endif
5762

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

    
5776
#ifdef _WIN32
5777
    socket_init();
5778
#endif
5779

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

    
5789
    for(i = 0;i < nb_net_clients; i++) {
5790
        if (net_client_parse(net_clients[i]) < 0)
5791
            exit(1);
5792
    }
5793

    
5794
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5795
    net_set_boot_mask(net_boot);
5796

    
5797
    net_client_check();
5798

    
5799
    /* init the bluetooth world */
5800
    if (foreach_device_config(DEV_BT, bt_parse))
5801
        exit(1);
5802

    
5803
    /* init the memory */
5804
    if (ram_size == 0)
5805
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5806

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

    
5820
    /* init the dynamic translator */
5821
    cpu_exec_init_all(tb_size * 1024 * 1024);
5822

    
5823
    bdrv_init();
5824

    
5825
    /* we always create the cdrom drive, even if no disk is there */
5826
    drive_add(NULL, CDROM_ALIAS);
5827

    
5828
    /* we always create at least one floppy */
5829
    drive_add(NULL, FD_ALIAS, 0);
5830

    
5831
    /* we always create one sd slot, even if no card is in it */
5832
    drive_add(NULL, SD_ALIAS);
5833

    
5834
    /* open the virtual block devices */
5835
    if (snapshot)
5836
        qemu_opts_foreach(&drive_opt_list, drive_enable_snapshot, NULL, 0);
5837
    if (qemu_opts_foreach(&drive_opt_list, drive_init_func, machine, 1) != 0)
5838
        exit(1);
5839

    
5840
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5841
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5842

    
5843
#ifndef _WIN32
5844
    /* must be after terminal init, SDL library changes signal handlers */
5845
    sighandler_setup();
5846
#endif
5847

    
5848
    /* Maintain compatibility with multiple stdio monitors */
5849
    if (!strcmp(monitor_device,"stdio")) {
5850
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5851
            const char *devname = serial_devices[i];
5852
            if (devname && !strcmp(devname,"mon:stdio")) {
5853
                monitor_device = NULL;
5854
                break;
5855
            } else if (devname && !strcmp(devname,"stdio")) {
5856
                monitor_device = NULL;
5857
                serial_devices[i] = "mon:stdio";
5858
                break;
5859
            }
5860
        }
5861
    }
5862

    
5863
    if (nb_numa_nodes > 0) {
5864
        int i;
5865

    
5866
        if (nb_numa_nodes > smp_cpus) {
5867
            nb_numa_nodes = smp_cpus;
5868
        }
5869

    
5870
        /* If no memory size if given for any node, assume the default case
5871
         * and distribute the available memory equally across all nodes
5872
         */
5873
        for (i = 0; i < nb_numa_nodes; i++) {
5874
            if (node_mem[i] != 0)
5875
                break;
5876
        }
5877
        if (i == nb_numa_nodes) {
5878
            uint64_t usedmem = 0;
5879

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

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

    
5905
    if (kvm_enabled()) {
5906
        int ret;
5907

    
5908
        ret = kvm_init(smp_cpus);
5909
        if (ret < 0) {
5910
            fprintf(stderr, "failed to initialize KVM\n");
5911
            exit(1);
5912
        }
5913
    }
5914

    
5915
    if (monitor_device) {
5916
        monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5917
        if (!monitor_hd) {
5918
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5919
            exit(1);
5920
        }
5921
    }
5922

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

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

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

    
5965
    module_call_init(MODULE_INIT_DEVICE);
5966

    
5967
    if (machine->compat_props) {
5968
        qdev_prop_register_compat(machine->compat_props);
5969
    }
5970
    machine->init(ram_size, boot_devices,
5971
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5972

    
5973

    
5974
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5975
        for (i = 0; i < nb_numa_nodes; i++) {
5976
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5977
                env->numa_node = i;
5978
            }
5979
        }
5980
    }
5981

    
5982
    current_machine = machine;
5983

    
5984
    /* init USB devices */
5985
    if (usb_enabled) {
5986
        foreach_device_config(DEV_USB, usb_parse);
5987
    }
5988

    
5989
    /* init generic devices */
5990
    if (foreach_device_config(DEV_GENERIC, generic_parse))
5991
        exit(1);
5992

    
5993
    if (!display_state)
5994
        dumb_display_init();
5995
    /* just use the first displaystate for the moment */
5996
    ds = display_state;
5997

    
5998
    if (display_type == DT_DEFAULT) {
5999
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
6000
        display_type = DT_SDL;
6001
#else
6002
        display_type = DT_VNC;
6003
        vnc_display = "localhost:0,to=99";
6004
        show_vnc_port = 1;
6005
#endif
6006
    }
6007
        
6008

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

    
6031
        if (show_vnc_port) {
6032
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6033
        }
6034
        break;
6035
    default:
6036
        break;
6037
    }
6038
    dpy_resize(ds);
6039

    
6040
    dcl = ds->listeners;
6041
    while (dcl != NULL) {
6042
        if (dcl->dpy_refresh != NULL) {
6043
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6044
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6045
        }
6046
        dcl = dcl->next;
6047
    }
6048

    
6049
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6050
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6051
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6052
    }
6053

    
6054
    text_consoles_set_display(display_state);
6055
    qemu_chr_initial_reset();
6056

    
6057
    if (monitor_device && monitor_hd)
6058
        monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
6059

    
6060
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6061
        const char *devname = serial_devices[i];
6062
        if (devname && strcmp(devname, "none")) {
6063
            if (strstart(devname, "vc", 0))
6064
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6065
        }
6066
    }
6067

    
6068
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6069
        const char *devname = parallel_devices[i];
6070
        if (devname && strcmp(devname, "none")) {
6071
            if (strstart(devname, "vc", 0))
6072
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6073
        }
6074
    }
6075

    
6076
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
6077
        const char *devname = virtio_consoles[i];
6078
        if (virtcon_hds[i] && devname) {
6079
            if (strstart(devname, "vc", 0))
6080
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
6081
        }
6082
    }
6083

    
6084
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6085
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6086
                gdbstub_dev);
6087
        exit(1);
6088
    }
6089

    
6090
    if (loadvm)
6091
        do_loadvm(cur_mon, loadvm);
6092

    
6093
    if (incoming) {
6094
        autostart = 0;
6095
        qemu_start_incoming_migration(incoming);
6096
    }
6097

    
6098
    if (autostart)
6099
        vm_start();
6100

    
6101
#ifndef _WIN32
6102
    if (daemonize) {
6103
        uint8_t status = 0;
6104
        ssize_t len;
6105

    
6106
    again1:
6107
        len = write(fds[1], &status, 1);
6108
        if (len == -1 && (errno == EINTR))
6109
            goto again1;
6110

    
6111
        if (len != 1)
6112
            exit(1);
6113

    
6114
        chdir("/");
6115
        TFR(fd = open("/dev/null", O_RDWR));
6116
        if (fd == -1)
6117
            exit(1);
6118
    }
6119

    
6120
    if (run_as) {
6121
        pwd = getpwnam(run_as);
6122
        if (!pwd) {
6123
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
6124
            exit(1);
6125
        }
6126
    }
6127

    
6128
    if (chroot_dir) {
6129
        if (chroot(chroot_dir) < 0) {
6130
            fprintf(stderr, "chroot failed\n");
6131
            exit(1);
6132
        }
6133
        chdir("/");
6134
    }
6135

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

    
6151
    if (daemonize) {
6152
        dup2(fd, 0);
6153
        dup2(fd, 1);
6154
        dup2(fd, 2);
6155

    
6156
        close(fd);
6157
    }
6158
#endif
6159

    
6160
    main_loop();
6161
    quit_timers();
6162
    net_cleanup();
6163

    
6164
    return 0;
6165
}