Statistics
| Branch: | Revision:

root / vl.c @ ac33f8fa

History | View | Annotate | Download (156.6 kB)

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

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

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

    
65
/* For the benefit of older linux systems which don't supply it,
66
   we use a local copy of hpet.h. */
67
/* #include <linux/hpet.h> */
68
#include "hpet.h"
69

    
70
#include <linux/ppdev.h>
71
#include <linux/parport.h>
72
#endif
73
#ifdef __sun__
74
#include <sys/stat.h>
75
#include <sys/ethernet.h>
76
#include <sys/sockio.h>
77
#include <netinet/arp.h>
78
#include <netinet/in.h>
79
#include <netinet/in_systm.h>
80
#include <netinet/ip.h>
81
#include <netinet/ip_icmp.h> // must come after ip.h
82
#include <netinet/udp.h>
83
#include <netinet/tcp.h>
84
#include <net/if.h>
85
#include <syslog.h>
86
#include <stropts.h>
87
/* See MySQL bug #7156 (http://bugs.mysql.com/bug.php?id=7156) for
88
   discussion about Solaris header problems */
89
extern int madvise(caddr_t, size_t, int);
90
#endif
91
#endif
92
#endif
93

    
94
#if defined(__OpenBSD__)
95
#include <util.h>
96
#endif
97

    
98
#if defined(CONFIG_VDE)
99
#include <libvdeplug.h>
100
#endif
101

    
102
#ifdef _WIN32
103
#include <windows.h>
104
#include <mmsystem.h>
105
#endif
106

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

    
120
#ifdef CONFIG_COCOA
121
#undef main
122
#define main qemu_main
123
#endif /* CONFIG_COCOA */
124

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

    
161
#include "disas.h"
162

    
163
#include "exec-all.h"
164

    
165
#include "qemu_socket.h"
166

    
167
#include "slirp/libslirp.h"
168

    
169
#include "qemu-queue.h"
170

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

    
174
#define DEFAULT_RAM_SIZE 128
175

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

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

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

    
267
uint8_t qemu_uuid[16];
268

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

    
272
static int default_serial = 1;
273
static int default_parallel = 1;
274
static int default_virtcon = 1;
275
static int default_monitor = 1;
276
static int default_vga = 1;
277
static int default_floppy = 1;
278
static int default_cdrom = 1;
279
static int default_sdcard = 1;
280

    
281
static struct {
282
    const char *driver;
283
    int *flag;
284
} default_list[] = {
285
    { .driver = "isa-serial",           .flag = &default_serial    },
286
    { .driver = "isa-parallel",         .flag = &default_parallel  },
287
    { .driver = "virtio-console-pci",   .flag = &default_virtcon   },
288
    { .driver = "virtio-console-s390",  .flag = &default_virtcon   },
289
    { .driver = "VGA",                  .flag = &default_vga       },
290
    { .driver = "Cirrus VGA",           .flag = &default_vga       },
291
    { .driver = "QEMUware SVGA",        .flag = &default_vga       },
292
};
293

    
294
static int default_driver_check(QemuOpts *opts, void *opaque)
295
{
296
    const char *driver = qemu_opt_get(opts, "driver");
297
    int i;
298

    
299
    if (!driver)
300
        return 0;
301
    for (i = 0; i < ARRAY_SIZE(default_list); i++) {
302
        if (strcmp(default_list[i].driver, driver) != 0)
303
            continue;
304
        *(default_list[i].flag) = 0;
305
    }
306
    return 0;
307
}
308

    
309
/***********************************************************/
310
/* x86 ISA bus support */
311

    
312
target_phys_addr_t isa_mem_base = 0;
313
PicState2 *isa_pic;
314

    
315
/***********************************************************/
316
void hw_error(const char *fmt, ...)
317
{
318
    va_list ap;
319
    CPUState *env;
320

    
321
    va_start(ap, fmt);
322
    fprintf(stderr, "qemu: hardware error: ");
323
    vfprintf(stderr, fmt, ap);
324
    fprintf(stderr, "\n");
325
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
326
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
327
#ifdef TARGET_I386
328
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
329
#else
330
        cpu_dump_state(env, stderr, fprintf, 0);
331
#endif
332
    }
333
    va_end(ap);
334
    abort();
335
}
336

    
337
static void set_proc_name(const char *s)
338
{
339
#if defined(__linux__) && defined(PR_SET_NAME)
340
    char name[16];
341
    if (!s)
342
        return;
343
    name[sizeof(name) - 1] = 0;
344
    strncpy(name, s, sizeof(name));
345
    /* Could rewrite argv[0] too, but that's a bit more complicated.
346
       This simple way is enough for `top'. */
347
    prctl(PR_SET_NAME, name);
348
#endif            
349
}
350
 
351
/***************/
352
/* ballooning */
353

    
354
static QEMUBalloonEvent *qemu_balloon_event;
355
void *qemu_balloon_event_opaque;
356

    
357
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
358
{
359
    qemu_balloon_event = func;
360
    qemu_balloon_event_opaque = opaque;
361
}
362

    
363
void qemu_balloon(ram_addr_t target)
364
{
365
    if (qemu_balloon_event)
366
        qemu_balloon_event(qemu_balloon_event_opaque, target);
367
}
368

    
369
ram_addr_t qemu_balloon_status(void)
370
{
371
    if (qemu_balloon_event)
372
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
373
    return 0;
374
}
375

    
376
/***********************************************************/
377
/* keyboard/mouse */
378

    
379
static QEMUPutKBDEvent *qemu_put_kbd_event;
380
static void *qemu_put_kbd_event_opaque;
381
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
382
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
383

    
384
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
385
{
386
    qemu_put_kbd_event_opaque = opaque;
387
    qemu_put_kbd_event = func;
388
}
389

    
390
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
391
                                                void *opaque, int absolute,
392
                                                const char *name)
393
{
394
    QEMUPutMouseEntry *s, *cursor;
395

    
396
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
397

    
398
    s->qemu_put_mouse_event = func;
399
    s->qemu_put_mouse_event_opaque = opaque;
400
    s->qemu_put_mouse_event_absolute = absolute;
401
    s->qemu_put_mouse_event_name = qemu_strdup(name);
402
    s->next = NULL;
403

    
404
    if (!qemu_put_mouse_event_head) {
405
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
406
        return s;
407
    }
408

    
409
    cursor = qemu_put_mouse_event_head;
410
    while (cursor->next != NULL)
411
        cursor = cursor->next;
412

    
413
    cursor->next = s;
414
    qemu_put_mouse_event_current = s;
415

    
416
    return s;
417
}
418

    
419
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
420
{
421
    QEMUPutMouseEntry *prev = NULL, *cursor;
422

    
423
    if (!qemu_put_mouse_event_head || entry == NULL)
424
        return;
425

    
426
    cursor = qemu_put_mouse_event_head;
427
    while (cursor != NULL && cursor != entry) {
428
        prev = cursor;
429
        cursor = cursor->next;
430
    }
431

    
432
    if (cursor == NULL) // does not exist or list empty
433
        return;
434
    else if (prev == NULL) { // entry is head
435
        qemu_put_mouse_event_head = cursor->next;
436
        if (qemu_put_mouse_event_current == entry)
437
            qemu_put_mouse_event_current = cursor->next;
438
        qemu_free(entry->qemu_put_mouse_event_name);
439
        qemu_free(entry);
440
        return;
441
    }
442

    
443
    prev->next = entry->next;
444

    
445
    if (qemu_put_mouse_event_current == entry)
446
        qemu_put_mouse_event_current = prev;
447

    
448
    qemu_free(entry->qemu_put_mouse_event_name);
449
    qemu_free(entry);
450
}
451

    
452
void kbd_put_keycode(int keycode)
453
{
454
    if (qemu_put_kbd_event) {
455
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
456
    }
457
}
458

    
459
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
460
{
461
    QEMUPutMouseEvent *mouse_event;
462
    void *mouse_event_opaque;
463
    int width;
464

    
465
    if (!qemu_put_mouse_event_current) {
466
        return;
467
    }
468

    
469
    mouse_event =
470
        qemu_put_mouse_event_current->qemu_put_mouse_event;
471
    mouse_event_opaque =
472
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
473

    
474
    if (mouse_event) {
475
        if (graphic_rotate) {
476
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
477
                width = 0x7fff;
478
            else
479
                width = graphic_width - 1;
480
            mouse_event(mouse_event_opaque,
481
                                 width - dy, dx, dz, buttons_state);
482
        } else
483
            mouse_event(mouse_event_opaque,
484
                                 dx, dy, dz, buttons_state);
485
    }
486
}
487

    
488
int kbd_mouse_is_absolute(void)
489
{
490
    if (!qemu_put_mouse_event_current)
491
        return 0;
492

    
493
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
494
}
495

    
496
static void info_mice_iter(QObject *data, void *opaque)
497
{
498
    QDict *mouse;
499
    Monitor *mon = opaque;
500

    
501
    mouse = qobject_to_qdict(data);
502
    monitor_printf(mon, "%c Mouse #%" PRId64 ": %s\n",
503
                  (qdict_get_bool(mouse, "current") ? '*' : ' '),
504
                  qdict_get_int(mouse, "index"), qdict_get_str(mouse, "name"));
505
}
506

    
507
void do_info_mice_print(Monitor *mon, const QObject *data)
508
{
509
    QList *mice_list;
510

    
511
    mice_list = qobject_to_qlist(data);
512
    if (qlist_empty(mice_list)) {
513
        monitor_printf(mon, "No mouse devices connected\n");
514
        return;
515
    }
516

    
517
    qlist_iter(mice_list, info_mice_iter, mon);
518
}
519

    
520
/**
521
 * do_info_mice(): Show VM mice information
522
 *
523
 * Each mouse is represented by a QDict, the returned QObject is a QList of
524
 * all mice.
525
 *
526
 * The mouse QDict contains the following:
527
 *
528
 * - "name": mouse's name
529
 * - "index": mouse's index
530
 * - "current": true if this mouse is receiving events, false otherwise
531
 *
532
 * Example:
533
 *
534
 * [ { "name": "QEMU Microsoft Mouse", "index": 0, "current": false },
535
 *   { "name": "QEMU PS/2 Mouse", "index": 1, "current": true } ]
536
 */
537
void do_info_mice(Monitor *mon, QObject **ret_data)
538
{
539
    QEMUPutMouseEntry *cursor;
540
    QList *mice_list;
541
    int index = 0;
542

    
543
    mice_list = qlist_new();
544

    
545
    if (!qemu_put_mouse_event_head) {
546
        goto out;
547
    }
548

    
549
    cursor = qemu_put_mouse_event_head;
550
    while (cursor != NULL) {
551
        QObject *obj;
552
        obj = qobject_from_jsonf("{ 'name': %s, 'index': %d, 'current': %i }",
553
                                 cursor->qemu_put_mouse_event_name,
554
                                 index, cursor == qemu_put_mouse_event_current);
555
        qlist_append_obj(mice_list, obj);
556
        index++;
557
        cursor = cursor->next;
558
    }
559

    
560
out:
561
    *ret_data = QOBJECT(mice_list);
562
}
563

    
564
void do_mouse_set(Monitor *mon, const QDict *qdict)
565
{
566
    QEMUPutMouseEntry *cursor;
567
    int i = 0;
568
    int index = qdict_get_int(qdict, "index");
569

    
570
    if (!qemu_put_mouse_event_head) {
571
        monitor_printf(mon, "No mouse devices connected\n");
572
        return;
573
    }
574

    
575
    cursor = qemu_put_mouse_event_head;
576
    while (cursor != NULL && index != i) {
577
        i++;
578
        cursor = cursor->next;
579
    }
580

    
581
    if (cursor != NULL)
582
        qemu_put_mouse_event_current = cursor;
583
    else
584
        monitor_printf(mon, "Mouse at given index not found\n");
585
}
586

    
587
/* compute with 96 bit intermediate result: (a*b)/c */
588
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
589
{
590
    union {
591
        uint64_t ll;
592
        struct {
593
#ifdef HOST_WORDS_BIGENDIAN
594
            uint32_t high, low;
595
#else
596
            uint32_t low, high;
597
#endif
598
        } l;
599
    } u, res;
600
    uint64_t rl, rh;
601

    
602
    u.ll = a;
603
    rl = (uint64_t)u.l.low * (uint64_t)b;
604
    rh = (uint64_t)u.l.high * (uint64_t)b;
605
    rh += (rl >> 32);
606
    res.l.high = rh / c;
607
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
608
    return res.ll;
609
}
610

    
611
/***********************************************************/
612
/* real time host monotonic timer */
613

    
614
static int64_t get_clock_realtime(void)
615
{
616
    struct timeval tv;
617

    
618
    gettimeofday(&tv, NULL);
619
    return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
620
}
621

    
622
#ifdef WIN32
623

    
624
static int64_t clock_freq;
625

    
626
static void init_get_clock(void)
627
{
628
    LARGE_INTEGER freq;
629
    int ret;
630
    ret = QueryPerformanceFrequency(&freq);
631
    if (ret == 0) {
632
        fprintf(stderr, "Could not calibrate ticks\n");
633
        exit(1);
634
    }
635
    clock_freq = freq.QuadPart;
636
}
637

    
638
static int64_t get_clock(void)
639
{
640
    LARGE_INTEGER ti;
641
    QueryPerformanceCounter(&ti);
642
    return muldiv64(ti.QuadPart, get_ticks_per_sec(), clock_freq);
643
}
644

    
645
#else
646

    
647
static int use_rt_clock;
648

    
649
static void init_get_clock(void)
650
{
651
    use_rt_clock = 0;
652
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
653
    || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
654
    {
655
        struct timespec ts;
656
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
657
            use_rt_clock = 1;
658
        }
659
    }
660
#endif
661
}
662

    
663
static int64_t get_clock(void)
664
{
665
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
666
        || defined(__DragonFly__) || defined(__FreeBSD_kernel__)
667
    if (use_rt_clock) {
668
        struct timespec ts;
669
        clock_gettime(CLOCK_MONOTONIC, &ts);
670
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
671
    } else
672
#endif
673
    {
674
        /* XXX: using gettimeofday leads to problems if the date
675
           changes, so it should be avoided. */
676
        return get_clock_realtime();
677
    }
678
}
679
#endif
680

    
681
/* Return the virtual CPU time, based on the instruction counter.  */
682
static int64_t cpu_get_icount(void)
683
{
684
    int64_t icount;
685
    CPUState *env = cpu_single_env;;
686
    icount = qemu_icount;
687
    if (env) {
688
        if (!can_do_io(env))
689
            fprintf(stderr, "Bad clock read\n");
690
        icount -= (env->icount_decr.u16.low + env->icount_extra);
691
    }
692
    return qemu_icount_bias + (icount << icount_time_shift);
693
}
694

    
695
/***********************************************************/
696
/* guest cycle counter */
697

    
698
typedef struct TimersState {
699
    int64_t cpu_ticks_prev;
700
    int64_t cpu_ticks_offset;
701
    int64_t cpu_clock_offset;
702
    int32_t cpu_ticks_enabled;
703
    int64_t dummy;
704
} TimersState;
705

    
706
TimersState timers_state;
707

    
708
/* return the host CPU cycle counter and handle stop/restart */
709
int64_t cpu_get_ticks(void)
710
{
711
    if (use_icount) {
712
        return cpu_get_icount();
713
    }
714
    if (!timers_state.cpu_ticks_enabled) {
715
        return timers_state.cpu_ticks_offset;
716
    } else {
717
        int64_t ticks;
718
        ticks = cpu_get_real_ticks();
719
        if (timers_state.cpu_ticks_prev > ticks) {
720
            /* Note: non increasing ticks may happen if the host uses
721
               software suspend */
722
            timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
723
        }
724
        timers_state.cpu_ticks_prev = ticks;
725
        return ticks + timers_state.cpu_ticks_offset;
726
    }
727
}
728

    
729
/* return the host CPU monotonic timer and handle stop/restart */
730
static int64_t cpu_get_clock(void)
731
{
732
    int64_t ti;
733
    if (!timers_state.cpu_ticks_enabled) {
734
        return timers_state.cpu_clock_offset;
735
    } else {
736
        ti = get_clock();
737
        return ti + timers_state.cpu_clock_offset;
738
    }
739
}
740

    
741
/* enable cpu_get_ticks() */
742
void cpu_enable_ticks(void)
743
{
744
    if (!timers_state.cpu_ticks_enabled) {
745
        timers_state.cpu_ticks_offset -= cpu_get_real_ticks();
746
        timers_state.cpu_clock_offset -= get_clock();
747
        timers_state.cpu_ticks_enabled = 1;
748
    }
749
}
750

    
751
/* disable cpu_get_ticks() : the clock is stopped. You must not call
752
   cpu_get_ticks() after that.  */
753
void cpu_disable_ticks(void)
754
{
755
    if (timers_state.cpu_ticks_enabled) {
756
        timers_state.cpu_ticks_offset = cpu_get_ticks();
757
        timers_state.cpu_clock_offset = cpu_get_clock();
758
        timers_state.cpu_ticks_enabled = 0;
759
    }
760
}
761

    
762
/***********************************************************/
763
/* timers */
764

    
765
#define QEMU_CLOCK_REALTIME 0
766
#define QEMU_CLOCK_VIRTUAL  1
767
#define QEMU_CLOCK_HOST     2
768

    
769
struct QEMUClock {
770
    int type;
771
    /* XXX: add frequency */
772
};
773

    
774
struct QEMUTimer {
775
    QEMUClock *clock;
776
    int64_t expire_time;
777
    QEMUTimerCB *cb;
778
    void *opaque;
779
    struct QEMUTimer *next;
780
};
781

    
782
struct qemu_alarm_timer {
783
    char const *name;
784
    unsigned int flags;
785

    
786
    int (*start)(struct qemu_alarm_timer *t);
787
    void (*stop)(struct qemu_alarm_timer *t);
788
    void (*rearm)(struct qemu_alarm_timer *t);
789
    void *priv;
790
};
791

    
792
#define ALARM_FLAG_DYNTICKS  0x1
793
#define ALARM_FLAG_EXPIRED   0x2
794

    
795
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
796
{
797
    return t && (t->flags & ALARM_FLAG_DYNTICKS);
798
}
799

    
800
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
801
{
802
    if (!alarm_has_dynticks(t))
803
        return;
804

    
805
    t->rearm(t);
806
}
807

    
808
/* TODO: MIN_TIMER_REARM_US should be optimized */
809
#define MIN_TIMER_REARM_US 250
810

    
811
static struct qemu_alarm_timer *alarm_timer;
812

    
813
#ifdef _WIN32
814

    
815
struct qemu_alarm_win32 {
816
    MMRESULT timerId;
817
    unsigned int period;
818
} alarm_win32_data = {0, -1};
819

    
820
static int win32_start_timer(struct qemu_alarm_timer *t);
821
static void win32_stop_timer(struct qemu_alarm_timer *t);
822
static void win32_rearm_timer(struct qemu_alarm_timer *t);
823

    
824
#else
825

    
826
static int unix_start_timer(struct qemu_alarm_timer *t);
827
static void unix_stop_timer(struct qemu_alarm_timer *t);
828

    
829
#ifdef __linux__
830

    
831
static int dynticks_start_timer(struct qemu_alarm_timer *t);
832
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
833
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
834

    
835
static int hpet_start_timer(struct qemu_alarm_timer *t);
836
static void hpet_stop_timer(struct qemu_alarm_timer *t);
837

    
838
static int rtc_start_timer(struct qemu_alarm_timer *t);
839
static void rtc_stop_timer(struct qemu_alarm_timer *t);
840

    
841
#endif /* __linux__ */
842

    
843
#endif /* _WIN32 */
844

    
845
/* Correlation between real and virtual time is always going to be
846
   fairly approximate, so ignore small variation.
847
   When the guest is idle real and virtual time will be aligned in
848
   the IO wait loop.  */
849
#define ICOUNT_WOBBLE (get_ticks_per_sec() / 10)
850

    
851
static void icount_adjust(void)
852
{
853
    int64_t cur_time;
854
    int64_t cur_icount;
855
    int64_t delta;
856
    static int64_t last_delta;
857
    /* If the VM is not running, then do nothing.  */
858
    if (!vm_running)
859
        return;
860

    
861
    cur_time = cpu_get_clock();
862
    cur_icount = qemu_get_clock(vm_clock);
863
    delta = cur_icount - cur_time;
864
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
865
    if (delta > 0
866
        && last_delta + ICOUNT_WOBBLE < delta * 2
867
        && icount_time_shift > 0) {
868
        /* The guest is getting too far ahead.  Slow time down.  */
869
        icount_time_shift--;
870
    }
871
    if (delta < 0
872
        && last_delta - ICOUNT_WOBBLE > delta * 2
873
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
874
        /* The guest is getting too far behind.  Speed time up.  */
875
        icount_time_shift++;
876
    }
877
    last_delta = delta;
878
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
879
}
880

    
881
static void icount_adjust_rt(void * opaque)
882
{
883
    qemu_mod_timer(icount_rt_timer,
884
                   qemu_get_clock(rt_clock) + 1000);
885
    icount_adjust();
886
}
887

    
888
static void icount_adjust_vm(void * opaque)
889
{
890
    qemu_mod_timer(icount_vm_timer,
891
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
892
    icount_adjust();
893
}
894

    
895
static void init_icount_adjust(void)
896
{
897
    /* Have both realtime and virtual time triggers for speed adjustment.
898
       The realtime trigger catches emulated time passing too slowly,
899
       the virtual time trigger catches emulated time passing too fast.
900
       Realtime triggers occur even when idle, so use them less frequently
901
       than VM triggers.  */
902
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
903
    qemu_mod_timer(icount_rt_timer,
904
                   qemu_get_clock(rt_clock) + 1000);
905
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
906
    qemu_mod_timer(icount_vm_timer,
907
                   qemu_get_clock(vm_clock) + get_ticks_per_sec() / 10);
908
}
909

    
910
static struct qemu_alarm_timer alarm_timers[] = {
911
#ifndef _WIN32
912
#ifdef __linux__
913
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
914
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
915
    /* HPET - if available - is preferred */
916
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
917
    /* ...otherwise try RTC */
918
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
919
#endif
920
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
921
#else
922
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
923
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
924
    {"win32", 0, win32_start_timer,
925
     win32_stop_timer, NULL, &alarm_win32_data},
926
#endif
927
    {NULL, }
928
};
929

    
930
static void show_available_alarms(void)
931
{
932
    int i;
933

    
934
    printf("Available alarm timers, in order of precedence:\n");
935
    for (i = 0; alarm_timers[i].name; i++)
936
        printf("%s\n", alarm_timers[i].name);
937
}
938

    
939
static void configure_alarms(char const *opt)
940
{
941
    int i;
942
    int cur = 0;
943
    int count = ARRAY_SIZE(alarm_timers) - 1;
944
    char *arg;
945
    char *name;
946
    struct qemu_alarm_timer tmp;
947

    
948
    if (!strcmp(opt, "?")) {
949
        show_available_alarms();
950
        exit(0);
951
    }
952

    
953
    arg = qemu_strdup(opt);
954

    
955
    /* Reorder the array */
956
    name = strtok(arg, ",");
957
    while (name) {
958
        for (i = 0; i < count && alarm_timers[i].name; i++) {
959
            if (!strcmp(alarm_timers[i].name, name))
960
                break;
961
        }
962

    
963
        if (i == count) {
964
            fprintf(stderr, "Unknown clock %s\n", name);
965
            goto next;
966
        }
967

    
968
        if (i < cur)
969
            /* Ignore */
970
            goto next;
971

    
972
        /* Swap */
973
        tmp = alarm_timers[i];
974
        alarm_timers[i] = alarm_timers[cur];
975
        alarm_timers[cur] = tmp;
976

    
977
        cur++;
978
next:
979
        name = strtok(NULL, ",");
980
    }
981

    
982
    qemu_free(arg);
983

    
984
    if (cur) {
985
        /* Disable remaining timers */
986
        for (i = cur; i < count; i++)
987
            alarm_timers[i].name = NULL;
988
    } else {
989
        show_available_alarms();
990
        exit(1);
991
    }
992
}
993

    
994
#define QEMU_NUM_CLOCKS 3
995

    
996
QEMUClock *rt_clock;
997
QEMUClock *vm_clock;
998
QEMUClock *host_clock;
999

    
1000
static QEMUTimer *active_timers[QEMU_NUM_CLOCKS];
1001

    
1002
static QEMUClock *qemu_new_clock(int type)
1003
{
1004
    QEMUClock *clock;
1005
    clock = qemu_mallocz(sizeof(QEMUClock));
1006
    clock->type = type;
1007
    return clock;
1008
}
1009

    
1010
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1011
{
1012
    QEMUTimer *ts;
1013

    
1014
    ts = qemu_mallocz(sizeof(QEMUTimer));
1015
    ts->clock = clock;
1016
    ts->cb = cb;
1017
    ts->opaque = opaque;
1018
    return ts;
1019
}
1020

    
1021
void qemu_free_timer(QEMUTimer *ts)
1022
{
1023
    qemu_free(ts);
1024
}
1025

    
1026
/* stop a timer, but do not dealloc it */
1027
void qemu_del_timer(QEMUTimer *ts)
1028
{
1029
    QEMUTimer **pt, *t;
1030

    
1031
    /* NOTE: this code must be signal safe because
1032
       qemu_timer_expired() can be called from a signal. */
1033
    pt = &active_timers[ts->clock->type];
1034
    for(;;) {
1035
        t = *pt;
1036
        if (!t)
1037
            break;
1038
        if (t == ts) {
1039
            *pt = t->next;
1040
            break;
1041
        }
1042
        pt = &t->next;
1043
    }
1044
}
1045

    
1046
/* modify the current timer so that it will be fired when current_time
1047
   >= expire_time. The corresponding callback will be called. */
1048
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1049
{
1050
    QEMUTimer **pt, *t;
1051

    
1052
    qemu_del_timer(ts);
1053

    
1054
    /* add the timer in the sorted list */
1055
    /* NOTE: this code must be signal safe because
1056
       qemu_timer_expired() can be called from a signal. */
1057
    pt = &active_timers[ts->clock->type];
1058
    for(;;) {
1059
        t = *pt;
1060
        if (!t)
1061
            break;
1062
        if (t->expire_time > expire_time)
1063
            break;
1064
        pt = &t->next;
1065
    }
1066
    ts->expire_time = expire_time;
1067
    ts->next = *pt;
1068
    *pt = ts;
1069

    
1070
    /* Rearm if necessary  */
1071
    if (pt == &active_timers[ts->clock->type]) {
1072
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1073
            qemu_rearm_alarm_timer(alarm_timer);
1074
        }
1075
        /* Interrupt execution to force deadline recalculation.  */
1076
        if (use_icount)
1077
            qemu_notify_event();
1078
    }
1079
}
1080

    
1081
int qemu_timer_pending(QEMUTimer *ts)
1082
{
1083
    QEMUTimer *t;
1084
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1085
        if (t == ts)
1086
            return 1;
1087
    }
1088
    return 0;
1089
}
1090

    
1091
int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1092
{
1093
    if (!timer_head)
1094
        return 0;
1095
    return (timer_head->expire_time <= current_time);
1096
}
1097

    
1098
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1099
{
1100
    QEMUTimer *ts;
1101

    
1102
    for(;;) {
1103
        ts = *ptimer_head;
1104
        if (!ts || ts->expire_time > current_time)
1105
            break;
1106
        /* remove timer from the list before calling the callback */
1107
        *ptimer_head = ts->next;
1108
        ts->next = NULL;
1109

    
1110
        /* run the callback (the timer list can be modified) */
1111
        ts->cb(ts->opaque);
1112
    }
1113
}
1114

    
1115
int64_t qemu_get_clock(QEMUClock *clock)
1116
{
1117
    switch(clock->type) {
1118
    case QEMU_CLOCK_REALTIME:
1119
        return get_clock() / 1000000;
1120
    default:
1121
    case QEMU_CLOCK_VIRTUAL:
1122
        if (use_icount) {
1123
            return cpu_get_icount();
1124
        } else {
1125
            return cpu_get_clock();
1126
        }
1127
    case QEMU_CLOCK_HOST:
1128
        return get_clock_realtime();
1129
    }
1130
}
1131

    
1132
static void init_clocks(void)
1133
{
1134
    init_get_clock();
1135
    rt_clock = qemu_new_clock(QEMU_CLOCK_REALTIME);
1136
    vm_clock = qemu_new_clock(QEMU_CLOCK_VIRTUAL);
1137
    host_clock = qemu_new_clock(QEMU_CLOCK_HOST);
1138

    
1139
    rtc_clock = host_clock;
1140
}
1141

    
1142
/* save a timer */
1143
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1144
{
1145
    uint64_t expire_time;
1146

    
1147
    if (qemu_timer_pending(ts)) {
1148
        expire_time = ts->expire_time;
1149
    } else {
1150
        expire_time = -1;
1151
    }
1152
    qemu_put_be64(f, expire_time);
1153
}
1154

    
1155
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1156
{
1157
    uint64_t expire_time;
1158

    
1159
    expire_time = qemu_get_be64(f);
1160
    if (expire_time != -1) {
1161
        qemu_mod_timer(ts, expire_time);
1162
    } else {
1163
        qemu_del_timer(ts);
1164
    }
1165
}
1166

    
1167
static const VMStateDescription vmstate_timers = {
1168
    .name = "timer",
1169
    .version_id = 2,
1170
    .minimum_version_id = 1,
1171
    .minimum_version_id_old = 1,
1172
    .fields      = (VMStateField []) {
1173
        VMSTATE_INT64(cpu_ticks_offset, TimersState),
1174
        VMSTATE_INT64(dummy, TimersState),
1175
        VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
1176
        VMSTATE_END_OF_LIST()
1177
    }
1178
};
1179

    
1180
static void qemu_event_increment(void);
1181

    
1182
#ifdef _WIN32
1183
static void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1184
                                        DWORD_PTR dwUser, DWORD_PTR dw1,
1185
                                        DWORD_PTR dw2)
1186
#else
1187
static void host_alarm_handler(int host_signum)
1188
#endif
1189
{
1190
#if 0
1191
#define DISP_FREQ 1000
1192
    {
1193
        static int64_t delta_min = INT64_MAX;
1194
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1195
        static int count;
1196
        ti = qemu_get_clock(vm_clock);
1197
        if (last_clock != 0) {
1198
            delta = ti - last_clock;
1199
            if (delta < delta_min)
1200
                delta_min = delta;
1201
            if (delta > delta_max)
1202
                delta_max = delta;
1203
            delta_cum += delta;
1204
            if (++count == DISP_FREQ) {
1205
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1206
                       muldiv64(delta_min, 1000000, get_ticks_per_sec()),
1207
                       muldiv64(delta_max, 1000000, get_ticks_per_sec()),
1208
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, get_ticks_per_sec()),
1209
                       (double)get_ticks_per_sec() / ((double)delta_cum / DISP_FREQ));
1210
                count = 0;
1211
                delta_min = INT64_MAX;
1212
                delta_max = 0;
1213
                delta_cum = 0;
1214
            }
1215
        }
1216
        last_clock = ti;
1217
    }
1218
#endif
1219
    if (alarm_has_dynticks(alarm_timer) ||
1220
        (!use_icount &&
1221
            qemu_timer_expired(active_timers[QEMU_CLOCK_VIRTUAL],
1222
                               qemu_get_clock(vm_clock))) ||
1223
        qemu_timer_expired(active_timers[QEMU_CLOCK_REALTIME],
1224
                           qemu_get_clock(rt_clock)) ||
1225
        qemu_timer_expired(active_timers[QEMU_CLOCK_HOST],
1226
                           qemu_get_clock(host_clock))) {
1227
        qemu_event_increment();
1228
        if (alarm_timer) alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1229

    
1230
#ifndef CONFIG_IOTHREAD
1231
        if (next_cpu) {
1232
            /* stop the currently executing cpu because a timer occured */
1233
            cpu_exit(next_cpu);
1234
        }
1235
#endif
1236
        timer_alarm_pending = 1;
1237
        qemu_notify_event();
1238
    }
1239
}
1240

    
1241
static int64_t qemu_next_deadline(void)
1242
{
1243
    /* To avoid problems with overflow limit this to 2^32.  */
1244
    int64_t delta = INT32_MAX;
1245

    
1246
    if (active_timers[QEMU_CLOCK_VIRTUAL]) {
1247
        delta = active_timers[QEMU_CLOCK_VIRTUAL]->expire_time -
1248
                     qemu_get_clock(vm_clock);
1249
    }
1250
    if (active_timers[QEMU_CLOCK_HOST]) {
1251
        int64_t hdelta = active_timers[QEMU_CLOCK_HOST]->expire_time -
1252
                 qemu_get_clock(host_clock);
1253
        if (hdelta < delta)
1254
            delta = hdelta;
1255
    }
1256

    
1257
    if (delta < 0)
1258
        delta = 0;
1259

    
1260
    return delta;
1261
}
1262

    
1263
#if defined(__linux__)
1264
static uint64_t qemu_next_deadline_dyntick(void)
1265
{
1266
    int64_t delta;
1267
    int64_t rtdelta;
1268

    
1269
    if (use_icount)
1270
        delta = INT32_MAX;
1271
    else
1272
        delta = (qemu_next_deadline() + 999) / 1000;
1273

    
1274
    if (active_timers[QEMU_CLOCK_REALTIME]) {
1275
        rtdelta = (active_timers[QEMU_CLOCK_REALTIME]->expire_time -
1276
                 qemu_get_clock(rt_clock))*1000;
1277
        if (rtdelta < delta)
1278
            delta = rtdelta;
1279
    }
1280

    
1281
    if (delta < MIN_TIMER_REARM_US)
1282
        delta = MIN_TIMER_REARM_US;
1283

    
1284
    return delta;
1285
}
1286
#endif
1287

    
1288
#ifndef _WIN32
1289

    
1290
/* Sets a specific flag */
1291
static int fcntl_setfl(int fd, int flag)
1292
{
1293
    int flags;
1294

    
1295
    flags = fcntl(fd, F_GETFL);
1296
    if (flags == -1)
1297
        return -errno;
1298

    
1299
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1300
        return -errno;
1301

    
1302
    return 0;
1303
}
1304

    
1305
#if defined(__linux__)
1306

    
1307
#define RTC_FREQ 1024
1308

    
1309
static void enable_sigio_timer(int fd)
1310
{
1311
    struct sigaction act;
1312

    
1313
    /* timer signal */
1314
    sigfillset(&act.sa_mask);
1315
    act.sa_flags = 0;
1316
    act.sa_handler = host_alarm_handler;
1317

    
1318
    sigaction(SIGIO, &act, NULL);
1319
    fcntl_setfl(fd, O_ASYNC);
1320
    fcntl(fd, F_SETOWN, getpid());
1321
}
1322

    
1323
static int hpet_start_timer(struct qemu_alarm_timer *t)
1324
{
1325
    struct hpet_info info;
1326
    int r, fd;
1327

    
1328
    fd = qemu_open("/dev/hpet", O_RDONLY);
1329
    if (fd < 0)
1330
        return -1;
1331

    
1332
    /* Set frequency */
1333
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1334
    if (r < 0) {
1335
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1336
                "error, but for better emulation accuracy type:\n"
1337
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1338
        goto fail;
1339
    }
1340

    
1341
    /* Check capabilities */
1342
    r = ioctl(fd, HPET_INFO, &info);
1343
    if (r < 0)
1344
        goto fail;
1345

    
1346
    /* Enable periodic mode */
1347
    r = ioctl(fd, HPET_EPI, 0);
1348
    if (info.hi_flags && (r < 0))
1349
        goto fail;
1350

    
1351
    /* Enable interrupt */
1352
    r = ioctl(fd, HPET_IE_ON, 0);
1353
    if (r < 0)
1354
        goto fail;
1355

    
1356
    enable_sigio_timer(fd);
1357
    t->priv = (void *)(long)fd;
1358

    
1359
    return 0;
1360
fail:
1361
    close(fd);
1362
    return -1;
1363
}
1364

    
1365
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1366
{
1367
    int fd = (long)t->priv;
1368

    
1369
    close(fd);
1370
}
1371

    
1372
static int rtc_start_timer(struct qemu_alarm_timer *t)
1373
{
1374
    int rtc_fd;
1375
    unsigned long current_rtc_freq = 0;
1376

    
1377
    TFR(rtc_fd = qemu_open("/dev/rtc", O_RDONLY));
1378
    if (rtc_fd < 0)
1379
        return -1;
1380
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1381
    if (current_rtc_freq != RTC_FREQ &&
1382
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1383
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1384
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1385
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1386
        goto fail;
1387
    }
1388
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1389
    fail:
1390
        close(rtc_fd);
1391
        return -1;
1392
    }
1393

    
1394
    enable_sigio_timer(rtc_fd);
1395

    
1396
    t->priv = (void *)(long)rtc_fd;
1397

    
1398
    return 0;
1399
}
1400

    
1401
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1402
{
1403
    int rtc_fd = (long)t->priv;
1404

    
1405
    close(rtc_fd);
1406
}
1407

    
1408
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1409
{
1410
    struct sigevent ev;
1411
    timer_t host_timer;
1412
    struct sigaction act;
1413

    
1414
    sigfillset(&act.sa_mask);
1415
    act.sa_flags = 0;
1416
    act.sa_handler = host_alarm_handler;
1417

    
1418
    sigaction(SIGALRM, &act, NULL);
1419

    
1420
    /* 
1421
     * Initialize ev struct to 0 to avoid valgrind complaining
1422
     * about uninitialized data in timer_create call
1423
     */
1424
    memset(&ev, 0, sizeof(ev));
1425
    ev.sigev_value.sival_int = 0;
1426
    ev.sigev_notify = SIGEV_SIGNAL;
1427
    ev.sigev_signo = SIGALRM;
1428

    
1429
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1430
        perror("timer_create");
1431

    
1432
        /* disable dynticks */
1433
        fprintf(stderr, "Dynamic Ticks disabled\n");
1434

    
1435
        return -1;
1436
    }
1437

    
1438
    t->priv = (void *)(long)host_timer;
1439

    
1440
    return 0;
1441
}
1442

    
1443
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1444
{
1445
    timer_t host_timer = (timer_t)(long)t->priv;
1446

    
1447
    timer_delete(host_timer);
1448
}
1449

    
1450
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1451
{
1452
    timer_t host_timer = (timer_t)(long)t->priv;
1453
    struct itimerspec timeout;
1454
    int64_t nearest_delta_us = INT64_MAX;
1455
    int64_t current_us;
1456

    
1457
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1458
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1459
        !active_timers[QEMU_CLOCK_HOST])
1460
        return;
1461

    
1462
    nearest_delta_us = qemu_next_deadline_dyntick();
1463

    
1464
    /* check whether a timer is already running */
1465
    if (timer_gettime(host_timer, &timeout)) {
1466
        perror("gettime");
1467
        fprintf(stderr, "Internal timer error: aborting\n");
1468
        exit(1);
1469
    }
1470
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1471
    if (current_us && current_us <= nearest_delta_us)
1472
        return;
1473

    
1474
    timeout.it_interval.tv_sec = 0;
1475
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1476
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1477
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1478
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1479
        perror("settime");
1480
        fprintf(stderr, "Internal timer error: aborting\n");
1481
        exit(1);
1482
    }
1483
}
1484

    
1485
#endif /* defined(__linux__) */
1486

    
1487
static int unix_start_timer(struct qemu_alarm_timer *t)
1488
{
1489
    struct sigaction act;
1490
    struct itimerval itv;
1491
    int err;
1492

    
1493
    /* timer signal */
1494
    sigfillset(&act.sa_mask);
1495
    act.sa_flags = 0;
1496
    act.sa_handler = host_alarm_handler;
1497

    
1498
    sigaction(SIGALRM, &act, NULL);
1499

    
1500
    itv.it_interval.tv_sec = 0;
1501
    /* for i386 kernel 2.6 to get 1 ms */
1502
    itv.it_interval.tv_usec = 999;
1503
    itv.it_value.tv_sec = 0;
1504
    itv.it_value.tv_usec = 10 * 1000;
1505

    
1506
    err = setitimer(ITIMER_REAL, &itv, NULL);
1507
    if (err)
1508
        return -1;
1509

    
1510
    return 0;
1511
}
1512

    
1513
static void unix_stop_timer(struct qemu_alarm_timer *t)
1514
{
1515
    struct itimerval itv;
1516

    
1517
    memset(&itv, 0, sizeof(itv));
1518
    setitimer(ITIMER_REAL, &itv, NULL);
1519
}
1520

    
1521
#endif /* !defined(_WIN32) */
1522

    
1523

    
1524
#ifdef _WIN32
1525

    
1526
static int win32_start_timer(struct qemu_alarm_timer *t)
1527
{
1528
    TIMECAPS tc;
1529
    struct qemu_alarm_win32 *data = t->priv;
1530
    UINT flags;
1531

    
1532
    memset(&tc, 0, sizeof(tc));
1533
    timeGetDevCaps(&tc, sizeof(tc));
1534

    
1535
    if (data->period < tc.wPeriodMin)
1536
        data->period = tc.wPeriodMin;
1537

    
1538
    timeBeginPeriod(data->period);
1539

    
1540
    flags = TIME_CALLBACK_FUNCTION;
1541
    if (alarm_has_dynticks(t))
1542
        flags |= TIME_ONESHOT;
1543
    else
1544
        flags |= TIME_PERIODIC;
1545

    
1546
    data->timerId = timeSetEvent(1,         // interval (ms)
1547
                        data->period,       // resolution
1548
                        host_alarm_handler, // function
1549
                        (DWORD)t,           // parameter
1550
                        flags);
1551

    
1552
    if (!data->timerId) {
1553
        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",
1554
                GetLastError());
1555
        timeEndPeriod(data->period);
1556
        return -1;
1557
    }
1558

    
1559
    return 0;
1560
}
1561

    
1562
static void win32_stop_timer(struct qemu_alarm_timer *t)
1563
{
1564
    struct qemu_alarm_win32 *data = t->priv;
1565

    
1566
    timeKillEvent(data->timerId);
1567
    timeEndPeriod(data->period);
1568
}
1569

    
1570
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1571
{
1572
    struct qemu_alarm_win32 *data = t->priv;
1573

    
1574
    if (!active_timers[QEMU_CLOCK_REALTIME] &&
1575
        !active_timers[QEMU_CLOCK_VIRTUAL] &&
1576
        !active_timers[QEMU_CLOCK_HOST])
1577
        return;
1578

    
1579
    timeKillEvent(data->timerId);
1580

    
1581
    data->timerId = timeSetEvent(1,
1582
                        data->period,
1583
                        host_alarm_handler,
1584
                        (DWORD)t,
1585
                        TIME_ONESHOT | TIME_PERIODIC);
1586

    
1587
    if (!data->timerId) {
1588
        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",
1589
                GetLastError());
1590

    
1591
        timeEndPeriod(data->period);
1592
        exit(1);
1593
    }
1594
}
1595

    
1596
#endif /* _WIN32 */
1597

    
1598
static int init_timer_alarm(void)
1599
{
1600
    struct qemu_alarm_timer *t = NULL;
1601
    int i, err = -1;
1602

    
1603
    for (i = 0; alarm_timers[i].name; i++) {
1604
        t = &alarm_timers[i];
1605

    
1606
        err = t->start(t);
1607
        if (!err)
1608
            break;
1609
    }
1610

    
1611
    if (err) {
1612
        err = -ENOENT;
1613
        goto fail;
1614
    }
1615

    
1616
    alarm_timer = t;
1617

    
1618
    return 0;
1619

    
1620
fail:
1621
    return err;
1622
}
1623

    
1624
static void quit_timers(void)
1625
{
1626
    alarm_timer->stop(alarm_timer);
1627
    alarm_timer = NULL;
1628
}
1629

    
1630
/***********************************************************/
1631
/* host time/date access */
1632
void qemu_get_timedate(struct tm *tm, int offset)
1633
{
1634
    time_t ti;
1635
    struct tm *ret;
1636

    
1637
    time(&ti);
1638
    ti += offset;
1639
    if (rtc_date_offset == -1) {
1640
        if (rtc_utc)
1641
            ret = gmtime(&ti);
1642
        else
1643
            ret = localtime(&ti);
1644
    } else {
1645
        ti -= rtc_date_offset;
1646
        ret = gmtime(&ti);
1647
    }
1648

    
1649
    memcpy(tm, ret, sizeof(struct tm));
1650
}
1651

    
1652
int qemu_timedate_diff(struct tm *tm)
1653
{
1654
    time_t seconds;
1655

    
1656
    if (rtc_date_offset == -1)
1657
        if (rtc_utc)
1658
            seconds = mktimegm(tm);
1659
        else
1660
            seconds = mktime(tm);
1661
    else
1662
        seconds = mktimegm(tm) + rtc_date_offset;
1663

    
1664
    return seconds - time(NULL);
1665
}
1666

    
1667
static void configure_rtc_date_offset(const char *startdate, int legacy)
1668
{
1669
    time_t rtc_start_date;
1670
    struct tm tm;
1671

    
1672
    if (!strcmp(startdate, "now") && legacy) {
1673
        rtc_date_offset = -1;
1674
    } else {
1675
        if (sscanf(startdate, "%d-%d-%dT%d:%d:%d",
1676
                   &tm.tm_year,
1677
                   &tm.tm_mon,
1678
                   &tm.tm_mday,
1679
                   &tm.tm_hour,
1680
                   &tm.tm_min,
1681
                   &tm.tm_sec) == 6) {
1682
            /* OK */
1683
        } else if (sscanf(startdate, "%d-%d-%d",
1684
                          &tm.tm_year,
1685
                          &tm.tm_mon,
1686
                          &tm.tm_mday) == 3) {
1687
            tm.tm_hour = 0;
1688
            tm.tm_min = 0;
1689
            tm.tm_sec = 0;
1690
        } else {
1691
            goto date_fail;
1692
        }
1693
        tm.tm_year -= 1900;
1694
        tm.tm_mon--;
1695
        rtc_start_date = mktimegm(&tm);
1696
        if (rtc_start_date == -1) {
1697
        date_fail:
1698
            fprintf(stderr, "Invalid date format. Valid formats are:\n"
1699
                            "'2006-06-17T16:01:21' or '2006-06-17'\n");
1700
            exit(1);
1701
        }
1702
        rtc_date_offset = time(NULL) - rtc_start_date;
1703
    }
1704
}
1705

    
1706
static void configure_rtc(QemuOpts *opts)
1707
{
1708
    const char *value;
1709

    
1710
    value = qemu_opt_get(opts, "base");
1711
    if (value) {
1712
        if (!strcmp(value, "utc")) {
1713
            rtc_utc = 1;
1714
        } else if (!strcmp(value, "localtime")) {
1715
            rtc_utc = 0;
1716
        } else {
1717
            configure_rtc_date_offset(value, 0);
1718
        }
1719
    }
1720
    value = qemu_opt_get(opts, "clock");
1721
    if (value) {
1722
        if (!strcmp(value, "host")) {
1723
            rtc_clock = host_clock;
1724
        } else if (!strcmp(value, "vm")) {
1725
            rtc_clock = vm_clock;
1726
        } else {
1727
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1728
            exit(1);
1729
        }
1730
    }
1731
#ifdef CONFIG_TARGET_I386
1732
    value = qemu_opt_get(opts, "driftfix");
1733
    if (value) {
1734
        if (!strcmp(buf, "slew")) {
1735
            rtc_td_hack = 1;
1736
        } else if (!strcmp(buf, "none")) {
1737
            rtc_td_hack = 0;
1738
        } else {
1739
            fprintf(stderr, "qemu: invalid option value '%s'\n", value);
1740
            exit(1);
1741
        }
1742
    }
1743
#endif
1744
}
1745

    
1746
#ifdef _WIN32
1747
static void socket_cleanup(void)
1748
{
1749
    WSACleanup();
1750
}
1751

    
1752
static int socket_init(void)
1753
{
1754
    WSADATA Data;
1755
    int ret, err;
1756

    
1757
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1758
    if (ret != 0) {
1759
        err = WSAGetLastError();
1760
        fprintf(stderr, "WSAStartup: %d\n", err);
1761
        return -1;
1762
    }
1763
    atexit(socket_cleanup);
1764
    return 0;
1765
}
1766
#endif
1767

    
1768
/***********************************************************/
1769
/* Bluetooth support */
1770
static int nb_hcis;
1771
static int cur_hci;
1772
static struct HCIInfo *hci_table[MAX_NICS];
1773

    
1774
static struct bt_vlan_s {
1775
    struct bt_scatternet_s net;
1776
    int id;
1777
    struct bt_vlan_s *next;
1778
} *first_bt_vlan;
1779

    
1780
/* find or alloc a new bluetooth "VLAN" */
1781
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1782
{
1783
    struct bt_vlan_s **pvlan, *vlan;
1784
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1785
        if (vlan->id == id)
1786
            return &vlan->net;
1787
    }
1788
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1789
    vlan->id = id;
1790
    pvlan = &first_bt_vlan;
1791
    while (*pvlan != NULL)
1792
        pvlan = &(*pvlan)->next;
1793
    *pvlan = vlan;
1794
    return &vlan->net;
1795
}
1796

    
1797
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1798
{
1799
}
1800

    
1801
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1802
{
1803
    return -ENOTSUP;
1804
}
1805

    
1806
static struct HCIInfo null_hci = {
1807
    .cmd_send = null_hci_send,
1808
    .sco_send = null_hci_send,
1809
    .acl_send = null_hci_send,
1810
    .bdaddr_set = null_hci_addr_set,
1811
};
1812

    
1813
struct HCIInfo *qemu_next_hci(void)
1814
{
1815
    if (cur_hci == nb_hcis)
1816
        return &null_hci;
1817

    
1818
    return hci_table[cur_hci++];
1819
}
1820

    
1821
static struct HCIInfo *hci_init(const char *str)
1822
{
1823
    char *endp;
1824
    struct bt_scatternet_s *vlan = 0;
1825

    
1826
    if (!strcmp(str, "null"))
1827
        /* null */
1828
        return &null_hci;
1829
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
1830
        /* host[:hciN] */
1831
        return bt_host_hci(str[4] ? str + 5 : "hci0");
1832
    else if (!strncmp(str, "hci", 3)) {
1833
        /* hci[,vlan=n] */
1834
        if (str[3]) {
1835
            if (!strncmp(str + 3, ",vlan=", 6)) {
1836
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
1837
                if (*endp)
1838
                    vlan = 0;
1839
            }
1840
        } else
1841
            vlan = qemu_find_bt_vlan(0);
1842
        if (vlan)
1843
           return bt_new_hci(vlan);
1844
    }
1845

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

    
1848
    return 0;
1849
}
1850

    
1851
static int bt_hci_parse(const char *str)
1852
{
1853
    struct HCIInfo *hci;
1854
    bdaddr_t bdaddr;
1855

    
1856
    if (nb_hcis >= MAX_NICS) {
1857
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
1858
        return -1;
1859
    }
1860

    
1861
    hci = hci_init(str);
1862
    if (!hci)
1863
        return -1;
1864

    
1865
    bdaddr.b[0] = 0x52;
1866
    bdaddr.b[1] = 0x54;
1867
    bdaddr.b[2] = 0x00;
1868
    bdaddr.b[3] = 0x12;
1869
    bdaddr.b[4] = 0x34;
1870
    bdaddr.b[5] = 0x56 + nb_hcis;
1871
    hci->bdaddr_set(hci, bdaddr.b);
1872

    
1873
    hci_table[nb_hcis++] = hci;
1874

    
1875
    return 0;
1876
}
1877

    
1878
static void bt_vhci_add(int vlan_id)
1879
{
1880
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
1881

    
1882
    if (!vlan->slave)
1883
        fprintf(stderr, "qemu: warning: adding a VHCI to "
1884
                        "an empty scatternet %i\n", vlan_id);
1885

    
1886
    bt_vhci_init(bt_new_hci(vlan));
1887
}
1888

    
1889
static struct bt_device_s *bt_device_add(const char *opt)
1890
{
1891
    struct bt_scatternet_s *vlan;
1892
    int vlan_id = 0;
1893
    char *endp = strstr(opt, ",vlan=");
1894
    int len = (endp ? endp - opt : strlen(opt)) + 1;
1895
    char devname[10];
1896

    
1897
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
1898

    
1899
    if (endp) {
1900
        vlan_id = strtol(endp + 6, &endp, 0);
1901
        if (*endp) {
1902
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
1903
            return 0;
1904
        }
1905
    }
1906

    
1907
    vlan = qemu_find_bt_vlan(vlan_id);
1908

    
1909
    if (!vlan->slave)
1910
        fprintf(stderr, "qemu: warning: adding a slave device to "
1911
                        "an empty scatternet %i\n", vlan_id);
1912

    
1913
    if (!strcmp(devname, "keyboard"))
1914
        return bt_keyboard_init(vlan);
1915

    
1916
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
1917
    return 0;
1918
}
1919

    
1920
static int bt_parse(const char *opt)
1921
{
1922
    const char *endp, *p;
1923
    int vlan;
1924

    
1925
    if (strstart(opt, "hci", &endp)) {
1926
        if (!*endp || *endp == ',') {
1927
            if (*endp)
1928
                if (!strstart(endp, ",vlan=", 0))
1929
                    opt = endp + 1;
1930

    
1931
            return bt_hci_parse(opt);
1932
       }
1933
    } else if (strstart(opt, "vhci", &endp)) {
1934
        if (!*endp || *endp == ',') {
1935
            if (*endp) {
1936
                if (strstart(endp, ",vlan=", &p)) {
1937
                    vlan = strtol(p, (char **) &endp, 0);
1938
                    if (*endp) {
1939
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
1940
                        return 1;
1941
                    }
1942
                } else {
1943
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
1944
                    return 1;
1945
                }
1946
            } else
1947
                vlan = 0;
1948

    
1949
            bt_vhci_add(vlan);
1950
            return 0;
1951
        }
1952
    } else if (strstart(opt, "device:", &endp))
1953
        return !bt_device_add(endp);
1954

    
1955
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
1956
    return 1;
1957
}
1958

    
1959
/***********************************************************/
1960
/* QEMU Block devices */
1961

    
1962
#define HD_ALIAS "index=%d,media=disk"
1963
#define CDROM_ALIAS "index=2,media=cdrom"
1964
#define FD_ALIAS "index=%d,if=floppy"
1965
#define PFLASH_ALIAS "if=pflash"
1966
#define MTD_ALIAS "if=mtd"
1967
#define SD_ALIAS "index=0,if=sd"
1968

    
1969
QemuOpts *drive_add(const char *file, const char *fmt, ...)
1970
{
1971
    va_list ap;
1972
    char optstr[1024];
1973
    QemuOpts *opts;
1974

    
1975
    va_start(ap, fmt);
1976
    vsnprintf(optstr, sizeof(optstr), fmt, ap);
1977
    va_end(ap);
1978

    
1979
    opts = qemu_opts_parse(&qemu_drive_opts, optstr, NULL);
1980
    if (!opts) {
1981
        fprintf(stderr, "%s: huh? duplicate? (%s)\n",
1982
                __FUNCTION__, optstr);
1983
        return NULL;
1984
    }
1985
    if (file)
1986
        qemu_opt_set(opts, "file", file);
1987
    return opts;
1988
}
1989

    
1990
DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
1991
{
1992
    DriveInfo *dinfo;
1993

    
1994
    /* seek interface, bus and unit */
1995

    
1996
    QTAILQ_FOREACH(dinfo, &drives, next) {
1997
        if (dinfo->type == type &&
1998
            dinfo->bus == bus &&
1999
            dinfo->unit == unit)
2000
            return dinfo;
2001
    }
2002

    
2003
    return NULL;
2004
}
2005

    
2006
DriveInfo *drive_get_by_id(const char *id)
2007
{
2008
    DriveInfo *dinfo;
2009

    
2010
    QTAILQ_FOREACH(dinfo, &drives, next) {
2011
        if (strcmp(id, dinfo->id))
2012
            continue;
2013
        return dinfo;
2014
    }
2015
    return NULL;
2016
}
2017

    
2018
int drive_get_max_bus(BlockInterfaceType type)
2019
{
2020
    int max_bus;
2021
    DriveInfo *dinfo;
2022

    
2023
    max_bus = -1;
2024
    QTAILQ_FOREACH(dinfo, &drives, next) {
2025
        if(dinfo->type == type &&
2026
           dinfo->bus > max_bus)
2027
            max_bus = dinfo->bus;
2028
    }
2029
    return max_bus;
2030
}
2031

    
2032
const char *drive_get_serial(BlockDriverState *bdrv)
2033
{
2034
    DriveInfo *dinfo;
2035

    
2036
    QTAILQ_FOREACH(dinfo, &drives, next) {
2037
        if (dinfo->bdrv == bdrv)
2038
            return dinfo->serial;
2039
    }
2040

    
2041
    return "\0";
2042
}
2043

    
2044
BlockInterfaceErrorAction drive_get_on_error(
2045
    BlockDriverState *bdrv, int is_read)
2046
{
2047
    DriveInfo *dinfo;
2048

    
2049
    QTAILQ_FOREACH(dinfo, &drives, next) {
2050
        if (dinfo->bdrv == bdrv)
2051
            return is_read ? dinfo->on_read_error : dinfo->on_write_error;
2052
    }
2053

    
2054
    return is_read ? BLOCK_ERR_REPORT : BLOCK_ERR_STOP_ENOSPC;
2055
}
2056

    
2057
static void bdrv_format_print(void *opaque, const char *name)
2058
{
2059
    fprintf(stderr, " %s", name);
2060
}
2061

    
2062
void drive_uninit(DriveInfo *dinfo)
2063
{
2064
    qemu_opts_del(dinfo->opts);
2065
    bdrv_delete(dinfo->bdrv);
2066
    QTAILQ_REMOVE(&drives, dinfo, next);
2067
    qemu_free(dinfo);
2068
}
2069

    
2070
static int parse_block_error_action(const char *buf, int is_read)
2071
{
2072
    if (!strcmp(buf, "ignore")) {
2073
        return BLOCK_ERR_IGNORE;
2074
    } else if (!is_read && !strcmp(buf, "enospc")) {
2075
        return BLOCK_ERR_STOP_ENOSPC;
2076
    } else if (!strcmp(buf, "stop")) {
2077
        return BLOCK_ERR_STOP_ANY;
2078
    } else if (!strcmp(buf, "report")) {
2079
        return BLOCK_ERR_REPORT;
2080
    } else {
2081
        fprintf(stderr, "qemu: '%s' invalid %s error action\n",
2082
            buf, is_read ? "read" : "write");
2083
        return -1;
2084
    }
2085
}
2086

    
2087
DriveInfo *drive_init(QemuOpts *opts, void *opaque,
2088
                      int *fatal_error)
2089
{
2090
    const char *buf;
2091
    const char *file = NULL;
2092
    char devname[128];
2093
    const char *serial;
2094
    const char *mediastr = "";
2095
    BlockInterfaceType type;
2096
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2097
    int bus_id, unit_id;
2098
    int cyls, heads, secs, translation;
2099
    BlockDriver *drv = NULL;
2100
    QEMUMachine *machine = opaque;
2101
    int max_devs;
2102
    int index;
2103
    int cache;
2104
    int aio = 0;
2105
    int ro = 0;
2106
    int bdrv_flags;
2107
    int on_read_error, on_write_error;
2108
    const char *devaddr;
2109
    DriveInfo *dinfo;
2110
    int snapshot = 0;
2111

    
2112
    *fatal_error = 1;
2113

    
2114
    translation = BIOS_ATA_TRANSLATION_AUTO;
2115
    cache = 1;
2116

    
2117
    if (machine && machine->use_scsi) {
2118
        type = IF_SCSI;
2119
        max_devs = MAX_SCSI_DEVS;
2120
        pstrcpy(devname, sizeof(devname), "scsi");
2121
    } else {
2122
        type = IF_IDE;
2123
        max_devs = MAX_IDE_DEVS;
2124
        pstrcpy(devname, sizeof(devname), "ide");
2125
    }
2126
    media = MEDIA_DISK;
2127

    
2128
    /* extract parameters */
2129
    bus_id  = qemu_opt_get_number(opts, "bus", 0);
2130
    unit_id = qemu_opt_get_number(opts, "unit", -1);
2131
    index   = qemu_opt_get_number(opts, "index", -1);
2132

    
2133
    cyls  = qemu_opt_get_number(opts, "cyls", 0);
2134
    heads = qemu_opt_get_number(opts, "heads", 0);
2135
    secs  = qemu_opt_get_number(opts, "secs", 0);
2136

    
2137
    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
2138
    ro = qemu_opt_get_bool(opts, "readonly", 0);
2139

    
2140
    file = qemu_opt_get(opts, "file");
2141
    serial = qemu_opt_get(opts, "serial");
2142

    
2143
    if ((buf = qemu_opt_get(opts, "if")) != NULL) {
2144
        pstrcpy(devname, sizeof(devname), buf);
2145
        if (!strcmp(buf, "ide")) {
2146
            type = IF_IDE;
2147
            max_devs = MAX_IDE_DEVS;
2148
        } else if (!strcmp(buf, "scsi")) {
2149
            type = IF_SCSI;
2150
            max_devs = MAX_SCSI_DEVS;
2151
        } else if (!strcmp(buf, "floppy")) {
2152
            type = IF_FLOPPY;
2153
            max_devs = 0;
2154
        } else if (!strcmp(buf, "pflash")) {
2155
            type = IF_PFLASH;
2156
            max_devs = 0;
2157
        } else if (!strcmp(buf, "mtd")) {
2158
            type = IF_MTD;
2159
            max_devs = 0;
2160
        } else if (!strcmp(buf, "sd")) {
2161
            type = IF_SD;
2162
            max_devs = 0;
2163
        } else if (!strcmp(buf, "virtio")) {
2164
            type = IF_VIRTIO;
2165
            max_devs = 0;
2166
        } else if (!strcmp(buf, "xen")) {
2167
            type = IF_XEN;
2168
            max_devs = 0;
2169
        } else if (!strcmp(buf, "none")) {
2170
            type = IF_NONE;
2171
            max_devs = 0;
2172
        } else {
2173
            fprintf(stderr, "qemu: unsupported bus type '%s'\n", buf);
2174
            return NULL;
2175
        }
2176
    }
2177

    
2178
    if (cyls || heads || secs) {
2179
        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {
2180
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", buf);
2181
            return NULL;
2182
        }
2183
        if (heads < 1 || (type == IF_IDE && heads > 16)) {
2184
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", buf);
2185
            return NULL;
2186
        }
2187
        if (secs < 1 || (type == IF_IDE && secs > 63)) {
2188
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", buf);
2189
            return NULL;
2190
        }
2191
    }
2192

    
2193
    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
2194
        if (!cyls) {
2195
            fprintf(stderr,
2196
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2197
                    buf);
2198
            return NULL;
2199
        }
2200
        if (!strcmp(buf, "none"))
2201
            translation = BIOS_ATA_TRANSLATION_NONE;
2202
        else if (!strcmp(buf, "lba"))
2203
            translation = BIOS_ATA_TRANSLATION_LBA;
2204
        else if (!strcmp(buf, "auto"))
2205
            translation = BIOS_ATA_TRANSLATION_AUTO;
2206
        else {
2207
            fprintf(stderr, "qemu: '%s' invalid translation type\n", buf);
2208
            return NULL;
2209
        }
2210
    }
2211

    
2212
    if ((buf = qemu_opt_get(opts, "media")) != NULL) {
2213
        if (!strcmp(buf, "disk")) {
2214
            media = MEDIA_DISK;
2215
        } else if (!strcmp(buf, "cdrom")) {
2216
            if (cyls || secs || heads) {
2217
                fprintf(stderr,
2218
                        "qemu: '%s' invalid physical CHS format\n", buf);
2219
                return NULL;
2220
            }
2221
            media = MEDIA_CDROM;
2222
        } else {
2223
            fprintf(stderr, "qemu: '%s' invalid media\n", buf);
2224
            return NULL;
2225
        }
2226
    }
2227

    
2228
    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
2229
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2230
            cache = 0;
2231
        else if (!strcmp(buf, "writethrough"))
2232
            cache = 1;
2233
        else if (!strcmp(buf, "writeback"))
2234
            cache = 2;
2235
        else {
2236
           fprintf(stderr, "qemu: invalid cache option\n");
2237
           return NULL;
2238
        }
2239
    }
2240

    
2241
#ifdef CONFIG_LINUX_AIO
2242
    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
2243
        if (!strcmp(buf, "threads"))
2244
            aio = 0;
2245
        else if (!strcmp(buf, "native"))
2246
            aio = 1;
2247
        else {
2248
           fprintf(stderr, "qemu: invalid aio option\n");
2249
           return NULL;
2250
        }
2251
    }
2252
#endif
2253

    
2254
    if ((buf = qemu_opt_get(opts, "format")) != NULL) {
2255
       if (strcmp(buf, "?") == 0) {
2256
            fprintf(stderr, "qemu: Supported formats:");
2257
            bdrv_iterate_format(bdrv_format_print, NULL);
2258
            fprintf(stderr, "\n");
2259
            return NULL;
2260
        }
2261
        drv = bdrv_find_whitelisted_format(buf);
2262
        if (!drv) {
2263
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2264
            return NULL;
2265
        }
2266
    }
2267

    
2268
    on_write_error = BLOCK_ERR_STOP_ENOSPC;
2269
    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
2270
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2271
            fprintf(stderr, "werror is no supported by this format\n");
2272
            return NULL;
2273
        }
2274

    
2275
        on_write_error = parse_block_error_action(buf, 0);
2276
        if (on_write_error < 0) {
2277
            return NULL;
2278
        }
2279
    }
2280

    
2281
    on_read_error = BLOCK_ERR_REPORT;
2282
    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
2283
        if (type != IF_IDE && type != IF_VIRTIO) {
2284
            fprintf(stderr, "rerror is no supported by this format\n");
2285
            return NULL;
2286
        }
2287

    
2288
        on_read_error = parse_block_error_action(buf, 1);
2289
        if (on_read_error < 0) {
2290
            return NULL;
2291
        }
2292
    }
2293

    
2294
    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
2295
        if (type != IF_VIRTIO) {
2296
            fprintf(stderr, "addr is not supported\n");
2297
            return NULL;
2298
        }
2299
    }
2300

    
2301
    /* compute bus and unit according index */
2302

    
2303
    if (index != -1) {
2304
        if (bus_id != 0 || unit_id != -1) {
2305
            fprintf(stderr,
2306
                    "qemu: index cannot be used with bus and unit\n");
2307
            return NULL;
2308
        }
2309
        if (max_devs == 0)
2310
        {
2311
            unit_id = index;
2312
            bus_id = 0;
2313
        } else {
2314
            unit_id = index % max_devs;
2315
            bus_id = index / max_devs;
2316
        }
2317
    }
2318

    
2319
    /* if user doesn't specify a unit_id,
2320
     * try to find the first free
2321
     */
2322

    
2323
    if (unit_id == -1) {
2324
       unit_id = 0;
2325
       while (drive_get(type, bus_id, unit_id) != NULL) {
2326
           unit_id++;
2327
           if (max_devs && unit_id >= max_devs) {
2328
               unit_id -= max_devs;
2329
               bus_id++;
2330
           }
2331
       }
2332
    }
2333

    
2334
    /* check unit id */
2335

    
2336
    if (max_devs && unit_id >= max_devs) {
2337
        fprintf(stderr, "qemu: unit %d too big (max is %d)\n",
2338
                unit_id, max_devs - 1);
2339
        return NULL;
2340
    }
2341

    
2342
    /*
2343
     * ignore multiple definitions
2344
     */
2345

    
2346
    if (drive_get(type, bus_id, unit_id) != NULL) {
2347
        *fatal_error = 0;
2348
        return NULL;
2349
    }
2350

    
2351
    /* init */
2352

    
2353
    dinfo = qemu_mallocz(sizeof(*dinfo));
2354
    if ((buf = qemu_opts_id(opts)) != NULL) {
2355
        dinfo->id = qemu_strdup(buf);
2356
    } else {
2357
        /* no id supplied -> create one */
2358
        dinfo->id = qemu_mallocz(32);
2359
        if (type == IF_IDE || type == IF_SCSI)
2360
            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2361
        if (max_devs)
2362
            snprintf(dinfo->id, 32, "%s%i%s%i",
2363
                     devname, bus_id, mediastr, unit_id);
2364
        else
2365
            snprintf(dinfo->id, 32, "%s%s%i",
2366
                     devname, mediastr, unit_id);
2367
    }
2368
    dinfo->bdrv = bdrv_new(dinfo->id);
2369
    dinfo->devaddr = devaddr;
2370
    dinfo->type = type;
2371
    dinfo->bus = bus_id;
2372
    dinfo->unit = unit_id;
2373
    dinfo->on_read_error = on_read_error;
2374
    dinfo->on_write_error = on_write_error;
2375
    dinfo->opts = opts;
2376
    if (serial)
2377
        strncpy(dinfo->serial, serial, sizeof(serial));
2378
    QTAILQ_INSERT_TAIL(&drives, dinfo, next);
2379

    
2380
    switch(type) {
2381
    case IF_IDE:
2382
    case IF_SCSI:
2383
    case IF_XEN:
2384
    case IF_NONE:
2385
        switch(media) {
2386
        case MEDIA_DISK:
2387
            if (cyls != 0) {
2388
                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);
2389
                bdrv_set_translation_hint(dinfo->bdrv, translation);
2390
            }
2391
            break;
2392
        case MEDIA_CDROM:
2393
            bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_CDROM);
2394
            break;
2395
        }
2396
        break;
2397
    case IF_SD:
2398
        /* FIXME: This isn't really a floppy, but it's a reasonable
2399
           approximation.  */
2400
    case IF_FLOPPY:
2401
        bdrv_set_type_hint(dinfo->bdrv, BDRV_TYPE_FLOPPY);
2402
        break;
2403
    case IF_PFLASH:
2404
    case IF_MTD:
2405
        break;
2406
    case IF_VIRTIO:
2407
        /* add virtio block device */
2408
        opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
2409
        qemu_opt_set(opts, "driver", "virtio-blk-pci");
2410
        qemu_opt_set(opts, "drive", dinfo->id);
2411
        if (devaddr)
2412
            qemu_opt_set(opts, "addr", devaddr);
2413
        break;
2414
    case IF_COUNT:
2415
        abort();
2416
    }
2417
    if (!file) {
2418
        *fatal_error = 0;
2419
        return NULL;
2420
    }
2421
    bdrv_flags = 0;
2422
    if (snapshot) {
2423
        bdrv_flags |= BDRV_O_SNAPSHOT;
2424
        cache = 2; /* always use write-back with snapshot */
2425
    }
2426
    if (cache == 0) /* no caching */
2427
        bdrv_flags |= BDRV_O_NOCACHE;
2428
    else if (cache == 2) /* write-back */
2429
        bdrv_flags |= BDRV_O_CACHE_WB;
2430

    
2431
    if (aio == 1) {
2432
        bdrv_flags |= BDRV_O_NATIVE_AIO;
2433
    } else {
2434
        bdrv_flags &= ~BDRV_O_NATIVE_AIO;
2435
    }
2436

    
2437
    if (ro == 1) {
2438
        if (type == IF_IDE) {
2439
            fprintf(stderr, "qemu: readonly flag not supported for drive with ide interface\n");
2440
            return NULL;
2441
        }
2442
        (void)bdrv_set_read_only(dinfo->bdrv, 1);
2443
    }
2444

    
2445
    if (bdrv_open2(dinfo->bdrv, file, bdrv_flags, drv) < 0) {
2446
        fprintf(stderr, "qemu: could not open disk image %s: %s\n",
2447
                        file, strerror(errno));
2448
        return NULL;
2449
    }
2450

    
2451
    if (bdrv_key_required(dinfo->bdrv))
2452
        autostart = 0;
2453
    *fatal_error = 0;
2454
    return dinfo;
2455
}
2456

    
2457
static int drive_init_func(QemuOpts *opts, void *opaque)
2458
{
2459
    QEMUMachine *machine = opaque;
2460
    int fatal_error = 0;
2461

    
2462
    if (drive_init(opts, machine, &fatal_error) == NULL) {
2463
        if (fatal_error)
2464
            return 1;
2465
    }
2466
    return 0;
2467
}
2468

    
2469
static int drive_enable_snapshot(QemuOpts *opts, void *opaque)
2470
{
2471
    if (NULL == qemu_opt_get(opts, "snapshot")) {
2472
        qemu_opt_set(opts, "snapshot", "on");
2473
    }
2474
    return 0;
2475
}
2476

    
2477
void qemu_register_boot_set(QEMUBootSetHandler *func, void *opaque)
2478
{
2479
    boot_set_handler = func;
2480
    boot_set_opaque = opaque;
2481
}
2482

    
2483
int qemu_boot_set(const char *boot_devices)
2484
{
2485
    if (!boot_set_handler) {
2486
        return -EINVAL;
2487
    }
2488
    return boot_set_handler(boot_set_opaque, boot_devices);
2489
}
2490

    
2491
static int parse_bootdevices(char *devices)
2492
{
2493
    /* We just do some generic consistency checks */
2494
    const char *p;
2495
    int bitmap = 0;
2496

    
2497
    for (p = devices; *p != '\0'; p++) {
2498
        /* Allowed boot devices are:
2499
         * a-b: floppy disk drives
2500
         * c-f: IDE disk drives
2501
         * g-m: machine implementation dependant drives
2502
         * n-p: network devices
2503
         * It's up to each machine implementation to check if the given boot
2504
         * devices match the actual hardware implementation and firmware
2505
         * features.
2506
         */
2507
        if (*p < 'a' || *p > 'p') {
2508
            fprintf(stderr, "Invalid boot device '%c'\n", *p);
2509
            exit(1);
2510
        }
2511
        if (bitmap & (1 << (*p - 'a'))) {
2512
            fprintf(stderr, "Boot device '%c' was given twice\n", *p);
2513
            exit(1);
2514
        }
2515
        bitmap |= 1 << (*p - 'a');
2516
    }
2517
    return bitmap;
2518
}
2519

    
2520
static void restore_boot_devices(void *opaque)
2521
{
2522
    char *standard_boot_devices = opaque;
2523

    
2524
    qemu_boot_set(standard_boot_devices);
2525

    
2526
    qemu_unregister_reset(restore_boot_devices, standard_boot_devices);
2527
    qemu_free(standard_boot_devices);
2528
}
2529

    
2530
static void numa_add(const char *optarg)
2531
{
2532
    char option[128];
2533
    char *endptr;
2534
    unsigned long long value, endvalue;
2535
    int nodenr;
2536

    
2537
    optarg = get_opt_name(option, 128, optarg, ',') + 1;
2538
    if (!strcmp(option, "node")) {
2539
        if (get_param_value(option, 128, "nodeid", optarg) == 0) {
2540
            nodenr = nb_numa_nodes;
2541
        } else {
2542
            nodenr = strtoull(option, NULL, 10);
2543
        }
2544

    
2545
        if (get_param_value(option, 128, "mem", optarg) == 0) {
2546
            node_mem[nodenr] = 0;
2547
        } else {
2548
            value = strtoull(option, &endptr, 0);
2549
            switch (*endptr) {
2550
            case 0: case 'M': case 'm':
2551
                value <<= 20;
2552
                break;
2553
            case 'G': case 'g':
2554
                value <<= 30;
2555
                break;
2556
            }
2557
            node_mem[nodenr] = value;
2558
        }
2559
        if (get_param_value(option, 128, "cpus", optarg) == 0) {
2560
            node_cpumask[nodenr] = 0;
2561
        } else {
2562
            value = strtoull(option, &endptr, 10);
2563
            if (value >= 64) {
2564
                value = 63;
2565
                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");
2566
            } else {
2567
                if (*endptr == '-') {
2568
                    endvalue = strtoull(endptr+1, &endptr, 10);
2569
                    if (endvalue >= 63) {
2570
                        endvalue = 62;
2571
                        fprintf(stderr,
2572
                            "only 63 CPUs in NUMA mode supported.\n");
2573
                    }
2574
                    value = (1 << (endvalue + 1)) - (1 << value);
2575
                } else {
2576
                    value = 1 << value;
2577
                }
2578
            }
2579
            node_cpumask[nodenr] = value;
2580
        }
2581
        nb_numa_nodes++;
2582
    }
2583
    return;
2584
}
2585

    
2586
static void smp_parse(const char *optarg)
2587
{
2588
    int smp, sockets = 0, threads = 0, cores = 0;
2589
    char *endptr;
2590
    char option[128];
2591

    
2592
    smp = strtoul(optarg, &endptr, 10);
2593
    if (endptr != optarg) {
2594
        if (*endptr == ',') {
2595
            endptr++;
2596
        }
2597
    }
2598
    if (get_param_value(option, 128, "sockets", endptr) != 0)
2599
        sockets = strtoull(option, NULL, 10);
2600
    if (get_param_value(option, 128, "cores", endptr) != 0)
2601
        cores = strtoull(option, NULL, 10);
2602
    if (get_param_value(option, 128, "threads", endptr) != 0)
2603
        threads = strtoull(option, NULL, 10);
2604
    if (get_param_value(option, 128, "maxcpus", endptr) != 0)
2605
        max_cpus = strtoull(option, NULL, 10);
2606

    
2607
    /* compute missing values, prefer sockets over cores over threads */
2608
    if (smp == 0 || sockets == 0) {
2609
        sockets = sockets > 0 ? sockets : 1;
2610
        cores = cores > 0 ? cores : 1;
2611
        threads = threads > 0 ? threads : 1;
2612
        if (smp == 0) {
2613
            smp = cores * threads * sockets;
2614
        } else {
2615
            sockets = smp / (cores * threads);
2616
        }
2617
    } else {
2618
        if (cores == 0) {
2619
            threads = threads > 0 ? threads : 1;
2620
            cores = smp / (sockets * threads);
2621
        } else {
2622
            if (sockets == 0) {
2623
                sockets = smp / (cores * threads);
2624
            } else {
2625
                threads = smp / (cores * sockets);
2626
            }
2627
        }
2628
    }
2629
    smp_cpus = smp;
2630
    smp_cores = cores > 0 ? cores : 1;
2631
    smp_threads = threads > 0 ? threads : 1;
2632
    if (max_cpus == 0)
2633
        max_cpus = smp_cpus;
2634
}
2635

    
2636
/***********************************************************/
2637
/* USB devices */
2638

    
2639
static int usb_device_add(const char *devname, int is_hotplug)
2640
{
2641
    const char *p;
2642
    USBDevice *dev = NULL;
2643

    
2644
    if (!usb_enabled)
2645
        return -1;
2646

    
2647
    /* drivers with .usbdevice_name entry in USBDeviceInfo */
2648
    dev = usbdevice_create(devname);
2649
    if (dev)
2650
        goto done;
2651

    
2652
    /* the other ones */
2653
    if (strstart(devname, "host:", &p)) {
2654
        dev = usb_host_device_open(p);
2655
    } else if (strstart(devname, "net:", &p)) {
2656
        QemuOpts *opts;
2657
        int idx;
2658

    
2659
        opts = qemu_opts_parse(&qemu_net_opts, p, NULL);
2660
        if (!opts) {
2661
            return -1;
2662
        }
2663

    
2664
        qemu_opt_set(opts, "type", "nic");
2665
        qemu_opt_set(opts, "model", "usb");
2666

    
2667
        idx = net_client_init(NULL, opts, 0);
2668
        if (idx == -1) {
2669
            return -1;
2670
        }
2671

    
2672
        dev = usb_net_init(&nd_table[idx]);
2673
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2674
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2675
                        bt_new_hci(qemu_find_bt_vlan(0)));
2676
    } else {
2677
        return -1;
2678
    }
2679
    if (!dev)
2680
        return -1;
2681

    
2682
done:
2683
    return 0;
2684
}
2685

    
2686
static int usb_device_del(const char *devname)
2687
{
2688
    int bus_num, addr;
2689
    const char *p;
2690

    
2691
    if (strstart(devname, "host:", &p))
2692
        return usb_host_device_close(p);
2693

    
2694
    if (!usb_enabled)
2695
        return -1;
2696

    
2697
    p = strchr(devname, '.');
2698
    if (!p)
2699
        return -1;
2700
    bus_num = strtoul(devname, NULL, 0);
2701
    addr = strtoul(p + 1, NULL, 0);
2702

    
2703
    return usb_device_delete_addr(bus_num, addr);
2704
}
2705

    
2706
static int usb_parse(const char *cmdline)
2707
{
2708
    return usb_device_add(cmdline, 0);
2709
}
2710

    
2711
void do_usb_add(Monitor *mon, const QDict *qdict)
2712
{
2713
    usb_device_add(qdict_get_str(qdict, "devname"), 1);
2714
}
2715

    
2716
void do_usb_del(Monitor *mon, const QDict *qdict)
2717
{
2718
    usb_device_del(qdict_get_str(qdict, "devname"));
2719
}
2720

    
2721
/***********************************************************/
2722
/* PCMCIA/Cardbus */
2723

    
2724
static struct pcmcia_socket_entry_s {
2725
    PCMCIASocket *socket;
2726
    struct pcmcia_socket_entry_s *next;
2727
} *pcmcia_sockets = 0;
2728

    
2729
void pcmcia_socket_register(PCMCIASocket *socket)
2730
{
2731
    struct pcmcia_socket_entry_s *entry;
2732

    
2733
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2734
    entry->socket = socket;
2735
    entry->next = pcmcia_sockets;
2736
    pcmcia_sockets = entry;
2737
}
2738

    
2739
void pcmcia_socket_unregister(PCMCIASocket *socket)
2740
{
2741
    struct pcmcia_socket_entry_s *entry, **ptr;
2742

    
2743
    ptr = &pcmcia_sockets;
2744
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2745
        if (entry->socket == socket) {
2746
            *ptr = entry->next;
2747
            qemu_free(entry);
2748
        }
2749
}
2750

    
2751
void pcmcia_info(Monitor *mon)
2752
{
2753
    struct pcmcia_socket_entry_s *iter;
2754

    
2755
    if (!pcmcia_sockets)
2756
        monitor_printf(mon, "No PCMCIA sockets\n");
2757

    
2758
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2759
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2760
                       iter->socket->attached ? iter->socket->card_string :
2761
                       "Empty");
2762
}
2763

    
2764
/***********************************************************/
2765
/* register display */
2766

    
2767
struct DisplayAllocator default_allocator = {
2768
    defaultallocator_create_displaysurface,
2769
    defaultallocator_resize_displaysurface,
2770
    defaultallocator_free_displaysurface
2771
};
2772

    
2773
void register_displaystate(DisplayState *ds)
2774
{
2775
    DisplayState **s;
2776
    s = &display_state;
2777
    while (*s != NULL)
2778
        s = &(*s)->next;
2779
    ds->next = NULL;
2780
    *s = ds;
2781
}
2782

    
2783
DisplayState *get_displaystate(void)
2784
{
2785
    return display_state;
2786
}
2787

    
2788
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2789
{
2790
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2791
    return ds->allocator;
2792
}
2793

    
2794
/* dumb display */
2795

    
2796
static void dumb_display_init(void)
2797
{
2798
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2799
    ds->allocator = &default_allocator;
2800
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2801
    register_displaystate(ds);
2802
}
2803

    
2804
/***********************************************************/
2805
/* I/O handling */
2806

    
2807
typedef struct IOHandlerRecord {
2808
    int fd;
2809
    IOCanRWHandler *fd_read_poll;
2810
    IOHandler *fd_read;
2811
    IOHandler *fd_write;
2812
    int deleted;
2813
    void *opaque;
2814
    /* temporary data */
2815
    struct pollfd *ufd;
2816
    struct IOHandlerRecord *next;
2817
} IOHandlerRecord;
2818

    
2819
static IOHandlerRecord *first_io_handler;
2820

    
2821
/* XXX: fd_read_poll should be suppressed, but an API change is
2822
   necessary in the character devices to suppress fd_can_read(). */
2823
int qemu_set_fd_handler2(int fd,
2824
                         IOCanRWHandler *fd_read_poll,
2825
                         IOHandler *fd_read,
2826
                         IOHandler *fd_write,
2827
                         void *opaque)
2828
{
2829
    IOHandlerRecord **pioh, *ioh;
2830

    
2831
    if (!fd_read && !fd_write) {
2832
        pioh = &first_io_handler;
2833
        for(;;) {
2834
            ioh = *pioh;
2835
            if (ioh == NULL)
2836
                break;
2837
            if (ioh->fd == fd) {
2838
                ioh->deleted = 1;
2839
                break;
2840
            }
2841
            pioh = &ioh->next;
2842
        }
2843
    } else {
2844
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2845
            if (ioh->fd == fd)
2846
                goto found;
2847
        }
2848
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2849
        ioh->next = first_io_handler;
2850
        first_io_handler = ioh;
2851
    found:
2852
        ioh->fd = fd;
2853
        ioh->fd_read_poll = fd_read_poll;
2854
        ioh->fd_read = fd_read;
2855
        ioh->fd_write = fd_write;
2856
        ioh->opaque = opaque;
2857
        ioh->deleted = 0;
2858
    }
2859
    return 0;
2860
}
2861

    
2862
int qemu_set_fd_handler(int fd,
2863
                        IOHandler *fd_read,
2864
                        IOHandler *fd_write,
2865
                        void *opaque)
2866
{
2867
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2868
}
2869

    
2870
#ifdef _WIN32
2871
/***********************************************************/
2872
/* Polling handling */
2873

    
2874
typedef struct PollingEntry {
2875
    PollingFunc *func;
2876
    void *opaque;
2877
    struct PollingEntry *next;
2878
} PollingEntry;
2879

    
2880
static PollingEntry *first_polling_entry;
2881

    
2882
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2883
{
2884
    PollingEntry **ppe, *pe;
2885
    pe = qemu_mallocz(sizeof(PollingEntry));
2886
    pe->func = func;
2887
    pe->opaque = opaque;
2888
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2889
    *ppe = pe;
2890
    return 0;
2891
}
2892

    
2893
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2894
{
2895
    PollingEntry **ppe, *pe;
2896
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2897
        pe = *ppe;
2898
        if (pe->func == func && pe->opaque == opaque) {
2899
            *ppe = pe->next;
2900
            qemu_free(pe);
2901
            break;
2902
        }
2903
    }
2904
}
2905

    
2906
/***********************************************************/
2907
/* Wait objects support */
2908
typedef struct WaitObjects {
2909
    int num;
2910
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2911
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2912
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2913
} WaitObjects;
2914

    
2915
static WaitObjects wait_objects = {0};
2916

    
2917
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2918
{
2919
    WaitObjects *w = &wait_objects;
2920

    
2921
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2922
        return -1;
2923
    w->events[w->num] = handle;
2924
    w->func[w->num] = func;
2925
    w->opaque[w->num] = opaque;
2926
    w->num++;
2927
    return 0;
2928
}
2929

    
2930
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2931
{
2932
    int i, found;
2933
    WaitObjects *w = &wait_objects;
2934

    
2935
    found = 0;
2936
    for (i = 0; i < w->num; i++) {
2937
        if (w->events[i] == handle)
2938
            found = 1;
2939
        if (found) {
2940
            w->events[i] = w->events[i + 1];
2941
            w->func[i] = w->func[i + 1];
2942
            w->opaque[i] = w->opaque[i + 1];
2943
        }
2944
    }
2945
    if (found)
2946
        w->num--;
2947
}
2948
#endif
2949

    
2950
/***********************************************************/
2951
/* ram save/restore */
2952

    
2953
#define RAM_SAVE_FLAG_FULL        0x01 /* Obsolete, not used anymore */
2954
#define RAM_SAVE_FLAG_COMPRESS        0x02
2955
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
2956
#define RAM_SAVE_FLAG_PAGE        0x08
2957
#define RAM_SAVE_FLAG_EOS        0x10
2958

    
2959
static int is_dup_page(uint8_t *page, uint8_t ch)
2960
{
2961
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
2962
    uint32_t *array = (uint32_t *)page;
2963
    int i;
2964

    
2965
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
2966
        if (array[i] != val)
2967
            return 0;
2968
    }
2969

    
2970
    return 1;
2971
}
2972

    
2973
static int ram_save_block(QEMUFile *f)
2974
{
2975
    static ram_addr_t current_addr = 0;
2976
    ram_addr_t saved_addr = current_addr;
2977
    ram_addr_t addr = 0;
2978
    int found = 0;
2979

    
2980
    while (addr < last_ram_offset) {
2981
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
2982
            uint8_t *p;
2983

    
2984
            cpu_physical_memory_reset_dirty(current_addr,
2985
                                            current_addr + TARGET_PAGE_SIZE,
2986
                                            MIGRATION_DIRTY_FLAG);
2987

    
2988
            p = qemu_get_ram_ptr(current_addr);
2989

    
2990
            if (is_dup_page(p, *p)) {
2991
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
2992
                qemu_put_byte(f, *p);
2993
            } else {
2994
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
2995
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
2996
            }
2997

    
2998
            found = 1;
2999
            break;
3000
        }
3001
        addr += TARGET_PAGE_SIZE;
3002
        current_addr = (saved_addr + addr) % last_ram_offset;
3003
    }
3004

    
3005
    return found;
3006
}
3007

    
3008
static uint64_t bytes_transferred;
3009

    
3010
static ram_addr_t ram_save_remaining(void)
3011
{
3012
    ram_addr_t addr;
3013
    ram_addr_t count = 0;
3014

    
3015
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3016
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3017
            count++;
3018
    }
3019

    
3020
    return count;
3021
}
3022

    
3023
uint64_t ram_bytes_remaining(void)
3024
{
3025
    return ram_save_remaining() * TARGET_PAGE_SIZE;
3026
}
3027

    
3028
uint64_t ram_bytes_transferred(void)
3029
{
3030
    return bytes_transferred;
3031
}
3032

    
3033
uint64_t ram_bytes_total(void)
3034
{
3035
    return last_ram_offset;
3036
}
3037

    
3038
static int ram_save_live(Monitor *mon, QEMUFile *f, int stage, void *opaque)
3039
{
3040
    ram_addr_t addr;
3041
    uint64_t bytes_transferred_last;
3042
    double bwidth = 0;
3043
    uint64_t expected_time = 0;
3044

    
3045
    if (stage < 0) {
3046
        cpu_physical_memory_set_dirty_tracking(0);
3047
        return 0;
3048
    }
3049

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

    
3055
    if (stage == 1) {
3056
        bytes_transferred = 0;
3057

    
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
    if (stage == 3) {
3092
        /* flush all remaining blocks regardless of rate limiting */
3093
        while (ram_save_block(f) != 0) {
3094
            bytes_transferred += TARGET_PAGE_SIZE;
3095
        }
3096
        cpu_physical_memory_set_dirty_tracking(0);
3097
    }
3098

    
3099
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3100

    
3101
    expected_time = ram_save_remaining() * TARGET_PAGE_SIZE / bwidth;
3102

    
3103
    return (stage == 2) && (expected_time <= migrate_max_downtime());
3104
}
3105

    
3106
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3107
{
3108
    ram_addr_t addr;
3109
    int flags;
3110

    
3111
    if (version_id != 3)
3112
        return -EINVAL;
3113

    
3114
    do {
3115
        addr = qemu_get_be64(f);
3116

    
3117
        flags = addr & ~TARGET_PAGE_MASK;
3118
        addr &= TARGET_PAGE_MASK;
3119

    
3120
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3121
            if (addr != last_ram_offset)
3122
                return -EINVAL;
3123
        }
3124

    
3125
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3126
            uint8_t ch = qemu_get_byte(f);
3127
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3128
#ifndef _WIN32
3129
            if (ch == 0 &&
3130
                (!kvm_enabled() || kvm_has_sync_mmu())) {
3131
                madvise(qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE, MADV_DONTNEED);
3132
            }
3133
#endif
3134
        } else if (flags & RAM_SAVE_FLAG_PAGE) {
3135
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3136
        }
3137
        if (qemu_file_has_error(f)) {
3138
            return -EIO;
3139
        }
3140
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3141

    
3142
    return 0;
3143
}
3144

    
3145
void qemu_service_io(void)
3146
{
3147
    qemu_notify_event();
3148
}
3149

    
3150
/***********************************************************/
3151
/* machine registration */
3152

    
3153
static QEMUMachine *first_machine = NULL;
3154
QEMUMachine *current_machine = NULL;
3155

    
3156
int qemu_register_machine(QEMUMachine *m)
3157
{
3158
    QEMUMachine **pm;
3159
    pm = &first_machine;
3160
    while (*pm != NULL)
3161
        pm = &(*pm)->next;
3162
    m->next = NULL;
3163
    *pm = m;
3164
    return 0;
3165
}
3166

    
3167
static QEMUMachine *find_machine(const char *name)
3168
{
3169
    QEMUMachine *m;
3170

    
3171
    for(m = first_machine; m != NULL; m = m->next) {
3172
        if (!strcmp(m->name, name))
3173
            return m;
3174
        if (m->alias && !strcmp(m->alias, name))
3175
            return m;
3176
    }
3177
    return NULL;
3178
}
3179

    
3180
static QEMUMachine *find_default_machine(void)
3181
{
3182
    QEMUMachine *m;
3183

    
3184
    for(m = first_machine; m != NULL; m = m->next) {
3185
        if (m->is_default) {
3186
            return m;
3187
        }
3188
    }
3189
    return NULL;
3190
}
3191

    
3192
/***********************************************************/
3193
/* main execution loop */
3194

    
3195
static void gui_update(void *opaque)
3196
{
3197
    uint64_t interval = GUI_REFRESH_INTERVAL;
3198
    DisplayState *ds = opaque;
3199
    DisplayChangeListener *dcl = ds->listeners;
3200

    
3201
    dpy_refresh(ds);
3202

    
3203
    while (dcl != NULL) {
3204
        if (dcl->gui_timer_interval &&
3205
            dcl->gui_timer_interval < interval)
3206
            interval = dcl->gui_timer_interval;
3207
        dcl = dcl->next;
3208
    }
3209
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3210
}
3211

    
3212
static void nographic_update(void *opaque)
3213
{
3214
    uint64_t interval = GUI_REFRESH_INTERVAL;
3215

    
3216
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3217
}
3218

    
3219
struct vm_change_state_entry {
3220
    VMChangeStateHandler *cb;
3221
    void *opaque;
3222
    QLIST_ENTRY (vm_change_state_entry) entries;
3223
};
3224

    
3225
static QLIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3226

    
3227
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3228
                                                     void *opaque)
3229
{
3230
    VMChangeStateEntry *e;
3231

    
3232
    e = qemu_mallocz(sizeof (*e));
3233

    
3234
    e->cb = cb;
3235
    e->opaque = opaque;
3236
    QLIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3237
    return e;
3238
}
3239

    
3240
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3241
{
3242
    QLIST_REMOVE (e, entries);
3243
    qemu_free (e);
3244
}
3245

    
3246
static void vm_state_notify(int running, int reason)
3247
{
3248
    VMChangeStateEntry *e;
3249

    
3250
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3251
        e->cb(e->opaque, running, reason);
3252
    }
3253
}
3254

    
3255
static void resume_all_vcpus(void);
3256
static void pause_all_vcpus(void);
3257

    
3258
void vm_start(void)
3259
{
3260
    if (!vm_running) {
3261
        cpu_enable_ticks();
3262
        vm_running = 1;
3263
        vm_state_notify(1, 0);
3264
        qemu_rearm_alarm_timer(alarm_timer);
3265
        resume_all_vcpus();
3266
    }
3267
}
3268

    
3269
/* reset/shutdown handler */
3270

    
3271
typedef struct QEMUResetEntry {
3272
    QTAILQ_ENTRY(QEMUResetEntry) entry;
3273
    QEMUResetHandler *func;
3274
    void *opaque;
3275
} QEMUResetEntry;
3276

    
3277
static QTAILQ_HEAD(reset_handlers, QEMUResetEntry) reset_handlers =
3278
    QTAILQ_HEAD_INITIALIZER(reset_handlers);
3279
static int reset_requested;
3280
static int shutdown_requested;
3281
static int powerdown_requested;
3282
static int debug_requested;
3283
static int vmstop_requested;
3284

    
3285
int qemu_shutdown_requested(void)
3286
{
3287
    int r = shutdown_requested;
3288
    shutdown_requested = 0;
3289
    return r;
3290
}
3291

    
3292
int qemu_reset_requested(void)
3293
{
3294
    int r = reset_requested;
3295
    reset_requested = 0;
3296
    return r;
3297
}
3298

    
3299
int qemu_powerdown_requested(void)
3300
{
3301
    int r = powerdown_requested;
3302
    powerdown_requested = 0;
3303
    return r;
3304
}
3305

    
3306
static int qemu_debug_requested(void)
3307
{
3308
    int r = debug_requested;
3309
    debug_requested = 0;
3310
    return r;
3311
}
3312

    
3313
static int qemu_vmstop_requested(void)
3314
{
3315
    int r = vmstop_requested;
3316
    vmstop_requested = 0;
3317
    return r;
3318
}
3319

    
3320
static void do_vm_stop(int reason)
3321
{
3322
    if (vm_running) {
3323
        cpu_disable_ticks();
3324
        vm_running = 0;
3325
        pause_all_vcpus();
3326
        vm_state_notify(0, reason);
3327
    }
3328
}
3329

    
3330
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3331
{
3332
    QEMUResetEntry *re = qemu_mallocz(sizeof(QEMUResetEntry));
3333

    
3334
    re->func = func;
3335
    re->opaque = opaque;
3336
    QTAILQ_INSERT_TAIL(&reset_handlers, re, entry);
3337
}
3338

    
3339
void qemu_unregister_reset(QEMUResetHandler *func, void *opaque)
3340
{
3341
    QEMUResetEntry *re;
3342

    
3343
    QTAILQ_FOREACH(re, &reset_handlers, entry) {
3344
        if (re->func == func && re->opaque == opaque) {
3345
            QTAILQ_REMOVE(&reset_handlers, re, entry);
3346
            qemu_free(re);
3347
            return;
3348
        }
3349
    }
3350
}
3351

    
3352
void qemu_system_reset(void)
3353
{
3354
    QEMUResetEntry *re, *nre;
3355

    
3356
    /* reset all devices */
3357
    QTAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {
3358
        re->func(re->opaque);
3359
    }
3360
}
3361

    
3362
void qemu_system_reset_request(void)
3363
{
3364
    if (no_reboot) {
3365
        shutdown_requested = 1;
3366
    } else {
3367
        reset_requested = 1;
3368
    }
3369
    qemu_notify_event();
3370
}
3371

    
3372
void qemu_system_shutdown_request(void)
3373
{
3374
    shutdown_requested = 1;
3375
    qemu_notify_event();
3376
}
3377

    
3378
void qemu_system_powerdown_request(void)
3379
{
3380
    powerdown_requested = 1;
3381
    qemu_notify_event();
3382
}
3383

    
3384
#ifdef CONFIG_IOTHREAD
3385
static void qemu_system_vmstop_request(int reason)
3386
{
3387
    vmstop_requested = reason;
3388
    qemu_notify_event();
3389
}
3390
#endif
3391

    
3392
#ifndef _WIN32
3393
static int io_thread_fd = -1;
3394

    
3395
static void qemu_event_increment(void)
3396
{
3397
    static const char byte = 0;
3398

    
3399
    if (io_thread_fd == -1)
3400
        return;
3401

    
3402
    write(io_thread_fd, &byte, sizeof(byte));
3403
}
3404

    
3405
static void qemu_event_read(void *opaque)
3406
{
3407
    int fd = (unsigned long)opaque;
3408
    ssize_t len;
3409

    
3410
    /* Drain the notify pipe */
3411
    do {
3412
        char buffer[512];
3413
        len = read(fd, buffer, sizeof(buffer));
3414
    } while ((len == -1 && errno == EINTR) || len > 0);
3415
}
3416

    
3417
static int qemu_event_init(void)
3418
{
3419
    int err;
3420
    int fds[2];
3421

    
3422
    err = qemu_pipe(fds);
3423
    if (err == -1)
3424
        return -errno;
3425

    
3426
    err = fcntl_setfl(fds[0], O_NONBLOCK);
3427
    if (err < 0)
3428
        goto fail;
3429

    
3430
    err = fcntl_setfl(fds[1], O_NONBLOCK);
3431
    if (err < 0)
3432
        goto fail;
3433

    
3434
    qemu_set_fd_handler2(fds[0], NULL, qemu_event_read, NULL,
3435
                         (void *)(unsigned long)fds[0]);
3436

    
3437
    io_thread_fd = fds[1];
3438
    return 0;
3439

    
3440
fail:
3441
    close(fds[0]);
3442
    close(fds[1]);
3443
    return err;
3444
}
3445
#else
3446
HANDLE qemu_event_handle;
3447

    
3448
static void dummy_event_handler(void *opaque)
3449
{
3450
}
3451

    
3452
static int qemu_event_init(void)
3453
{
3454
    qemu_event_handle = CreateEvent(NULL, FALSE, FALSE, NULL);
3455
    if (!qemu_event_handle) {
3456
        fprintf(stderr, "Failed CreateEvent: %ld\n", GetLastError());
3457
        return -1;
3458
    }
3459
    qemu_add_wait_object(qemu_event_handle, dummy_event_handler, NULL);
3460
    return 0;
3461
}
3462

    
3463
static void qemu_event_increment(void)
3464
{
3465
    if (!SetEvent(qemu_event_handle)) {
3466
        fprintf(stderr, "qemu_event_increment: SetEvent failed: %ld\n",
3467
                GetLastError());
3468
        exit (1);
3469
    }
3470
}
3471
#endif
3472

    
3473
static int cpu_can_run(CPUState *env)
3474
{
3475
    if (env->stop)
3476
        return 0;
3477
    if (env->stopped)
3478
        return 0;
3479
    return 1;
3480
}
3481

    
3482
#ifndef CONFIG_IOTHREAD
3483
static int qemu_init_main_loop(void)
3484
{
3485
    return qemu_event_init();
3486
}
3487

    
3488
void qemu_init_vcpu(void *_env)
3489
{
3490
    CPUState *env = _env;
3491

    
3492
    if (kvm_enabled())
3493
        kvm_init_vcpu(env);
3494
    env->nr_cores = smp_cores;
3495
    env->nr_threads = smp_threads;
3496
    return;
3497
}
3498

    
3499
int qemu_cpu_self(void *env)
3500
{
3501
    return 1;
3502
}
3503

    
3504
static void resume_all_vcpus(void)
3505
{
3506
}
3507

    
3508
static void pause_all_vcpus(void)
3509
{
3510
}
3511

    
3512
void qemu_cpu_kick(void *env)
3513
{
3514
    return;
3515
}
3516

    
3517
void qemu_notify_event(void)
3518
{
3519
    CPUState *env = cpu_single_env;
3520

    
3521
    if (env) {
3522
        cpu_exit(env);
3523
    }
3524
}
3525

    
3526
void qemu_mutex_lock_iothread(void) {}
3527
void qemu_mutex_unlock_iothread(void) {}
3528

    
3529
void vm_stop(int reason)
3530
{
3531
    do_vm_stop(reason);
3532
}
3533

    
3534
#else /* CONFIG_IOTHREAD */
3535

    
3536
#include "qemu-thread.h"
3537

    
3538
QemuMutex qemu_global_mutex;
3539
static QemuMutex qemu_fair_mutex;
3540

    
3541
static QemuThread io_thread;
3542

    
3543
static QemuThread *tcg_cpu_thread;
3544
static QemuCond *tcg_halt_cond;
3545

    
3546
static int qemu_system_ready;
3547
/* cpu creation */
3548
static QemuCond qemu_cpu_cond;
3549
/* system init */
3550
static QemuCond qemu_system_cond;
3551
static QemuCond qemu_pause_cond;
3552

    
3553
static void block_io_signals(void);
3554
static void unblock_io_signals(void);
3555
static int tcg_has_work(void);
3556

    
3557
static int qemu_init_main_loop(void)
3558
{
3559
    int ret;
3560

    
3561
    ret = qemu_event_init();
3562
    if (ret)
3563
        return ret;
3564

    
3565
    qemu_cond_init(&qemu_pause_cond);
3566
    qemu_mutex_init(&qemu_fair_mutex);
3567
    qemu_mutex_init(&qemu_global_mutex);
3568
    qemu_mutex_lock(&qemu_global_mutex);
3569

    
3570
    unblock_io_signals();
3571
    qemu_thread_self(&io_thread);
3572

    
3573
    return 0;
3574
}
3575

    
3576
static void qemu_wait_io_event(CPUState *env)
3577
{
3578
    while (!tcg_has_work())
3579
        qemu_cond_timedwait(env->halt_cond, &qemu_global_mutex, 1000);
3580

    
3581
    qemu_mutex_unlock(&qemu_global_mutex);
3582

    
3583
    /*
3584
     * Users of qemu_global_mutex can be starved, having no chance
3585
     * to acquire it since this path will get to it first.
3586
     * So use another lock to provide fairness.
3587
     */
3588
    qemu_mutex_lock(&qemu_fair_mutex);
3589
    qemu_mutex_unlock(&qemu_fair_mutex);
3590

    
3591
    qemu_mutex_lock(&qemu_global_mutex);
3592
    if (env->stop) {
3593
        env->stop = 0;
3594
        env->stopped = 1;
3595
        qemu_cond_signal(&qemu_pause_cond);
3596
    }
3597
}
3598

    
3599
static int qemu_cpu_exec(CPUState *env);
3600

    
3601
static void *kvm_cpu_thread_fn(void *arg)
3602
{
3603
    CPUState *env = arg;
3604

    
3605
    block_io_signals();
3606
    qemu_thread_self(env->thread);
3607
    if (kvm_enabled())
3608
        kvm_init_vcpu(env);
3609

    
3610
    /* signal CPU creation */
3611
    qemu_mutex_lock(&qemu_global_mutex);
3612
    env->created = 1;
3613
    qemu_cond_signal(&qemu_cpu_cond);
3614

    
3615
    /* and wait for machine initialization */
3616
    while (!qemu_system_ready)
3617
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3618

    
3619
    while (1) {
3620
        if (cpu_can_run(env))
3621
            qemu_cpu_exec(env);
3622
        qemu_wait_io_event(env);
3623
    }
3624

    
3625
    return NULL;
3626
}
3627

    
3628
static void tcg_cpu_exec(void);
3629

    
3630
static void *tcg_cpu_thread_fn(void *arg)
3631
{
3632
    CPUState *env = arg;
3633

    
3634
    block_io_signals();
3635
    qemu_thread_self(env->thread);
3636

    
3637
    /* signal CPU creation */
3638
    qemu_mutex_lock(&qemu_global_mutex);
3639
    for (env = first_cpu; env != NULL; env = env->next_cpu)
3640
        env->created = 1;
3641
    qemu_cond_signal(&qemu_cpu_cond);
3642

    
3643
    /* and wait for machine initialization */
3644
    while (!qemu_system_ready)
3645
        qemu_cond_timedwait(&qemu_system_cond, &qemu_global_mutex, 100);
3646

    
3647
    while (1) {
3648
        tcg_cpu_exec();
3649
        qemu_wait_io_event(cur_cpu);
3650
    }
3651

    
3652
    return NULL;
3653
}
3654

    
3655
void qemu_cpu_kick(void *_env)
3656
{
3657
    CPUState *env = _env;
3658
    qemu_cond_broadcast(env->halt_cond);
3659
    if (kvm_enabled())
3660
        qemu_thread_signal(env->thread, SIGUSR1);
3661
}
3662

    
3663
int qemu_cpu_self(void *_env)
3664
{
3665
    CPUState *env = _env;
3666
    QemuThread this;
3667
 
3668
    qemu_thread_self(&this);
3669
 
3670
    return qemu_thread_equal(&this, env->thread);
3671
}
3672

    
3673
static void cpu_signal(int sig)
3674
{
3675
    if (cpu_single_env)
3676
        cpu_exit(cpu_single_env);
3677
}
3678

    
3679
static void block_io_signals(void)
3680
{
3681
    sigset_t set;
3682
    struct sigaction sigact;
3683

    
3684
    sigemptyset(&set);
3685
    sigaddset(&set, SIGUSR2);
3686
    sigaddset(&set, SIGIO);
3687
    sigaddset(&set, SIGALRM);
3688
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3689

    
3690
    sigemptyset(&set);
3691
    sigaddset(&set, SIGUSR1);
3692
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3693

    
3694
    memset(&sigact, 0, sizeof(sigact));
3695
    sigact.sa_handler = cpu_signal;
3696
    sigaction(SIGUSR1, &sigact, NULL);
3697
}
3698

    
3699
static void unblock_io_signals(void)
3700
{
3701
    sigset_t set;
3702

    
3703
    sigemptyset(&set);
3704
    sigaddset(&set, SIGUSR2);
3705
    sigaddset(&set, SIGIO);
3706
    sigaddset(&set, SIGALRM);
3707
    pthread_sigmask(SIG_UNBLOCK, &set, NULL);
3708

    
3709
    sigemptyset(&set);
3710
    sigaddset(&set, SIGUSR1);
3711
    pthread_sigmask(SIG_BLOCK, &set, NULL);
3712
}
3713

    
3714
static void qemu_signal_lock(unsigned int msecs)
3715
{
3716
    qemu_mutex_lock(&qemu_fair_mutex);
3717

    
3718
    while (qemu_mutex_trylock(&qemu_global_mutex)) {
3719
        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);
3720
        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))
3721
            break;
3722
    }
3723
    qemu_mutex_unlock(&qemu_fair_mutex);
3724
}
3725

    
3726
void qemu_mutex_lock_iothread(void)
3727
{
3728
    if (kvm_enabled()) {
3729
        qemu_mutex_lock(&qemu_fair_mutex);
3730
        qemu_mutex_lock(&qemu_global_mutex);
3731
        qemu_mutex_unlock(&qemu_fair_mutex);
3732
    } else
3733
        qemu_signal_lock(100);
3734
}
3735

    
3736
void qemu_mutex_unlock_iothread(void)
3737
{
3738
    qemu_mutex_unlock(&qemu_global_mutex);
3739
}
3740

    
3741
static int all_vcpus_paused(void)
3742
{
3743
    CPUState *penv = first_cpu;
3744

    
3745
    while (penv) {
3746
        if (!penv->stopped)
3747
            return 0;
3748
        penv = (CPUState *)penv->next_cpu;
3749
    }
3750

    
3751
    return 1;
3752
}
3753

    
3754
static void pause_all_vcpus(void)
3755
{
3756
    CPUState *penv = first_cpu;
3757

    
3758
    while (penv) {
3759
        penv->stop = 1;
3760
        qemu_thread_signal(penv->thread, SIGUSR1);
3761
        qemu_cpu_kick(penv);
3762
        penv = (CPUState *)penv->next_cpu;
3763
    }
3764

    
3765
    while (!all_vcpus_paused()) {
3766
        qemu_cond_timedwait(&qemu_pause_cond, &qemu_global_mutex, 100);
3767
        penv = first_cpu;
3768
        while (penv) {
3769
            qemu_thread_signal(penv->thread, SIGUSR1);
3770
            penv = (CPUState *)penv->next_cpu;
3771
        }
3772
    }
3773
}
3774

    
3775
static void resume_all_vcpus(void)
3776
{
3777
    CPUState *penv = first_cpu;
3778

    
3779
    while (penv) {
3780
        penv->stop = 0;
3781
        penv->stopped = 0;
3782
        qemu_thread_signal(penv->thread, SIGUSR1);
3783
        qemu_cpu_kick(penv);
3784
        penv = (CPUState *)penv->next_cpu;
3785
    }
3786
}
3787

    
3788
static void tcg_init_vcpu(void *_env)
3789
{
3790
    CPUState *env = _env;
3791
    /* share a single thread for all cpus with TCG */
3792
    if (!tcg_cpu_thread) {
3793
        env->thread = qemu_mallocz(sizeof(QemuThread));
3794
        env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3795
        qemu_cond_init(env->halt_cond);
3796
        qemu_thread_create(env->thread, tcg_cpu_thread_fn, env);
3797
        while (env->created == 0)
3798
            qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3799
        tcg_cpu_thread = env->thread;
3800
        tcg_halt_cond = env->halt_cond;
3801
    } else {
3802
        env->thread = tcg_cpu_thread;
3803
        env->halt_cond = tcg_halt_cond;
3804
    }
3805
}
3806

    
3807
static void kvm_start_vcpu(CPUState *env)
3808
{
3809
    env->thread = qemu_mallocz(sizeof(QemuThread));
3810
    env->halt_cond = qemu_mallocz(sizeof(QemuCond));
3811
    qemu_cond_init(env->halt_cond);
3812
    qemu_thread_create(env->thread, kvm_cpu_thread_fn, env);
3813
    while (env->created == 0)
3814
        qemu_cond_timedwait(&qemu_cpu_cond, &qemu_global_mutex, 100);
3815
}
3816

    
3817
void qemu_init_vcpu(void *_env)
3818
{
3819
    CPUState *env = _env;
3820

    
3821
    if (kvm_enabled())
3822
        kvm_start_vcpu(env);
3823
    else
3824
        tcg_init_vcpu(env);
3825
    env->nr_cores = smp_cores;
3826
    env->nr_threads = smp_threads;
3827
}
3828

    
3829
void qemu_notify_event(void)
3830
{
3831
    qemu_event_increment();
3832
}
3833

    
3834
void vm_stop(int reason)
3835
{
3836
    QemuThread me;
3837
    qemu_thread_self(&me);
3838

    
3839
    if (!qemu_thread_equal(&me, &io_thread)) {
3840
        qemu_system_vmstop_request(reason);
3841
        /*
3842
         * FIXME: should not return to device code in case
3843
         * vm_stop() has been requested.
3844
         */
3845
        if (cpu_single_env) {
3846
            cpu_exit(cpu_single_env);
3847
            cpu_single_env->stop = 1;
3848
        }
3849
        return;
3850
    }
3851
    do_vm_stop(reason);
3852
}
3853

    
3854
#endif
3855

    
3856

    
3857
#ifdef _WIN32
3858
static void host_main_loop_wait(int *timeout)
3859
{
3860
    int ret, ret2, i;
3861
    PollingEntry *pe;
3862

    
3863

    
3864
    /* XXX: need to suppress polling by better using win32 events */
3865
    ret = 0;
3866
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3867
        ret |= pe->func(pe->opaque);
3868
    }
3869
    if (ret == 0) {
3870
        int err;
3871
        WaitObjects *w = &wait_objects;
3872

    
3873
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3874
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3875
            if (w->func[ret - WAIT_OBJECT_0])
3876
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3877

    
3878
            /* Check for additional signaled events */
3879
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3880

    
3881
                /* Check if event is signaled */
3882
                ret2 = WaitForSingleObject(w->events[i], 0);
3883
                if(ret2 == WAIT_OBJECT_0) {
3884
                    if (w->func[i])
3885
                        w->func[i](w->opaque[i]);
3886
                } else if (ret2 == WAIT_TIMEOUT) {
3887
                } else {
3888
                    err = GetLastError();
3889
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3890
                }
3891
            }
3892
        } else if (ret == WAIT_TIMEOUT) {
3893
        } else {
3894
            err = GetLastError();
3895
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3896
        }
3897
    }
3898

    
3899
    *timeout = 0;
3900
}
3901
#else
3902
static void host_main_loop_wait(int *timeout)
3903
{
3904
}
3905
#endif
3906

    
3907
void main_loop_wait(int timeout)
3908
{
3909
    IOHandlerRecord *ioh;
3910
    fd_set rfds, wfds, xfds;
3911
    int ret, nfds;
3912
    struct timeval tv;
3913

    
3914
    qemu_bh_update_timeout(&timeout);
3915

    
3916
    host_main_loop_wait(&timeout);
3917

    
3918
    /* poll any events */
3919
    /* XXX: separate device handlers from system ones */
3920
    nfds = -1;
3921
    FD_ZERO(&rfds);
3922
    FD_ZERO(&wfds);
3923
    FD_ZERO(&xfds);
3924
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3925
        if (ioh->deleted)
3926
            continue;
3927
        if (ioh->fd_read &&
3928
            (!ioh->fd_read_poll ||
3929
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3930
            FD_SET(ioh->fd, &rfds);
3931
            if (ioh->fd > nfds)
3932
                nfds = ioh->fd;
3933
        }
3934
        if (ioh->fd_write) {
3935
            FD_SET(ioh->fd, &wfds);
3936
            if (ioh->fd > nfds)
3937
                nfds = ioh->fd;
3938
        }
3939
    }
3940

    
3941
    tv.tv_sec = timeout / 1000;
3942
    tv.tv_usec = (timeout % 1000) * 1000;
3943

    
3944
    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3945

    
3946
    qemu_mutex_unlock_iothread();
3947
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3948
    qemu_mutex_lock_iothread();
3949
    if (ret > 0) {
3950
        IOHandlerRecord **pioh;
3951

    
3952
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3953
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3954
                ioh->fd_read(ioh->opaque);
3955
            }
3956
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3957
                ioh->fd_write(ioh->opaque);
3958
            }
3959
        }
3960

    
3961
        /* remove deleted IO handlers */
3962
        pioh = &first_io_handler;
3963
        while (*pioh) {
3964
            ioh = *pioh;
3965
            if (ioh->deleted) {
3966
                *pioh = ioh->next;
3967
                qemu_free(ioh);
3968
            } else
3969
                pioh = &ioh->next;
3970
        }
3971
    }
3972

    
3973
    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));
3974

    
3975
    /* rearm timer, if not periodic */
3976
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
3977
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
3978
        qemu_rearm_alarm_timer(alarm_timer);
3979
    }
3980

    
3981
    /* vm time timers */
3982
    if (vm_running) {
3983
        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3984
            qemu_run_timers(&active_timers[QEMU_CLOCK_VIRTUAL],
3985
                            qemu_get_clock(vm_clock));
3986
    }
3987

    
3988
    /* real time timers */
3989
    qemu_run_timers(&active_timers[QEMU_CLOCK_REALTIME],
3990
                    qemu_get_clock(rt_clock));
3991

    
3992
    qemu_run_timers(&active_timers[QEMU_CLOCK_HOST],
3993
                    qemu_get_clock(host_clock));
3994

    
3995
    /* Check bottom-halves last in case any of the earlier events triggered
3996
       them.  */
3997
    qemu_bh_poll();
3998

    
3999
}
4000

    
4001
static int qemu_cpu_exec(CPUState *env)
4002
{
4003
    int ret;
4004
#ifdef CONFIG_PROFILER
4005
    int64_t ti;
4006
#endif
4007

    
4008
#ifdef CONFIG_PROFILER
4009
    ti = profile_getclock();
4010
#endif
4011
    if (use_icount) {
4012
        int64_t count;
4013
        int decr;
4014
        qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4015
        env->icount_decr.u16.low = 0;
4016
        env->icount_extra = 0;
4017
        count = qemu_next_deadline();
4018
        count = (count + (1 << icount_time_shift) - 1)
4019
                >> icount_time_shift;
4020
        qemu_icount += count;
4021
        decr = (count > 0xffff) ? 0xffff : count;
4022
        count -= decr;
4023
        env->icount_decr.u16.low = decr;
4024
        env->icount_extra = count;
4025
    }
4026
    ret = cpu_exec(env);
4027
#ifdef CONFIG_PROFILER
4028
    qemu_time += profile_getclock() - ti;
4029
#endif
4030
    if (use_icount) {
4031
        /* Fold pending instructions back into the
4032
           instruction counter, and clear the interrupt flag.  */
4033
        qemu_icount -= (env->icount_decr.u16.low
4034
                        + env->icount_extra);
4035
        env->icount_decr.u32 = 0;
4036
        env->icount_extra = 0;
4037
    }
4038
    return ret;
4039
}
4040

    
4041
static void tcg_cpu_exec(void)
4042
{
4043
    int ret = 0;
4044

    
4045
    if (next_cpu == NULL)
4046
        next_cpu = first_cpu;
4047
    for (; next_cpu != NULL; next_cpu = next_cpu->next_cpu) {
4048
        CPUState *env = cur_cpu = next_cpu;
4049

    
4050
        if (!vm_running)
4051
            break;
4052
        if (timer_alarm_pending) {
4053
            timer_alarm_pending = 0;
4054
            break;
4055
        }
4056
        if (cpu_can_run(env))
4057
            ret = qemu_cpu_exec(env);
4058
        if (ret == EXCP_DEBUG) {
4059
            gdb_set_stop_cpu(env);
4060
            debug_requested = 1;
4061
            break;
4062
        }
4063
    }
4064
}
4065

    
4066
static int cpu_has_work(CPUState *env)
4067
{
4068
    if (env->stop)
4069
        return 1;
4070
    if (env->stopped)
4071
        return 0;
4072
    if (!env->halted)
4073
        return 1;
4074
    if (qemu_cpu_has_work(env))
4075
        return 1;
4076
    return 0;
4077
}
4078

    
4079
static int tcg_has_work(void)
4080
{
4081
    CPUState *env;
4082

    
4083
    for (env = first_cpu; env != NULL; env = env->next_cpu)
4084
        if (cpu_has_work(env))
4085
            return 1;
4086
    return 0;
4087
}
4088

    
4089
static int qemu_calculate_timeout(void)
4090
{
4091
#ifndef CONFIG_IOTHREAD
4092
    int timeout;
4093

    
4094
    if (!vm_running)
4095
        timeout = 5000;
4096
    else if (tcg_has_work())
4097
        timeout = 0;
4098
    else if (!use_icount)
4099
        timeout = 5000;
4100
    else {
4101
     /* XXX: use timeout computed from timers */
4102
        int64_t add;
4103
        int64_t delta;
4104
        /* Advance virtual time to the next event.  */
4105
        if (use_icount == 1) {
4106
            /* When not using an adaptive execution frequency
4107
               we tend to get badly out of sync with real time,
4108
               so just delay for a reasonable amount of time.  */
4109
            delta = 0;
4110
        } else {
4111
            delta = cpu_get_icount() - cpu_get_clock();
4112
        }
4113
        if (delta > 0) {
4114
            /* If virtual time is ahead of real time then just
4115
               wait for IO.  */
4116
            timeout = (delta / 1000000) + 1;
4117
        } else {
4118
            /* Wait for either IO to occur or the next
4119
               timer event.  */
4120
            add = qemu_next_deadline();
4121
            /* We advance the timer before checking for IO.
4122
               Limit the amount we advance so that early IO
4123
               activity won't get the guest too far ahead.  */
4124
            if (add > 10000000)
4125
                add = 10000000;
4126
            delta += add;
4127
            add = (add + (1 << icount_time_shift) - 1)
4128
                  >> icount_time_shift;
4129
            qemu_icount += add;
4130
            timeout = delta / 1000000;
4131
            if (timeout < 0)
4132
                timeout = 0;
4133
        }
4134
    }
4135

    
4136
    return timeout;
4137
#else /* CONFIG_IOTHREAD */
4138
    return 1000;
4139
#endif
4140
}
4141

    
4142
static int vm_can_run(void)
4143
{
4144
    if (powerdown_requested)
4145
        return 0;
4146
    if (reset_requested)
4147
        return 0;
4148
    if (shutdown_requested)
4149
        return 0;
4150
    if (debug_requested)
4151
        return 0;
4152
    return 1;
4153
}
4154

    
4155
qemu_irq qemu_system_powerdown;
4156

    
4157
static void main_loop(void)
4158
{
4159
    int r;
4160

    
4161
#ifdef CONFIG_IOTHREAD
4162
    qemu_system_ready = 1;
4163
    qemu_cond_broadcast(&qemu_system_cond);
4164
#endif
4165

    
4166
    for (;;) {
4167
        do {
4168
#ifdef CONFIG_PROFILER
4169
            int64_t ti;
4170
#endif
4171
#ifndef CONFIG_IOTHREAD
4172
            tcg_cpu_exec();
4173
#endif
4174
#ifdef CONFIG_PROFILER
4175
            ti = profile_getclock();
4176
#endif
4177
            main_loop_wait(qemu_calculate_timeout());
4178
#ifdef CONFIG_PROFILER
4179
            dev_time += profile_getclock() - ti;
4180
#endif
4181
        } while (vm_can_run());
4182

    
4183
        if (qemu_debug_requested()) {
4184
            monitor_protocol_event(QEVENT_DEBUG, NULL);
4185
            vm_stop(EXCP_DEBUG);
4186
        }
4187
        if (qemu_shutdown_requested()) {
4188
            monitor_protocol_event(QEVENT_SHUTDOWN, NULL);
4189
            if (no_shutdown) {
4190
                vm_stop(0);
4191
                no_shutdown = 0;
4192
            } else
4193
                break;
4194
        }
4195
        if (qemu_reset_requested()) {
4196
            monitor_protocol_event(QEVENT_RESET, NULL);
4197
            pause_all_vcpus();
4198
            qemu_system_reset();
4199
            resume_all_vcpus();
4200
        }
4201
        if (qemu_powerdown_requested()) {
4202
            monitor_protocol_event(QEVENT_POWERDOWN, NULL);
4203
            qemu_irq_raise(qemu_system_powerdown);
4204
        }
4205
        if ((r = qemu_vmstop_requested())) {
4206
            monitor_protocol_event(QEVENT_STOP, NULL);
4207
            vm_stop(r);
4208
        }
4209
    }
4210
    pause_all_vcpus();
4211
}
4212

    
4213
static void version(void)
4214
{
4215
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
4216
}
4217

    
4218
static void help(int exitcode)
4219
{
4220
    version();
4221
    printf("usage: %s [options] [disk_image]\n"
4222
           "\n"
4223
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4224
           "\n"
4225
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4226
           opt_help
4227
#define DEFHEADING(text) stringify(text) "\n"
4228
#include "qemu-options.h"
4229
#undef DEF
4230
#undef DEFHEADING
4231
#undef GEN_DOCS
4232
           "\n"
4233
           "During emulation, the following keys are useful:\n"
4234
           "ctrl-alt-f      toggle full screen\n"
4235
           "ctrl-alt-n      switch to virtual console 'n'\n"
4236
           "ctrl-alt        toggle mouse and keyboard grab\n"
4237
           "\n"
4238
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4239
           ,
4240
           "qemu",
4241
           DEFAULT_RAM_SIZE,
4242
#ifndef _WIN32
4243
           DEFAULT_NETWORK_SCRIPT,
4244
           DEFAULT_NETWORK_DOWN_SCRIPT,
4245
#endif
4246
           DEFAULT_GDBSTUB_PORT,
4247
           "/tmp/qemu.log");
4248
    exit(exitcode);
4249
}
4250

    
4251
#define HAS_ARG 0x0001
4252

    
4253
enum {
4254
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4255
    opt_enum,
4256
#define DEFHEADING(text)
4257
#include "qemu-options.h"
4258
#undef DEF
4259
#undef DEFHEADING
4260
#undef GEN_DOCS
4261
};
4262

    
4263
typedef struct QEMUOption {
4264
    const char *name;
4265
    int flags;
4266
    int index;
4267
} QEMUOption;
4268

    
4269
static const QEMUOption qemu_options[] = {
4270
    { "h", 0, QEMU_OPTION_h },
4271
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4272
    { option, opt_arg, opt_enum },
4273
#define DEFHEADING(text)
4274
#include "qemu-options.h"
4275
#undef DEF
4276
#undef DEFHEADING
4277
#undef GEN_DOCS
4278
    { NULL },
4279
};
4280

    
4281
#ifdef HAS_AUDIO
4282
struct soundhw soundhw[] = {
4283
#ifdef HAS_AUDIO_CHOICE
4284
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4285
    {
4286
        "pcspk",
4287
        "PC speaker",
4288
        0,
4289
        1,
4290
        { .init_isa = pcspk_audio_init }
4291
    },
4292
#endif
4293

    
4294
#ifdef CONFIG_SB16
4295
    {
4296
        "sb16",
4297
        "Creative Sound Blaster 16",
4298
        0,
4299
        1,
4300
        { .init_isa = SB16_init }
4301
    },
4302
#endif
4303

    
4304
#ifdef CONFIG_CS4231A
4305
    {
4306
        "cs4231a",
4307
        "CS4231A",
4308
        0,
4309
        1,
4310
        { .init_isa = cs4231a_init }
4311
    },
4312
#endif
4313

    
4314
#ifdef CONFIG_ADLIB
4315
    {
4316
        "adlib",
4317
#ifdef HAS_YMF262
4318
        "Yamaha YMF262 (OPL3)",
4319
#else
4320
        "Yamaha YM3812 (OPL2)",
4321
#endif
4322
        0,
4323
        1,
4324
        { .init_isa = Adlib_init }
4325
    },
4326
#endif
4327

    
4328
#ifdef CONFIG_GUS
4329
    {
4330
        "gus",
4331
        "Gravis Ultrasound GF1",
4332
        0,
4333
        1,
4334
        { .init_isa = GUS_init }
4335
    },
4336
#endif
4337

    
4338
#ifdef CONFIG_AC97
4339
    {
4340
        "ac97",
4341
        "Intel 82801AA AC97 Audio",
4342
        0,
4343
        0,
4344
        { .init_pci = ac97_init }
4345
    },
4346
#endif
4347

    
4348
#ifdef CONFIG_ES1370
4349
    {
4350
        "es1370",
4351
        "ENSONIQ AudioPCI ES1370",
4352
        0,
4353
        0,
4354
        { .init_pci = es1370_init }
4355
    },
4356
#endif
4357

    
4358
#endif /* HAS_AUDIO_CHOICE */
4359

    
4360
    { NULL, NULL, 0, 0, { NULL } }
4361
};
4362

    
4363
static void select_soundhw (const char *optarg)
4364
{
4365
    struct soundhw *c;
4366

    
4367
    if (*optarg == '?') {
4368
    show_valid_cards:
4369

    
4370
        printf ("Valid sound card names (comma separated):\n");
4371
        for (c = soundhw; c->name; ++c) {
4372
            printf ("%-11s %s\n", c->name, c->descr);
4373
        }
4374
        printf ("\n-soundhw all will enable all of the above\n");
4375
        exit (*optarg != '?');
4376
    }
4377
    else {
4378
        size_t l;
4379
        const char *p;
4380
        char *e;
4381
        int bad_card = 0;
4382

    
4383
        if (!strcmp (optarg, "all")) {
4384
            for (c = soundhw; c->name; ++c) {
4385
                c->enabled = 1;
4386
            }
4387
            return;
4388
        }
4389

    
4390
        p = optarg;
4391
        while (*p) {
4392
            e = strchr (p, ',');
4393
            l = !e ? strlen (p) : (size_t) (e - p);
4394

    
4395
            for (c = soundhw; c->name; ++c) {
4396
                if (!strncmp (c->name, p, l) && !c->name[l]) {
4397
                    c->enabled = 1;
4398
                    break;
4399
                }
4400
            }
4401

    
4402
            if (!c->name) {
4403
                if (l > 80) {
4404
                    fprintf (stderr,
4405
                             "Unknown sound card name (too big to show)\n");
4406
                }
4407
                else {
4408
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4409
                             (int) l, p);
4410
                }
4411
                bad_card = 1;
4412
            }
4413
            p += l + (e != NULL);
4414
        }
4415

    
4416
        if (bad_card)
4417
            goto show_valid_cards;
4418
    }
4419
}
4420
#endif
4421

    
4422
static void select_vgahw (const char *p)
4423
{
4424
    const char *opts;
4425

    
4426
    default_vga = 0;
4427
    vga_interface_type = VGA_NONE;
4428
    if (strstart(p, "std", &opts)) {
4429
        vga_interface_type = VGA_STD;
4430
    } else if (strstart(p, "cirrus", &opts)) {
4431
        vga_interface_type = VGA_CIRRUS;
4432
    } else if (strstart(p, "vmware", &opts)) {
4433
        vga_interface_type = VGA_VMWARE;
4434
    } else if (strstart(p, "xenfb", &opts)) {
4435
        vga_interface_type = VGA_XENFB;
4436
    } else if (!strstart(p, "none", &opts)) {
4437
    invalid_vga:
4438
        fprintf(stderr, "Unknown vga type: %s\n", p);
4439
        exit(1);
4440
    }
4441
    while (*opts) {
4442
        const char *nextopt;
4443

    
4444
        if (strstart(opts, ",retrace=", &nextopt)) {
4445
            opts = nextopt;
4446
            if (strstart(opts, "dumb", &nextopt))
4447
                vga_retrace_method = VGA_RETRACE_DUMB;
4448
            else if (strstart(opts, "precise", &nextopt))
4449
                vga_retrace_method = VGA_RETRACE_PRECISE;
4450
            else goto invalid_vga;
4451
        } else goto invalid_vga;
4452
        opts = nextopt;
4453
    }
4454
}
4455

    
4456
#ifdef TARGET_I386
4457
static int balloon_parse(const char *arg)
4458
{
4459
    QemuOpts *opts;
4460

    
4461
    if (strcmp(arg, "none") == 0) {
4462
        return 0;
4463
    }
4464

    
4465
    if (!strncmp(arg, "virtio", 6)) {
4466
        if (arg[6] == ',') {
4467
            /* have params -> parse them */
4468
            opts = qemu_opts_parse(&qemu_device_opts, arg+7, NULL);
4469
            if (!opts)
4470
                return  -1;
4471
        } else {
4472
            /* create empty opts */
4473
            opts = qemu_opts_create(&qemu_device_opts, NULL, 0);
4474
        }
4475
        qemu_opt_set(opts, "driver", "virtio-balloon-pci");
4476
        return 0;
4477
    }
4478

    
4479
    return -1;
4480
}
4481
#endif
4482

    
4483
#ifdef _WIN32
4484
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4485
{
4486
    exit(STATUS_CONTROL_C_EXIT);
4487
    return TRUE;
4488
}
4489
#endif
4490

    
4491
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4492
{
4493
    int ret;
4494

    
4495
    if(strlen(str) != 36)
4496
        return -1;
4497

    
4498
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4499
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4500
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4501

    
4502
    if(ret != 16)
4503
        return -1;
4504

    
4505
#ifdef TARGET_I386
4506
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4507
#endif
4508

    
4509
    return 0;
4510
}
4511

    
4512
#ifndef _WIN32
4513

    
4514
static void termsig_handler(int signal)
4515
{
4516
    qemu_system_shutdown_request();
4517
}
4518

    
4519
static void sigchld_handler(int signal)
4520
{
4521
    waitpid(-1, NULL, WNOHANG);
4522
}
4523

    
4524
static void sighandler_setup(void)
4525
{
4526
    struct sigaction act;
4527

    
4528
    memset(&act, 0, sizeof(act));
4529
    act.sa_handler = termsig_handler;
4530
    sigaction(SIGINT,  &act, NULL);
4531
    sigaction(SIGHUP,  &act, NULL);
4532
    sigaction(SIGTERM, &act, NULL);
4533

    
4534
    act.sa_handler = sigchld_handler;
4535
    act.sa_flags = SA_NOCLDSTOP;
4536
    sigaction(SIGCHLD, &act, NULL);
4537
}
4538

    
4539
#endif
4540

    
4541
#ifdef _WIN32
4542
/* Look for support files in the same directory as the executable.  */
4543
static char *find_datadir(const char *argv0)
4544
{
4545
    char *p;
4546
    char buf[MAX_PATH];
4547
    DWORD len;
4548

    
4549
    len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
4550
    if (len == 0) {
4551
        return NULL;
4552
    }
4553

    
4554
    buf[len] = 0;
4555
    p = buf + len - 1;
4556
    while (p != buf && *p != '\\')
4557
        p--;
4558
    *p = 0;
4559
    if (access(buf, R_OK) == 0) {
4560
        return qemu_strdup(buf);
4561
    }
4562
    return NULL;
4563
}
4564
#else /* !_WIN32 */
4565

    
4566
/* Find a likely location for support files using the location of the binary.
4567
   For installed binaries this will be "$bindir/../share/qemu".  When
4568
   running from the build tree this will be "$bindir/../pc-bios".  */
4569
#define SHARE_SUFFIX "/share/qemu"
4570
#define BUILD_SUFFIX "/pc-bios"
4571
static char *find_datadir(const char *argv0)
4572
{
4573
    char *dir;
4574
    char *p = NULL;
4575
    char *res;
4576
    char buf[PATH_MAX];
4577
    size_t max_len;
4578

    
4579
#if defined(__linux__)
4580
    {
4581
        int len;
4582
        len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
4583
        if (len > 0) {
4584
            buf[len] = 0;
4585
            p = buf;
4586
        }
4587
    }
4588
#elif defined(__FreeBSD__)
4589
    {
4590
        int len;
4591
        len = readlink("/proc/curproc/file", buf, sizeof(buf) - 1);
4592
        if (len > 0) {
4593
            buf[len] = 0;
4594
            p = buf;
4595
        }
4596
    }
4597
#endif
4598
    /* If we don't have any way of figuring out the actual executable
4599
       location then try argv[0].  */
4600
    if (!p) {
4601
        p = realpath(argv0, buf);
4602
        if (!p) {
4603
            return NULL;
4604
        }
4605
    }
4606
    dir = dirname(p);
4607
    dir = dirname(dir);
4608

    
4609
    max_len = strlen(dir) +
4610
        MAX(strlen(SHARE_SUFFIX), strlen(BUILD_SUFFIX)) + 1;
4611
    res = qemu_mallocz(max_len);
4612
    snprintf(res, max_len, "%s%s", dir, SHARE_SUFFIX);
4613
    if (access(res, R_OK)) {
4614
        snprintf(res, max_len, "%s%s", dir, BUILD_SUFFIX);
4615
        if (access(res, R_OK)) {
4616
            qemu_free(res);
4617
            res = NULL;
4618
        }
4619
    }
4620

    
4621
    return res;
4622
}
4623
#undef SHARE_SUFFIX
4624
#undef BUILD_SUFFIX
4625
#endif
4626

    
4627
char *qemu_find_file(int type, const char *name)
4628
{
4629
    int len;
4630
    const char *subdir;
4631
    char *buf;
4632

    
4633
    /* If name contains path separators then try it as a straight path.  */
4634
    if ((strchr(name, '/') || strchr(name, '\\'))
4635
        && access(name, R_OK) == 0) {
4636
        return qemu_strdup(name);
4637
    }
4638
    switch (type) {
4639
    case QEMU_FILE_TYPE_BIOS:
4640
        subdir = "";
4641
        break;
4642
    case QEMU_FILE_TYPE_KEYMAP:
4643
        subdir = "keymaps/";
4644
        break;
4645
    default:
4646
        abort();
4647
    }
4648
    len = strlen(data_dir) + strlen(name) + strlen(subdir) + 2;
4649
    buf = qemu_mallocz(len);
4650
    snprintf(buf, len, "%s/%s%s", data_dir, subdir, name);
4651
    if (access(buf, R_OK)) {
4652
        qemu_free(buf);
4653
        return NULL;
4654
    }
4655
    return buf;
4656
}
4657

    
4658
static int device_init_func(QemuOpts *opts, void *opaque)
4659
{
4660
    DeviceState *dev;
4661

    
4662
    dev = qdev_device_add(opts);
4663
    if (!dev)
4664
        return -1;
4665
    return 0;
4666
}
4667

    
4668
static int chardev_init_func(QemuOpts *opts, void *opaque)
4669
{
4670
    CharDriverState *chr;
4671

    
4672
    chr = qemu_chr_open_opts(opts, NULL);
4673
    if (!chr)
4674
        return -1;
4675
    return 0;
4676
}
4677

    
4678
static int mon_init_func(QemuOpts *opts, void *opaque)
4679
{
4680
    CharDriverState *chr;
4681
    const char *chardev;
4682
    const char *mode;
4683
    int flags;
4684

    
4685
    mode = qemu_opt_get(opts, "mode");
4686
    if (mode == NULL) {
4687
        mode = "readline";
4688
    }
4689
    if (strcmp(mode, "readline") == 0) {
4690
        flags = MONITOR_USE_READLINE;
4691
    } else if (strcmp(mode, "control") == 0) {
4692
        flags = MONITOR_USE_CONTROL;
4693
    } else {
4694
        fprintf(stderr, "unknown monitor mode \"%s\"\n", mode);
4695
        exit(1);
4696
    }
4697

    
4698
    if (qemu_opt_get_bool(opts, "default", 0))
4699
        flags |= MONITOR_IS_DEFAULT;
4700

    
4701
    chardev = qemu_opt_get(opts, "chardev");
4702
    chr = qemu_chr_find(chardev);
4703
    if (chr == NULL) {
4704
        fprintf(stderr, "chardev \"%s\" not found\n", chardev);
4705
        exit(1);
4706
    }
4707

    
4708
    monitor_init(chr, flags);
4709
    return 0;
4710
}
4711

    
4712
static void monitor_parse(const char *optarg, const char *mode)
4713
{
4714
    static int monitor_device_index = 0;
4715
    QemuOpts *opts;
4716
    const char *p;
4717
    char label[32];
4718
    int def = 0;
4719

    
4720
    if (strstart(optarg, "chardev:", &p)) {
4721
        snprintf(label, sizeof(label), "%s", p);
4722
    } else {
4723
        if (monitor_device_index) {
4724
            snprintf(label, sizeof(label), "monitor%d",
4725
                     monitor_device_index);
4726
        } else {
4727
            snprintf(label, sizeof(label), "monitor");
4728
            def = 1;
4729
        }
4730
        opts = qemu_chr_parse_compat(label, optarg);
4731
        if (!opts) {
4732
            fprintf(stderr, "parse error: %s\n", optarg);
4733
            exit(1);
4734
        }
4735
    }
4736

    
4737
    opts = qemu_opts_create(&qemu_mon_opts, label, 1);
4738
    if (!opts) {
4739
        fprintf(stderr, "duplicate chardev: %s\n", label);
4740
        exit(1);
4741
    }
4742
    qemu_opt_set(opts, "mode", mode);
4743
    qemu_opt_set(opts, "chardev", label);
4744
    if (def)
4745
        qemu_opt_set(opts, "default", "on");
4746
    monitor_device_index++;
4747
}
4748

    
4749
struct device_config {
4750
    enum {
4751
        DEV_USB,       /* -usbdevice     */
4752
        DEV_BT,        /* -bt            */
4753
        DEV_SERIAL,    /* -serial        */
4754
        DEV_PARALLEL,  /* -parallel      */
4755
        DEV_VIRTCON,   /* -virtioconsole */
4756
    } type;
4757
    const char *cmdline;
4758
    QTAILQ_ENTRY(device_config) next;
4759
};
4760
QTAILQ_HEAD(, device_config) device_configs = QTAILQ_HEAD_INITIALIZER(device_configs);
4761

    
4762
static void add_device_config(int type, const char *cmdline)
4763
{
4764
    struct device_config *conf;
4765

    
4766
    conf = qemu_mallocz(sizeof(*conf));
4767
    conf->type = type;
4768
    conf->cmdline = cmdline;
4769
    QTAILQ_INSERT_TAIL(&device_configs, conf, next);
4770
}
4771

    
4772
static int foreach_device_config(int type, int (*func)(const char *cmdline))
4773
{
4774
    struct device_config *conf;
4775
    int rc;
4776

    
4777
    QTAILQ_FOREACH(conf, &device_configs, next) {
4778
        if (conf->type != type)
4779
            continue;
4780
        rc = func(conf->cmdline);
4781
        if (0 != rc)
4782
            return rc;
4783
    }
4784
    return 0;
4785
}
4786

    
4787
static int serial_parse(const char *devname)
4788
{
4789
    static int index = 0;
4790
    char label[32];
4791

    
4792
    if (strcmp(devname, "none") == 0)
4793
        return 0;
4794
    if (index == MAX_SERIAL_PORTS) {
4795
        fprintf(stderr, "qemu: too many serial ports\n");
4796
        exit(1);
4797
    }
4798
    snprintf(label, sizeof(label), "serial%d", index);
4799
    serial_hds[index] = qemu_chr_open(label, devname, NULL);
4800
    if (!serial_hds[index]) {
4801
        fprintf(stderr, "qemu: could not open serial device '%s': %s\n",
4802
                devname, strerror(errno));
4803
        return -1;
4804
    }
4805
    index++;
4806
    return 0;
4807
}
4808

    
4809
static int parallel_parse(const char *devname)
4810
{
4811
    static int index = 0;
4812
    char label[32];
4813

    
4814
    if (strcmp(devname, "none") == 0)
4815
        return 0;
4816
    if (index == MAX_PARALLEL_PORTS) {
4817
        fprintf(stderr, "qemu: too many parallel ports\n");
4818
        exit(1);
4819
    }
4820
    snprintf(label, sizeof(label), "parallel%d", index);
4821
    parallel_hds[index] = qemu_chr_open(label, devname, NULL);
4822
    if (!parallel_hds[index]) {
4823
        fprintf(stderr, "qemu: could not open parallel device '%s': %s\n",
4824
                devname, strerror(errno));
4825
        return -1;
4826
    }
4827
    index++;
4828
    return 0;
4829
}
4830

    
4831
static int virtcon_parse(const char *devname)
4832
{
4833
    static int index = 0;
4834
    char label[32];
4835

    
4836
    if (strcmp(devname, "none") == 0)
4837
        return 0;
4838
    if (index == MAX_VIRTIO_CONSOLES) {
4839
        fprintf(stderr, "qemu: too many virtio consoles\n");
4840
        exit(1);
4841
    }
4842
    snprintf(label, sizeof(label), "virtcon%d", index);
4843
    virtcon_hds[index] = qemu_chr_open(label, devname, NULL);
4844
    if (!virtcon_hds[index]) {
4845
        fprintf(stderr, "qemu: could not open virtio console '%s': %s\n",
4846
                devname, strerror(errno));
4847
        return -1;
4848
    }
4849
    index++;
4850
    return 0;
4851
}
4852

    
4853
int main(int argc, char **argv, char **envp)
4854
{
4855
    const char *gdbstub_dev = NULL;
4856
    uint32_t boot_devices_bitmap = 0;
4857
    int i;
4858
    int snapshot, linux_boot, net_boot;
4859
    const char *initrd_filename;
4860
    const char *kernel_filename, *kernel_cmdline;
4861
    char boot_devices[33] = "cad"; /* default to HD->floppy->CD-ROM */
4862
    DisplayState *ds;
4863
    DisplayChangeListener *dcl;
4864
    int cyls, heads, secs, translation;
4865
    QemuOpts *hda_opts = NULL, *opts;
4866
    int optind;
4867
    const char *r, *optarg;
4868
    const char *loadvm = NULL;
4869
    QEMUMachine *machine;
4870
    const char *cpu_model;
4871
#ifndef _WIN32
4872
    int fds[2];
4873
#endif
4874
    int tb_size;
4875
    const char *pid_file = NULL;
4876
    const char *incoming = NULL;
4877
#ifndef _WIN32
4878
    int fd = 0;
4879
    struct passwd *pwd = NULL;
4880
    const char *chroot_dir = NULL;
4881
    const char *run_as = NULL;
4882
#endif
4883
    CPUState *env;
4884
    int show_vnc_port = 0;
4885

    
4886
    init_clocks();
4887

    
4888
    qemu_errors_to_file(stderr);
4889
    qemu_cache_utils_init(envp);
4890

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

    
4922
    module_call_init(MODULE_INIT_MACHINE);
4923
    machine = find_default_machine();
4924
    cpu_model = NULL;
4925
    initrd_filename = NULL;
4926
    ram_size = 0;
4927
    snapshot = 0;
4928
    kernel_filename = NULL;
4929
    kernel_cmdline = "";
4930
    cyls = heads = secs = 0;
4931
    translation = BIOS_ATA_TRANSLATION_AUTO;
4932

    
4933
    for (i = 0; i < MAX_NODES; i++) {
4934
        node_mem[i] = 0;
4935
        node_cpumask[i] = 0;
4936
    }
4937

    
4938
    nb_numa_nodes = 0;
4939
    nb_nics = 0;
4940

    
4941
    tb_size = 0;
4942
    autostart= 1;
4943

    
4944
    optind = 1;
4945
    for(;;) {
4946
        if (optind >= argc)
4947
            break;
4948
        r = argv[optind];
4949
        if (r[0] != '-') {
4950
            hda_opts = drive_add(argv[optind++], HD_ALIAS, 0);
4951
        } else {
4952
            const QEMUOption *popt;
4953

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

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

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

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

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

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

    
5267
                    mask = cpu_str_to_log_mask(optarg);
5268
                    if (!mask) {
5269
                        printf("Log items (comma separated):\n");
5270
                    for(item = cpu_log_items; item->mask != 0; item++) {
5271
                        printf("%-10s %s\n", item->name, item->help);
5272
                    }
5273
                    exit(1);
5274
                    }
5275
                    cpu_set_log(mask);
5276
                }
5277
                break;
5278
            case QEMU_OPTION_s:
5279
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
5280
                break;
5281
            case QEMU_OPTION_gdb:
5282
                gdbstub_dev = optarg;
5283
                break;
5284
            case QEMU_OPTION_L:
5285
                data_dir = optarg;
5286
                break;
5287
            case QEMU_OPTION_bios:
5288
                bios_name = optarg;
5289
                break;
5290
            case QEMU_OPTION_singlestep:
5291
                singlestep = 1;
5292
                break;
5293
            case QEMU_OPTION_S:
5294
                autostart = 0;
5295
                break;
5296
            case QEMU_OPTION_k:
5297
                keyboard_layout = optarg;
5298
                break;
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_parse(optarg, "readline");
5351
                default_monitor = 0;
5352
                break;
5353
            case QEMU_OPTION_qmp:
5354
                monitor_parse(optarg, "control");
5355
                default_monitor = 0;
5356
                break;
5357
            case QEMU_OPTION_mon:
5358
                opts = qemu_opts_parse(&qemu_mon_opts, optarg, "chardev");
5359
                if (!opts) {
5360
                    fprintf(stderr, "parse error: %s\n", optarg);
5361
                    exit(1);
5362
                }
5363
                default_monitor = 0;
5364
                break;
5365
            case QEMU_OPTION_chardev:
5366
                opts = qemu_opts_parse(&qemu_chardev_opts, optarg, "backend");
5367
                if (!opts) {
5368
                    fprintf(stderr, "parse error: %s\n", optarg);
5369
                    exit(1);
5370
                }
5371
                break;
5372
            case QEMU_OPTION_serial:
5373
                add_device_config(DEV_SERIAL, optarg);
5374
                default_serial = 0;
5375
                break;
5376
            case QEMU_OPTION_watchdog:
5377
                if (watchdog) {
5378
                    fprintf(stderr,
5379
                            "qemu: only one watchdog option may be given\n");
5380
                    return 1;
5381
                }
5382
                watchdog = optarg;
5383
                break;
5384
            case QEMU_OPTION_watchdog_action:
5385
                if (select_watchdog_action(optarg) == -1) {
5386
                    fprintf(stderr, "Unknown -watchdog-action parameter\n");
5387
                    exit(1);
5388
                }
5389
                break;
5390
            case QEMU_OPTION_virtiocon:
5391
                add_device_config(DEV_VIRTCON, optarg);
5392
                default_virtcon = 0;
5393
                break;
5394
            case QEMU_OPTION_parallel:
5395
                add_device_config(DEV_PARALLEL, optarg);
5396
                default_parallel = 0;
5397
                break;
5398
            case QEMU_OPTION_loadvm:
5399
                loadvm = optarg;
5400
                break;
5401
            case QEMU_OPTION_full_screen:
5402
                full_screen = 1;
5403
                break;
5404
#ifdef CONFIG_SDL
5405
            case QEMU_OPTION_no_frame:
5406
                no_frame = 1;
5407
                break;
5408
            case QEMU_OPTION_alt_grab:
5409
                alt_grab = 1;
5410
                break;
5411
            case QEMU_OPTION_ctrl_grab:
5412
                ctrl_grab = 1;
5413
                break;
5414
            case QEMU_OPTION_no_quit:
5415
                no_quit = 1;
5416
                break;
5417
            case QEMU_OPTION_sdl:
5418
                display_type = DT_SDL;
5419
                break;
5420
#endif
5421
            case QEMU_OPTION_pidfile:
5422
                pid_file = optarg;
5423
                break;
5424
#ifdef TARGET_I386
5425
            case QEMU_OPTION_win2k_hack:
5426
                win2k_install_hack = 1;
5427
                break;
5428
            case QEMU_OPTION_rtc_td_hack:
5429
                rtc_td_hack = 1;
5430
                break;
5431
            case QEMU_OPTION_acpitable:
5432
                if(acpi_table_add(optarg) < 0) {
5433
                    fprintf(stderr, "Wrong acpi table provided\n");
5434
                    exit(1);
5435
                }
5436
                break;
5437
            case QEMU_OPTION_smbios:
5438
                if(smbios_entry_add(optarg) < 0) {
5439
                    fprintf(stderr, "Wrong smbios provided\n");
5440
                    exit(1);
5441
                }
5442
                break;
5443
#endif
5444
#ifdef CONFIG_KVM
5445
            case QEMU_OPTION_enable_kvm:
5446
                kvm_allowed = 1;
5447
                break;
5448
#endif
5449
            case QEMU_OPTION_usb:
5450
                usb_enabled = 1;
5451
                break;
5452
            case QEMU_OPTION_usbdevice:
5453
                usb_enabled = 1;
5454
                add_device_config(DEV_USB, optarg);
5455
                break;
5456
            case QEMU_OPTION_device:
5457
                if (!qemu_opts_parse(&qemu_device_opts, optarg, "driver")) {
5458
                    exit(1);
5459
                }
5460
                break;
5461
            case QEMU_OPTION_smp:
5462
                smp_parse(optarg);
5463
                if (smp_cpus < 1) {
5464
                    fprintf(stderr, "Invalid number of CPUs\n");
5465
                    exit(1);
5466
                }
5467
                if (max_cpus < smp_cpus) {
5468
                    fprintf(stderr, "maxcpus must be equal to or greater than "
5469
                            "smp\n");
5470
                    exit(1);
5471
                }
5472
                if (max_cpus > 255) {
5473
                    fprintf(stderr, "Unsupported number of maxcpus\n");
5474
                    exit(1);
5475
                }
5476
                break;
5477
            case QEMU_OPTION_vnc:
5478
                display_type = DT_VNC;
5479
                vnc_display = optarg;
5480
                break;
5481
#ifdef TARGET_I386
5482
            case QEMU_OPTION_no_acpi:
5483
                acpi_enabled = 0;
5484
                break;
5485
            case QEMU_OPTION_no_hpet:
5486
                no_hpet = 1;
5487
                break;
5488
            case QEMU_OPTION_balloon:
5489
                if (balloon_parse(optarg) < 0) {
5490
                    fprintf(stderr, "Unknown -balloon argument %s\n", optarg);
5491
                    exit(1);
5492
                }
5493
                break;
5494
#endif
5495
            case QEMU_OPTION_no_reboot:
5496
                no_reboot = 1;
5497
                break;
5498
            case QEMU_OPTION_no_shutdown:
5499
                no_shutdown = 1;
5500
                break;
5501
            case QEMU_OPTION_show_cursor:
5502
                cursor_hide = 0;
5503
                break;
5504
            case QEMU_OPTION_uuid:
5505
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5506
                    fprintf(stderr, "Fail to parse UUID string."
5507
                            " Wrong format.\n");
5508
                    exit(1);
5509
                }
5510
                break;
5511
#ifndef _WIN32
5512
            case QEMU_OPTION_daemonize:
5513
                daemonize = 1;
5514
                break;
5515
#endif
5516
            case QEMU_OPTION_option_rom:
5517
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5518
                    fprintf(stderr, "Too many option ROMs\n");
5519
                    exit(1);
5520
                }
5521
                option_rom[nb_option_roms] = optarg;
5522
                nb_option_roms++;
5523
                break;
5524
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5525
            case QEMU_OPTION_semihosting:
5526
                semihosting_enabled = 1;
5527
                break;
5528
#endif
5529
            case QEMU_OPTION_name:
5530
                qemu_name = qemu_strdup(optarg);
5531
                 {
5532
                     char *p = strchr(qemu_name, ',');
5533
                     if (p != NULL) {
5534
                        *p++ = 0;
5535
                        if (strncmp(p, "process=", 8)) {
5536
                            fprintf(stderr, "Unknown subargument %s to -name", p);
5537
                            exit(1);
5538
                        }
5539
                        p += 8;
5540
                        set_proc_name(p);
5541
                     }        
5542
                 }        
5543
                break;
5544
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5545
            case QEMU_OPTION_prom_env:
5546
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5547
                    fprintf(stderr, "Too many prom variables\n");
5548
                    exit(1);
5549
                }
5550
                prom_envs[nb_prom_envs] = optarg;
5551
                nb_prom_envs++;
5552
                break;
5553
#endif
5554
#ifdef TARGET_ARM
5555
            case QEMU_OPTION_old_param:
5556
                old_param = 1;
5557
                break;
5558
#endif
5559
            case QEMU_OPTION_clock:
5560
                configure_alarms(optarg);
5561
                break;
5562
            case QEMU_OPTION_startdate:
5563
                configure_rtc_date_offset(optarg, 1);
5564
                break;
5565
            case QEMU_OPTION_rtc:
5566
                opts = qemu_opts_parse(&qemu_rtc_opts, optarg, NULL);
5567
                if (!opts) {
5568
                    fprintf(stderr, "parse error: %s\n", optarg);
5569
                    exit(1);
5570
                }
5571
                configure_rtc(opts);
5572
                break;
5573
            case QEMU_OPTION_tb_size:
5574
                tb_size = strtol(optarg, NULL, 0);
5575
                if (tb_size < 0)
5576
                    tb_size = 0;
5577
                break;
5578
            case QEMU_OPTION_icount:
5579
                use_icount = 1;
5580
                if (strcmp(optarg, "auto") == 0) {
5581
                    icount_time_shift = -1;
5582
                } else {
5583
                    icount_time_shift = strtol(optarg, NULL, 0);
5584
                }
5585
                break;
5586
            case QEMU_OPTION_incoming:
5587
                incoming = optarg;
5588
                break;
5589
            case QEMU_OPTION_nodefaults:
5590
                default_serial = 0;
5591
                default_parallel = 0;
5592
                default_virtcon = 0;
5593
                default_monitor = 0;
5594
                default_vga = 0;
5595
                default_net = 0;
5596
                default_floppy = 0;
5597
                default_cdrom = 0;
5598
                default_sdcard = 0;
5599
                break;
5600
#ifndef _WIN32
5601
            case QEMU_OPTION_chroot:
5602
                chroot_dir = optarg;
5603
                break;
5604
            case QEMU_OPTION_runas:
5605
                run_as = optarg;
5606
                break;
5607
#endif
5608
#ifdef CONFIG_XEN
5609
            case QEMU_OPTION_xen_domid:
5610
                xen_domid = atoi(optarg);
5611
                break;
5612
            case QEMU_OPTION_xen_create:
5613
                xen_mode = XEN_CREATE;
5614
                break;
5615
            case QEMU_OPTION_xen_attach:
5616
                xen_mode = XEN_ATTACH;
5617
                break;
5618
#endif
5619
            case QEMU_OPTION_readconfig:
5620
                {
5621
                    FILE *fp;
5622
                    fp = fopen(optarg, "r");
5623
                    if (fp == NULL) {
5624
                        fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5625
                        exit(1);
5626
                    }
5627
                    if (qemu_config_parse(fp) != 0) {
5628
                        exit(1);
5629
                    }
5630
                    fclose(fp);
5631
                    break;
5632
                }
5633
            case QEMU_OPTION_writeconfig:
5634
                {
5635
                    FILE *fp;
5636
                    if (strcmp(optarg, "-") == 0) {
5637
                        fp = stdout;
5638
                    } else {
5639
                        fp = fopen(optarg, "w");
5640
                        if (fp == NULL) {
5641
                            fprintf(stderr, "open %s: %s\n", optarg, strerror(errno));
5642
                            exit(1);
5643
                        }
5644
                    }
5645
                    qemu_config_write(fp);
5646
                    fclose(fp);
5647
                    break;
5648
                }
5649
            }
5650
        }
5651
    }
5652

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

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

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

    
5678
    qemu_opts_foreach(&qemu_device_opts, default_driver_check, NULL, 0);
5679

    
5680
    if (machine->no_serial) {
5681
        default_serial = 0;
5682
    }
5683
    if (machine->no_parallel) {
5684
        default_parallel = 0;
5685
    }
5686
    if (!machine->use_virtcon) {
5687
        default_virtcon = 0;
5688
    }
5689
    if (machine->no_vga) {
5690
        default_vga = 0;
5691
    }
5692
    if (machine->no_floppy) {
5693
        default_floppy = 0;
5694
    }
5695
    if (machine->no_cdrom) {
5696
        default_cdrom = 0;
5697
    }
5698
    if (machine->no_sdcard) {
5699
        default_sdcard = 0;
5700
    }
5701

    
5702
    if (display_type == DT_NOGRAPHIC) {
5703
        if (default_parallel)
5704
            add_device_config(DEV_PARALLEL, "null");
5705
        if (default_serial && default_monitor) {
5706
            add_device_config(DEV_SERIAL, "mon:stdio");
5707
        } else if (default_virtcon && default_monitor) {
5708
            add_device_config(DEV_VIRTCON, "mon:stdio");
5709
        } else {
5710
            if (default_serial)
5711
                add_device_config(DEV_SERIAL, "stdio");
5712
            if (default_virtcon)
5713
                add_device_config(DEV_VIRTCON, "stdio");
5714
            if (default_monitor)
5715
                monitor_parse("stdio", "readline");
5716
        }
5717
    } else {
5718
        if (default_serial)
5719
            add_device_config(DEV_SERIAL, "vc:80Cx24C");
5720
        if (default_parallel)
5721
            add_device_config(DEV_PARALLEL, "vc:80Cx24C");
5722
        if (default_monitor)
5723
            monitor_parse("vc:80Cx24C", "readline");
5724
        if (default_virtcon)
5725
            add_device_config(DEV_VIRTCON, "vc:80Cx24C");
5726
    }
5727
    if (default_vga)
5728
        vga_interface_type = VGA_CIRRUS;
5729

    
5730
    if (qemu_opts_foreach(&qemu_chardev_opts, chardev_init_func, NULL, 1) != 0)
5731
        exit(1);
5732

    
5733
#ifndef _WIN32
5734
    if (daemonize) {
5735
        pid_t pid;
5736

    
5737
        if (pipe(fds) == -1)
5738
            exit(1);
5739

    
5740
        pid = fork();
5741
        if (pid > 0) {
5742
            uint8_t status;
5743
            ssize_t len;
5744

    
5745
            close(fds[1]);
5746

    
5747
        again:
5748
            len = read(fds[0], &status, 1);
5749
            if (len == -1 && (errno == EINTR))
5750
                goto again;
5751

    
5752
            if (len != 1)
5753
                exit(1);
5754
            else if (status == 1) {
5755
                fprintf(stderr, "Could not acquire pidfile: %s\n", strerror(errno));
5756
                exit(1);
5757
            } else
5758
                exit(0);
5759
        } else if (pid < 0)
5760
            exit(1);
5761

    
5762
        close(fds[0]);
5763
        qemu_set_cloexec(fds[1]);
5764

    
5765
        setsid();
5766

    
5767
        pid = fork();
5768
        if (pid > 0)
5769
            exit(0);
5770
        else if (pid < 0)
5771
            exit(1);
5772

    
5773
        umask(027);
5774

    
5775
        signal(SIGTSTP, SIG_IGN);
5776
        signal(SIGTTOU, SIG_IGN);
5777
        signal(SIGTTIN, SIG_IGN);
5778
    }
5779

    
5780
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5781
        if (daemonize) {
5782
            uint8_t status = 1;
5783
            write(fds[1], &status, 1);
5784
        } else
5785
            fprintf(stderr, "Could not acquire pid file: %s\n", strerror(errno));
5786
        exit(1);
5787
    }
5788
#endif
5789

    
5790
    if (kvm_enabled()) {
5791
        int ret;
5792

    
5793
        ret = kvm_init(smp_cpus);
5794
        if (ret < 0) {
5795
            fprintf(stderr, "failed to initialize KVM\n");
5796
            exit(1);
5797
        }
5798
    }
5799

    
5800
    if (qemu_init_main_loop()) {
5801
        fprintf(stderr, "qemu_init_main_loop failed\n");
5802
        exit(1);
5803
    }
5804
    linux_boot = (kernel_filename != NULL);
5805

    
5806
    if (!linux_boot && *kernel_cmdline != '\0') {
5807
        fprintf(stderr, "-append only allowed with -kernel option\n");
5808
        exit(1);
5809
    }
5810

    
5811
    if (!linux_boot && initrd_filename != NULL) {
5812
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5813
        exit(1);
5814
    }
5815

    
5816
#ifndef _WIN32
5817
    /* Win32 doesn't support line-buffering and requires size >= 2 */
5818
    setvbuf(stdout, NULL, _IOLBF, 0);
5819
#endif
5820

    
5821
    if (init_timer_alarm() < 0) {
5822
        fprintf(stderr, "could not initialize alarm timer\n");
5823
        exit(1);
5824
    }
5825
    if (use_icount && icount_time_shift < 0) {
5826
        use_icount = 2;
5827
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5828
           It will be corrected fairly quickly anyway.  */
5829
        icount_time_shift = 3;
5830
        init_icount_adjust();
5831
    }
5832

    
5833
#ifdef _WIN32
5834
    socket_init();
5835
#endif
5836

    
5837
    if (net_init_clients() < 0) {
5838
        exit(1);
5839
    }
5840

    
5841
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5842
    net_set_boot_mask(net_boot);
5843

    
5844
    /* init the bluetooth world */
5845
    if (foreach_device_config(DEV_BT, bt_parse))
5846
        exit(1);
5847

    
5848
    /* init the memory */
5849
    if (ram_size == 0)
5850
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5851

    
5852
    /* init the dynamic translator */
5853
    cpu_exec_init_all(tb_size * 1024 * 1024);
5854

    
5855
    bdrv_init_with_whitelist();
5856

    
5857
    blk_mig_init();
5858

    
5859
    if (default_cdrom) {
5860
        /* we always create the cdrom drive, even if no disk is there */
5861
        drive_add(NULL, CDROM_ALIAS);
5862
    }
5863

    
5864
    if (default_floppy) {
5865
        /* we always create at least one floppy */
5866
        drive_add(NULL, FD_ALIAS, 0);
5867
    }
5868

    
5869
    if (default_sdcard) {
5870
        /* we always create one sd slot, even if no card is in it */
5871
        drive_add(NULL, SD_ALIAS);
5872
    }
5873

    
5874
    /* open the virtual block devices */
5875
    if (snapshot)
5876
        qemu_opts_foreach(&qemu_drive_opts, drive_enable_snapshot, NULL, 0);
5877
    if (qemu_opts_foreach(&qemu_drive_opts, drive_init_func, machine, 1) != 0)
5878
        exit(1);
5879

    
5880
    vmstate_register(0, &vmstate_timers ,&timers_state);
5881
    register_savevm_live("ram", 0, 3, NULL, ram_save_live, NULL, 
5882
                         ram_load, NULL);
5883

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

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

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

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

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

    
5926
    if (foreach_device_config(DEV_SERIAL, serial_parse) < 0)
5927
        exit(1);
5928
    if (foreach_device_config(DEV_PARALLEL, parallel_parse) < 0)
5929
        exit(1);
5930
    if (foreach_device_config(DEV_VIRTCON, virtcon_parse) < 0)
5931
        exit(1);
5932

    
5933
    module_call_init(MODULE_INIT_DEVICE);
5934

    
5935
    if (watchdog) {
5936
        i = select_watchdog(watchdog);
5937
        if (i > 0)
5938
            exit (i == 1 ? 1 : 0);
5939
    }
5940

    
5941
    if (machine->compat_props) {
5942
        qdev_prop_register_global_list(machine->compat_props);
5943
    }
5944
    qemu_add_globals();
5945

    
5946
    machine->init(ram_size, boot_devices,
5947
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5948

    
5949

    
5950
#ifndef _WIN32
5951
    /* must be after terminal init, SDL library changes signal handlers */
5952
    sighandler_setup();
5953
#endif
5954

    
5955
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
5956
        for (i = 0; i < nb_numa_nodes; i++) {
5957
            if (node_cpumask[i] & (1 << env->cpu_index)) {
5958
                env->numa_node = i;
5959
            }
5960
        }
5961
    }
5962

    
5963
    current_machine = machine;
5964

    
5965
    /* init USB devices */
5966
    if (usb_enabled) {
5967
        if (foreach_device_config(DEV_USB, usb_parse) < 0)
5968
            exit(1);
5969
    }
5970

    
5971
    /* init generic devices */
5972
    if (qemu_opts_foreach(&qemu_device_opts, device_init_func, NULL, 1) != 0)
5973
        exit(1);
5974

    
5975
    if (!display_state)
5976
        dumb_display_init();
5977
    /* just use the first displaystate for the moment */
5978
    ds = display_state;
5979

    
5980
    if (display_type == DT_DEFAULT) {
5981
#if defined(CONFIG_SDL) || defined(CONFIG_COCOA)
5982
        display_type = DT_SDL;
5983
#else
5984
        display_type = DT_VNC;
5985
        vnc_display = "localhost:0,to=99";
5986
        show_vnc_port = 1;
5987
#endif
5988
    }
5989
        
5990

    
5991
    switch (display_type) {
5992
    case DT_NOGRAPHIC:
5993
        break;
5994
#if defined(CONFIG_CURSES)
5995
    case DT_CURSES:
5996
        curses_display_init(ds, full_screen);
5997
        break;
5998
#endif
5999
#if defined(CONFIG_SDL)
6000
    case DT_SDL:
6001
        sdl_display_init(ds, full_screen, no_frame);
6002
        break;
6003
#elif defined(CONFIG_COCOA)
6004
    case DT_SDL:
6005
        cocoa_display_init(ds, full_screen);
6006
        break;
6007
#endif
6008
    case DT_VNC:
6009
        vnc_display_init(ds);
6010
        if (vnc_display_open(ds, vnc_display) < 0)
6011
            exit(1);
6012

    
6013
        if (show_vnc_port) {
6014
            printf("VNC server running on `%s'\n", vnc_display_local_addr(ds));
6015
        }
6016
        break;
6017
    default:
6018
        break;
6019
    }
6020
    dpy_resize(ds);
6021

    
6022
    dcl = ds->listeners;
6023
    while (dcl != NULL) {
6024
        if (dcl->dpy_refresh != NULL) {
6025
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
6026
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
6027
        }
6028
        dcl = dcl->next;
6029
    }
6030

    
6031
    if (display_type == DT_NOGRAPHIC || display_type == DT_VNC) {
6032
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
6033
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
6034
    }
6035

    
6036
    text_consoles_set_display(display_state);
6037

    
6038
    if (qemu_opts_foreach(&qemu_mon_opts, mon_init_func, NULL, 1) != 0)
6039
        exit(1);
6040

    
6041
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
6042
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
6043
                gdbstub_dev);
6044
        exit(1);
6045
    }
6046

    
6047
    qdev_machine_creation_done();
6048

    
6049
    rom_load_all();
6050

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

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

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

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

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

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

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

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

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

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

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

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

    
6127
    return 0;
6128
}