Statistics
| Branch: | Revision:

root / vl.c @ d12d51d5

History | View | Annotate | Download (149.3 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 "hw/hw.h"
25
#include "hw/boards.h"
26
#include "hw/usb.h"
27
#include "hw/pcmcia.h"
28
#include "hw/pc.h"
29
#include "hw/audiodev.h"
30
#include "hw/isa.h"
31
#include "hw/baum.h"
32
#include "hw/bt.h"
33
#include "net.h"
34
#include "console.h"
35
#include "sysemu.h"
36
#include "gdbstub.h"
37
#include "qemu-timer.h"
38
#include "qemu-char.h"
39
#include "cache-utils.h"
40
#include "block.h"
41
#include "audio/audio.h"
42
#include "migration.h"
43
#include "kvm.h"
44
#include "balloon.h"
45

    
46
#include <unistd.h>
47
#include <fcntl.h>
48
#include <signal.h>
49
#include <time.h>
50
#include <errno.h>
51
#include <sys/time.h>
52
#include <zlib.h>
53

    
54
#ifndef _WIN32
55
#include <sys/times.h>
56
#include <sys/wait.h>
57
#include <termios.h>
58
#include <sys/mman.h>
59
#include <sys/ioctl.h>
60
#include <sys/resource.h>
61
#include <sys/socket.h>
62
#include <netinet/in.h>
63
#include <net/if.h>
64
#if defined(__NetBSD__)
65
#include <net/if_tap.h>
66
#endif
67
#ifdef __linux__
68
#include <linux/if_tun.h>
69
#endif
70
#include <arpa/inet.h>
71
#include <dirent.h>
72
#include <netdb.h>
73
#include <sys/select.h>
74
#ifdef _BSD
75
#include <sys/stat.h>
76
#ifdef __FreeBSD__
77
#include <libutil.h>
78
#else
79
#include <util.h>
80
#endif
81
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
82
#include <freebsd/stdlib.h>
83
#else
84
#ifdef __linux__
85
#include <pty.h>
86
#include <malloc.h>
87
#include <linux/rtc.h>
88

    
89
/* For the benefit of older linux systems which don't supply it,
90
   we use a local copy of hpet.h. */
91
/* #include <linux/hpet.h> */
92
#include "hpet.h"
93

    
94
#include <linux/ppdev.h>
95
#include <linux/parport.h>
96
#endif
97
#ifdef __sun__
98
#include <sys/stat.h>
99
#include <sys/ethernet.h>
100
#include <sys/sockio.h>
101
#include <netinet/arp.h>
102
#include <netinet/in.h>
103
#include <netinet/in_systm.h>
104
#include <netinet/ip.h>
105
#include <netinet/ip_icmp.h> // must come after ip.h
106
#include <netinet/udp.h>
107
#include <netinet/tcp.h>
108
#include <net/if.h>
109
#include <syslog.h>
110
#include <stropts.h>
111
#endif
112
#endif
113
#endif
114

    
115
#include "qemu_socket.h"
116

    
117
#if defined(CONFIG_SLIRP)
118
#include "libslirp.h"
119
#endif
120

    
121
#if defined(__OpenBSD__)
122
#include <util.h>
123
#endif
124

    
125
#if defined(CONFIG_VDE)
126
#include <libvdeplug.h>
127
#endif
128

    
129
#ifdef _WIN32
130
#include <malloc.h>
131
#include <sys/timeb.h>
132
#include <mmsystem.h>
133
#define getopt_long_only getopt_long
134
#define memalign(align, size) malloc(size)
135
#endif
136

    
137
#ifdef CONFIG_SDL
138
#ifdef __APPLE__
139
#include <SDL/SDL.h>
140
#endif
141
#endif /* CONFIG_SDL */
142

    
143
#ifdef CONFIG_COCOA
144
#undef main
145
#define main qemu_main
146
#endif /* CONFIG_COCOA */
147

    
148
#include "disas.h"
149

    
150
#include "exec-all.h"
151

    
152
//#define DEBUG_UNUSED_IOPORT
153
//#define DEBUG_IOPORT
154
//#define DEBUG_NET
155
//#define DEBUG_SLIRP
156

    
157

    
158
#ifdef DEBUG_IOPORT
159
#  define LOG_IOPORT(...) do {           \
160
     if (loglevel & CPU_LOG_IOPORT)      \
161
       fprintf(logfile, ## __VA_ARGS__); \
162
   } while (0)
163
#else
164
#  define LOG_IOPORT(...) do { } while (0)
165
#endif
166

    
167
#ifdef TARGET_PPC
168
#define DEFAULT_RAM_SIZE 144
169
#else
170
#define DEFAULT_RAM_SIZE 128
171
#endif
172

    
173
/* Max number of USB devices that can be specified on the commandline.  */
174
#define MAX_USB_CMDLINE 8
175

    
176
/* Max number of bluetooth switches on the commandline.  */
177
#define MAX_BT_CMDLINE 10
178

    
179
/* XXX: use a two level table to limit memory usage */
180
#define MAX_IOPORTS 65536
181

    
182
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
183
const char *bios_name = NULL;
184
static void *ioport_opaque[MAX_IOPORTS];
185
static IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
186
static IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
187
/* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
188
   to store the VM snapshots */
189
DriveInfo drives_table[MAX_DRIVES+1];
190
int nb_drives;
191
static int vga_ram_size;
192
enum vga_retrace_method vga_retrace_method = VGA_RETRACE_DUMB;
193
DisplayState display_state;
194
int nographic;
195
static int curses;
196
const char* keyboard_layout = NULL;
197
int64_t ticks_per_sec;
198
ram_addr_t ram_size;
199
int nb_nics;
200
NICInfo nd_table[MAX_NICS];
201
int vm_running;
202
static int rtc_utc = 1;
203
static int rtc_date_offset = -1; /* -1 means no change */
204
int cirrus_vga_enabled = 1;
205
int std_vga_enabled = 0;
206
int vmsvga_enabled = 0;
207
#ifdef TARGET_SPARC
208
int graphic_width = 1024;
209
int graphic_height = 768;
210
int graphic_depth = 8;
211
#else
212
int graphic_width = 800;
213
int graphic_height = 600;
214
int graphic_depth = 15;
215
#endif
216
static int full_screen = 0;
217
#ifdef CONFIG_SDL
218
static int no_frame = 0;
219
#endif
220
int no_quit = 0;
221
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
222
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
223
CharDriverState *virtcon_hds[MAX_VIRTIO_CONSOLES];
224
#ifdef TARGET_I386
225
int win2k_install_hack = 0;
226
int rtc_td_hack = 0;
227
#endif
228
int usb_enabled = 0;
229
int smp_cpus = 1;
230
const char *vnc_display;
231
int acpi_enabled = 1;
232
int no_hpet = 0;
233
int fd_bootchk = 1;
234
int no_reboot = 0;
235
int no_shutdown = 0;
236
int cursor_hide = 1;
237
int graphic_rotate = 0;
238
int daemonize = 0;
239
const char *option_rom[MAX_OPTION_ROMS];
240
int nb_option_roms;
241
int semihosting_enabled = 0;
242
#ifdef TARGET_ARM
243
int old_param = 0;
244
#endif
245
const char *qemu_name;
246
int alt_grab = 0;
247
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
248
unsigned int nb_prom_envs = 0;
249
const char *prom_envs[MAX_PROM_ENVS];
250
#endif
251
static int nb_drives_opt;
252
static struct drive_opt {
253
    const char *file;
254
    char opt[1024];
255
} drives_opt[MAX_DRIVES];
256

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

    
269
uint8_t qemu_uuid[16];
270

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

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

    
277
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
278
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
279

    
280
static uint32_t ioport_read(int index, uint32_t address)
281
{
282
    static IOPortReadFunc *default_func[3] = {
283
        default_ioport_readb,
284
        default_ioport_readw,
285
        default_ioport_readl
286
    };
287
    IOPortReadFunc *func = ioport_read_table[index][address];
288
    if (!func)
289
        func = default_func[index];
290
    return func(ioport_opaque[address], address);
291
}
292

    
293
static void ioport_write(int index, uint32_t address, uint32_t data)
294
{
295
    static IOPortWriteFunc *default_func[3] = {
296
        default_ioport_writeb,
297
        default_ioport_writew,
298
        default_ioport_writel
299
    };
300
    IOPortWriteFunc *func = ioport_write_table[index][address];
301
    if (!func)
302
        func = default_func[index];
303
    func(ioport_opaque[address], address, data);
304
}
305

    
306
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
307
{
308
#ifdef DEBUG_UNUSED_IOPORT
309
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
310
#endif
311
    return 0xff;
312
}
313

    
314
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
315
{
316
#ifdef DEBUG_UNUSED_IOPORT
317
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
318
#endif
319
}
320

    
321
/* default is to make two byte accesses */
322
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
323
{
324
    uint32_t data;
325
    data = ioport_read(0, address);
326
    address = (address + 1) & (MAX_IOPORTS - 1);
327
    data |= ioport_read(0, address) << 8;
328
    return data;
329
}
330

    
331
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
332
{
333
    ioport_write(0, address, data & 0xff);
334
    address = (address + 1) & (MAX_IOPORTS - 1);
335
    ioport_write(0, address, (data >> 8) & 0xff);
336
}
337

    
338
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
339
{
340
#ifdef DEBUG_UNUSED_IOPORT
341
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
342
#endif
343
    return 0xffffffff;
344
}
345

    
346
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
347
{
348
#ifdef DEBUG_UNUSED_IOPORT
349
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
350
#endif
351
}
352

    
353
/* size is the word size in byte */
354
int register_ioport_read(int start, int length, int size,
355
                         IOPortReadFunc *func, void *opaque)
356
{
357
    int i, bsize;
358

    
359
    if (size == 1) {
360
        bsize = 0;
361
    } else if (size == 2) {
362
        bsize = 1;
363
    } else if (size == 4) {
364
        bsize = 2;
365
    } else {
366
        hw_error("register_ioport_read: invalid size");
367
        return -1;
368
    }
369
    for(i = start; i < start + length; i += size) {
370
        ioport_read_table[bsize][i] = func;
371
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
372
            hw_error("register_ioport_read: invalid opaque");
373
        ioport_opaque[i] = opaque;
374
    }
375
    return 0;
376
}
377

    
378
/* size is the word size in byte */
379
int register_ioport_write(int start, int length, int size,
380
                          IOPortWriteFunc *func, void *opaque)
381
{
382
    int i, bsize;
383

    
384
    if (size == 1) {
385
        bsize = 0;
386
    } else if (size == 2) {
387
        bsize = 1;
388
    } else if (size == 4) {
389
        bsize = 2;
390
    } else {
391
        hw_error("register_ioport_write: invalid size");
392
        return -1;
393
    }
394
    for(i = start; i < start + length; i += size) {
395
        ioport_write_table[bsize][i] = func;
396
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
397
            hw_error("register_ioport_write: invalid opaque");
398
        ioport_opaque[i] = opaque;
399
    }
400
    return 0;
401
}
402

    
403
void isa_unassign_ioport(int start, int length)
404
{
405
    int i;
406

    
407
    for(i = start; i < start + length; i++) {
408
        ioport_read_table[0][i] = default_ioport_readb;
409
        ioport_read_table[1][i] = default_ioport_readw;
410
        ioport_read_table[2][i] = default_ioport_readl;
411

    
412
        ioport_write_table[0][i] = default_ioport_writeb;
413
        ioport_write_table[1][i] = default_ioport_writew;
414
        ioport_write_table[2][i] = default_ioport_writel;
415
    }
416
}
417

    
418
/***********************************************************/
419

    
420
void cpu_outb(CPUState *env, int addr, int val)
421
{
422
    LOG_IOPORT("outb: %04x %02x\n", addr, val);
423
    ioport_write(0, addr, val);
424
#ifdef USE_KQEMU
425
    if (env)
426
        env->last_io_time = cpu_get_time_fast();
427
#endif
428
}
429

    
430
void cpu_outw(CPUState *env, int addr, int val)
431
{
432
    LOG_IOPORT("outw: %04x %04x\n", addr, val);
433
    ioport_write(1, addr, val);
434
#ifdef USE_KQEMU
435
    if (env)
436
        env->last_io_time = cpu_get_time_fast();
437
#endif
438
}
439

    
440
void cpu_outl(CPUState *env, int addr, int val)
441
{
442
    LOG_IOPORT("outl: %04x %08x\n", addr, val);
443
    ioport_write(2, addr, val);
444
#ifdef USE_KQEMU
445
    if (env)
446
        env->last_io_time = cpu_get_time_fast();
447
#endif
448
}
449

    
450
int cpu_inb(CPUState *env, int addr)
451
{
452
    int val;
453
    val = ioport_read(0, addr);
454
    LOG_IOPORT("inb : %04x %02x\n", addr, val);
455
#ifdef USE_KQEMU
456
    if (env)
457
        env->last_io_time = cpu_get_time_fast();
458
#endif
459
    return val;
460
}
461

    
462
int cpu_inw(CPUState *env, int addr)
463
{
464
    int val;
465
    val = ioport_read(1, addr);
466
    LOG_IOPORT("inw : %04x %04x\n", addr, val);
467
#ifdef USE_KQEMU
468
    if (env)
469
        env->last_io_time = cpu_get_time_fast();
470
#endif
471
    return val;
472
}
473

    
474
int cpu_inl(CPUState *env, int addr)
475
{
476
    int val;
477
    val = ioport_read(2, addr);
478
    LOG_IOPORT("inl : %04x %08x\n", addr, val);
479
#ifdef USE_KQEMU
480
    if (env)
481
        env->last_io_time = cpu_get_time_fast();
482
#endif
483
    return val;
484
}
485

    
486
/***********************************************************/
487
void hw_error(const char *fmt, ...)
488
{
489
    va_list ap;
490
    CPUState *env;
491

    
492
    va_start(ap, fmt);
493
    fprintf(stderr, "qemu: hardware error: ");
494
    vfprintf(stderr, fmt, ap);
495
    fprintf(stderr, "\n");
496
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
497
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
498
#ifdef TARGET_I386
499
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
500
#else
501
        cpu_dump_state(env, stderr, fprintf, 0);
502
#endif
503
    }
504
    va_end(ap);
505
    abort();
506
}
507
 
508
/***************/
509
/* ballooning */
510

    
511
static QEMUBalloonEvent *qemu_balloon_event;
512
void *qemu_balloon_event_opaque;
513

    
514
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
515
{
516
    qemu_balloon_event = func;
517
    qemu_balloon_event_opaque = opaque;
518
}
519

    
520
void qemu_balloon(ram_addr_t target)
521
{
522
    if (qemu_balloon_event)
523
        qemu_balloon_event(qemu_balloon_event_opaque, target);
524
}
525

    
526
ram_addr_t qemu_balloon_status(void)
527
{
528
    if (qemu_balloon_event)
529
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
530
    return 0;
531
}
532

    
533
/***********************************************************/
534
/* keyboard/mouse */
535

    
536
static QEMUPutKBDEvent *qemu_put_kbd_event;
537
static void *qemu_put_kbd_event_opaque;
538
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
539
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
540

    
541
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
542
{
543
    qemu_put_kbd_event_opaque = opaque;
544
    qemu_put_kbd_event = func;
545
}
546

    
547
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
548
                                                void *opaque, int absolute,
549
                                                const char *name)
550
{
551
    QEMUPutMouseEntry *s, *cursor;
552

    
553
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
554
    if (!s)
555
        return NULL;
556

    
557
    s->qemu_put_mouse_event = func;
558
    s->qemu_put_mouse_event_opaque = opaque;
559
    s->qemu_put_mouse_event_absolute = absolute;
560
    s->qemu_put_mouse_event_name = qemu_strdup(name);
561
    s->next = NULL;
562

    
563
    if (!qemu_put_mouse_event_head) {
564
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
565
        return s;
566
    }
567

    
568
    cursor = qemu_put_mouse_event_head;
569
    while (cursor->next != NULL)
570
        cursor = cursor->next;
571

    
572
    cursor->next = s;
573
    qemu_put_mouse_event_current = s;
574

    
575
    return s;
576
}
577

    
578
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
579
{
580
    QEMUPutMouseEntry *prev = NULL, *cursor;
581

    
582
    if (!qemu_put_mouse_event_head || entry == NULL)
583
        return;
584

    
585
    cursor = qemu_put_mouse_event_head;
586
    while (cursor != NULL && cursor != entry) {
587
        prev = cursor;
588
        cursor = cursor->next;
589
    }
590

    
591
    if (cursor == NULL) // does not exist or list empty
592
        return;
593
    else if (prev == NULL) { // entry is head
594
        qemu_put_mouse_event_head = cursor->next;
595
        if (qemu_put_mouse_event_current == entry)
596
            qemu_put_mouse_event_current = cursor->next;
597
        qemu_free(entry->qemu_put_mouse_event_name);
598
        qemu_free(entry);
599
        return;
600
    }
601

    
602
    prev->next = entry->next;
603

    
604
    if (qemu_put_mouse_event_current == entry)
605
        qemu_put_mouse_event_current = prev;
606

    
607
    qemu_free(entry->qemu_put_mouse_event_name);
608
    qemu_free(entry);
609
}
610

    
611
void kbd_put_keycode(int keycode)
612
{
613
    if (qemu_put_kbd_event) {
614
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
615
    }
616
}
617

    
618
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
619
{
620
    QEMUPutMouseEvent *mouse_event;
621
    void *mouse_event_opaque;
622
    int width;
623

    
624
    if (!qemu_put_mouse_event_current) {
625
        return;
626
    }
627

    
628
    mouse_event =
629
        qemu_put_mouse_event_current->qemu_put_mouse_event;
630
    mouse_event_opaque =
631
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
632

    
633
    if (mouse_event) {
634
        if (graphic_rotate) {
635
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
636
                width = 0x7fff;
637
            else
638
                width = graphic_width - 1;
639
            mouse_event(mouse_event_opaque,
640
                                 width - dy, dx, dz, buttons_state);
641
        } else
642
            mouse_event(mouse_event_opaque,
643
                                 dx, dy, dz, buttons_state);
644
    }
645
}
646

    
647
int kbd_mouse_is_absolute(void)
648
{
649
    if (!qemu_put_mouse_event_current)
650
        return 0;
651

    
652
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
653
}
654

    
655
void do_info_mice(void)
656
{
657
    QEMUPutMouseEntry *cursor;
658
    int index = 0;
659

    
660
    if (!qemu_put_mouse_event_head) {
661
        term_printf("No mouse devices connected\n");
662
        return;
663
    }
664

    
665
    term_printf("Mouse devices available:\n");
666
    cursor = qemu_put_mouse_event_head;
667
    while (cursor != NULL) {
668
        term_printf("%c Mouse #%d: %s\n",
669
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
670
                    index, cursor->qemu_put_mouse_event_name);
671
        index++;
672
        cursor = cursor->next;
673
    }
674
}
675

    
676
void do_mouse_set(int index)
677
{
678
    QEMUPutMouseEntry *cursor;
679
    int i = 0;
680

    
681
    if (!qemu_put_mouse_event_head) {
682
        term_printf("No mouse devices connected\n");
683
        return;
684
    }
685

    
686
    cursor = qemu_put_mouse_event_head;
687
    while (cursor != NULL && index != i) {
688
        i++;
689
        cursor = cursor->next;
690
    }
691

    
692
    if (cursor != NULL)
693
        qemu_put_mouse_event_current = cursor;
694
    else
695
        term_printf("Mouse at given index not found\n");
696
}
697

    
698
/* compute with 96 bit intermediate result: (a*b)/c */
699
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
700
{
701
    union {
702
        uint64_t ll;
703
        struct {
704
#ifdef WORDS_BIGENDIAN
705
            uint32_t high, low;
706
#else
707
            uint32_t low, high;
708
#endif
709
        } l;
710
    } u, res;
711
    uint64_t rl, rh;
712

    
713
    u.ll = a;
714
    rl = (uint64_t)u.l.low * (uint64_t)b;
715
    rh = (uint64_t)u.l.high * (uint64_t)b;
716
    rh += (rl >> 32);
717
    res.l.high = rh / c;
718
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
719
    return res.ll;
720
}
721

    
722
/***********************************************************/
723
/* real time host monotonic timer */
724

    
725
#define QEMU_TIMER_BASE 1000000000LL
726

    
727
#ifdef WIN32
728

    
729
static int64_t clock_freq;
730

    
731
static void init_get_clock(void)
732
{
733
    LARGE_INTEGER freq;
734
    int ret;
735
    ret = QueryPerformanceFrequency(&freq);
736
    if (ret == 0) {
737
        fprintf(stderr, "Could not calibrate ticks\n");
738
        exit(1);
739
    }
740
    clock_freq = freq.QuadPart;
741
}
742

    
743
static int64_t get_clock(void)
744
{
745
    LARGE_INTEGER ti;
746
    QueryPerformanceCounter(&ti);
747
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
748
}
749

    
750
#else
751

    
752
static int use_rt_clock;
753

    
754
static void init_get_clock(void)
755
{
756
    use_rt_clock = 0;
757
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
758
    {
759
        struct timespec ts;
760
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
761
            use_rt_clock = 1;
762
        }
763
    }
764
#endif
765
}
766

    
767
static int64_t get_clock(void)
768
{
769
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
770
    if (use_rt_clock) {
771
        struct timespec ts;
772
        clock_gettime(CLOCK_MONOTONIC, &ts);
773
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
774
    } else
775
#endif
776
    {
777
        /* XXX: using gettimeofday leads to problems if the date
778
           changes, so it should be avoided. */
779
        struct timeval tv;
780
        gettimeofday(&tv, NULL);
781
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
782
    }
783
}
784
#endif
785

    
786
/* Return the virtual CPU time, based on the instruction counter.  */
787
static int64_t cpu_get_icount(void)
788
{
789
    int64_t icount;
790
    CPUState *env = cpu_single_env;;
791
    icount = qemu_icount;
792
    if (env) {
793
        if (!can_do_io(env))
794
            fprintf(stderr, "Bad clock read\n");
795
        icount -= (env->icount_decr.u16.low + env->icount_extra);
796
    }
797
    return qemu_icount_bias + (icount << icount_time_shift);
798
}
799

    
800
/***********************************************************/
801
/* guest cycle counter */
802

    
803
static int64_t cpu_ticks_prev;
804
static int64_t cpu_ticks_offset;
805
static int64_t cpu_clock_offset;
806
static int cpu_ticks_enabled;
807

    
808
/* return the host CPU cycle counter and handle stop/restart */
809
int64_t cpu_get_ticks(void)
810
{
811
    if (use_icount) {
812
        return cpu_get_icount();
813
    }
814
    if (!cpu_ticks_enabled) {
815
        return cpu_ticks_offset;
816
    } else {
817
        int64_t ticks;
818
        ticks = cpu_get_real_ticks();
819
        if (cpu_ticks_prev > ticks) {
820
            /* Note: non increasing ticks may happen if the host uses
821
               software suspend */
822
            cpu_ticks_offset += cpu_ticks_prev - ticks;
823
        }
824
        cpu_ticks_prev = ticks;
825
        return ticks + cpu_ticks_offset;
826
    }
827
}
828

    
829
/* return the host CPU monotonic timer and handle stop/restart */
830
static int64_t cpu_get_clock(void)
831
{
832
    int64_t ti;
833
    if (!cpu_ticks_enabled) {
834
        return cpu_clock_offset;
835
    } else {
836
        ti = get_clock();
837
        return ti + cpu_clock_offset;
838
    }
839
}
840

    
841
/* enable cpu_get_ticks() */
842
void cpu_enable_ticks(void)
843
{
844
    if (!cpu_ticks_enabled) {
845
        cpu_ticks_offset -= cpu_get_real_ticks();
846
        cpu_clock_offset -= get_clock();
847
        cpu_ticks_enabled = 1;
848
    }
849
}
850

    
851
/* disable cpu_get_ticks() : the clock is stopped. You must not call
852
   cpu_get_ticks() after that.  */
853
void cpu_disable_ticks(void)
854
{
855
    if (cpu_ticks_enabled) {
856
        cpu_ticks_offset = cpu_get_ticks();
857
        cpu_clock_offset = cpu_get_clock();
858
        cpu_ticks_enabled = 0;
859
    }
860
}
861

    
862
/***********************************************************/
863
/* timers */
864

    
865
#define QEMU_TIMER_REALTIME 0
866
#define QEMU_TIMER_VIRTUAL  1
867

    
868
struct QEMUClock {
869
    int type;
870
    /* XXX: add frequency */
871
};
872

    
873
struct QEMUTimer {
874
    QEMUClock *clock;
875
    int64_t expire_time;
876
    QEMUTimerCB *cb;
877
    void *opaque;
878
    struct QEMUTimer *next;
879
};
880

    
881
struct qemu_alarm_timer {
882
    char const *name;
883
    unsigned int flags;
884

    
885
    int (*start)(struct qemu_alarm_timer *t);
886
    void (*stop)(struct qemu_alarm_timer *t);
887
    void (*rearm)(struct qemu_alarm_timer *t);
888
    void *priv;
889
};
890

    
891
#define ALARM_FLAG_DYNTICKS  0x1
892
#define ALARM_FLAG_EXPIRED   0x2
893

    
894
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
895
{
896
    return t->flags & ALARM_FLAG_DYNTICKS;
897
}
898

    
899
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
900
{
901
    if (!alarm_has_dynticks(t))
902
        return;
903

    
904
    t->rearm(t);
905
}
906

    
907
/* TODO: MIN_TIMER_REARM_US should be optimized */
908
#define MIN_TIMER_REARM_US 250
909

    
910
static struct qemu_alarm_timer *alarm_timer;
911
#ifndef _WIN32
912
static int alarm_timer_rfd, alarm_timer_wfd;
913
#endif
914

    
915
#ifdef _WIN32
916

    
917
struct qemu_alarm_win32 {
918
    MMRESULT timerId;
919
    HANDLE host_alarm;
920
    unsigned int period;
921
} alarm_win32_data = {0, NULL, -1};
922

    
923
static int win32_start_timer(struct qemu_alarm_timer *t);
924
static void win32_stop_timer(struct qemu_alarm_timer *t);
925
static void win32_rearm_timer(struct qemu_alarm_timer *t);
926

    
927
#else
928

    
929
static int unix_start_timer(struct qemu_alarm_timer *t);
930
static void unix_stop_timer(struct qemu_alarm_timer *t);
931

    
932
#ifdef __linux__
933

    
934
static int dynticks_start_timer(struct qemu_alarm_timer *t);
935
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
936
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
937

    
938
static int hpet_start_timer(struct qemu_alarm_timer *t);
939
static void hpet_stop_timer(struct qemu_alarm_timer *t);
940

    
941
static int rtc_start_timer(struct qemu_alarm_timer *t);
942
static void rtc_stop_timer(struct qemu_alarm_timer *t);
943

    
944
#endif /* __linux__ */
945

    
946
#endif /* _WIN32 */
947

    
948
/* Correlation between real and virtual time is always going to be
949
   fairly approximate, so ignore small variation.
950
   When the guest is idle real and virtual time will be aligned in
951
   the IO wait loop.  */
952
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
953

    
954
static void icount_adjust(void)
955
{
956
    int64_t cur_time;
957
    int64_t cur_icount;
958
    int64_t delta;
959
    static int64_t last_delta;
960
    /* If the VM is not running, then do nothing.  */
961
    if (!vm_running)
962
        return;
963

    
964
    cur_time = cpu_get_clock();
965
    cur_icount = qemu_get_clock(vm_clock);
966
    delta = cur_icount - cur_time;
967
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
968
    if (delta > 0
969
        && last_delta + ICOUNT_WOBBLE < delta * 2
970
        && icount_time_shift > 0) {
971
        /* The guest is getting too far ahead.  Slow time down.  */
972
        icount_time_shift--;
973
    }
974
    if (delta < 0
975
        && last_delta - ICOUNT_WOBBLE > delta * 2
976
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
977
        /* The guest is getting too far behind.  Speed time up.  */
978
        icount_time_shift++;
979
    }
980
    last_delta = delta;
981
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
982
}
983

    
984
static void icount_adjust_rt(void * opaque)
985
{
986
    qemu_mod_timer(icount_rt_timer,
987
                   qemu_get_clock(rt_clock) + 1000);
988
    icount_adjust();
989
}
990

    
991
static void icount_adjust_vm(void * opaque)
992
{
993
    qemu_mod_timer(icount_vm_timer,
994
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
995
    icount_adjust();
996
}
997

    
998
static void init_icount_adjust(void)
999
{
1000
    /* Have both realtime and virtual time triggers for speed adjustment.
1001
       The realtime trigger catches emulated time passing too slowly,
1002
       the virtual time trigger catches emulated time passing too fast.
1003
       Realtime triggers occur even when idle, so use them less frequently
1004
       than VM triggers.  */
1005
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1006
    qemu_mod_timer(icount_rt_timer,
1007
                   qemu_get_clock(rt_clock) + 1000);
1008
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1009
    qemu_mod_timer(icount_vm_timer,
1010
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1011
}
1012

    
1013
static struct qemu_alarm_timer alarm_timers[] = {
1014
#ifndef _WIN32
1015
#ifdef __linux__
1016
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1017
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
1018
    /* HPET - if available - is preferred */
1019
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1020
    /* ...otherwise try RTC */
1021
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1022
#endif
1023
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1024
#else
1025
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1026
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1027
    {"win32", 0, win32_start_timer,
1028
     win32_stop_timer, NULL, &alarm_win32_data},
1029
#endif
1030
    {NULL, }
1031
};
1032

    
1033
static void show_available_alarms(void)
1034
{
1035
    int i;
1036

    
1037
    printf("Available alarm timers, in order of precedence:\n");
1038
    for (i = 0; alarm_timers[i].name; i++)
1039
        printf("%s\n", alarm_timers[i].name);
1040
}
1041

    
1042
static void configure_alarms(char const *opt)
1043
{
1044
    int i;
1045
    int cur = 0;
1046
    int count = ARRAY_SIZE(alarm_timers) - 1;
1047
    char *arg;
1048
    char *name;
1049
    struct qemu_alarm_timer tmp;
1050

    
1051
    if (!strcmp(opt, "?")) {
1052
        show_available_alarms();
1053
        exit(0);
1054
    }
1055

    
1056
    arg = strdup(opt);
1057

    
1058
    /* Reorder the array */
1059
    name = strtok(arg, ",");
1060
    while (name) {
1061
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1062
            if (!strcmp(alarm_timers[i].name, name))
1063
                break;
1064
        }
1065

    
1066
        if (i == count) {
1067
            fprintf(stderr, "Unknown clock %s\n", name);
1068
            goto next;
1069
        }
1070

    
1071
        if (i < cur)
1072
            /* Ignore */
1073
            goto next;
1074

    
1075
        /* Swap */
1076
        tmp = alarm_timers[i];
1077
        alarm_timers[i] = alarm_timers[cur];
1078
        alarm_timers[cur] = tmp;
1079

    
1080
        cur++;
1081
next:
1082
        name = strtok(NULL, ",");
1083
    }
1084

    
1085
    free(arg);
1086

    
1087
    if (cur) {
1088
        /* Disable remaining timers */
1089
        for (i = cur; i < count; i++)
1090
            alarm_timers[i].name = NULL;
1091
    } else {
1092
        show_available_alarms();
1093
        exit(1);
1094
    }
1095
}
1096

    
1097
QEMUClock *rt_clock;
1098
QEMUClock *vm_clock;
1099

    
1100
static QEMUTimer *active_timers[2];
1101

    
1102
static QEMUClock *qemu_new_clock(int type)
1103
{
1104
    QEMUClock *clock;
1105
    clock = qemu_mallocz(sizeof(QEMUClock));
1106
    if (!clock)
1107
        return NULL;
1108
    clock->type = type;
1109
    return clock;
1110
}
1111

    
1112
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1113
{
1114
    QEMUTimer *ts;
1115

    
1116
    ts = qemu_mallocz(sizeof(QEMUTimer));
1117
    ts->clock = clock;
1118
    ts->cb = cb;
1119
    ts->opaque = opaque;
1120
    return ts;
1121
}
1122

    
1123
void qemu_free_timer(QEMUTimer *ts)
1124
{
1125
    qemu_free(ts);
1126
}
1127

    
1128
/* stop a timer, but do not dealloc it */
1129
void qemu_del_timer(QEMUTimer *ts)
1130
{
1131
    QEMUTimer **pt, *t;
1132

    
1133
    /* NOTE: this code must be signal safe because
1134
       qemu_timer_expired() can be called from a signal. */
1135
    pt = &active_timers[ts->clock->type];
1136
    for(;;) {
1137
        t = *pt;
1138
        if (!t)
1139
            break;
1140
        if (t == ts) {
1141
            *pt = t->next;
1142
            break;
1143
        }
1144
        pt = &t->next;
1145
    }
1146
}
1147

    
1148
/* modify the current timer so that it will be fired when current_time
1149
   >= expire_time. The corresponding callback will be called. */
1150
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1151
{
1152
    QEMUTimer **pt, *t;
1153

    
1154
    qemu_del_timer(ts);
1155

    
1156
    /* add the timer in the sorted list */
1157
    /* NOTE: this code must be signal safe because
1158
       qemu_timer_expired() can be called from a signal. */
1159
    pt = &active_timers[ts->clock->type];
1160
    for(;;) {
1161
        t = *pt;
1162
        if (!t)
1163
            break;
1164
        if (t->expire_time > expire_time)
1165
            break;
1166
        pt = &t->next;
1167
    }
1168
    ts->expire_time = expire_time;
1169
    ts->next = *pt;
1170
    *pt = ts;
1171

    
1172
    /* Rearm if necessary  */
1173
    if (pt == &active_timers[ts->clock->type]) {
1174
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1175
            qemu_rearm_alarm_timer(alarm_timer);
1176
        }
1177
        /* Interrupt execution to force deadline recalculation.  */
1178
        if (use_icount && cpu_single_env) {
1179
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1180
        }
1181
    }
1182
}
1183

    
1184
int qemu_timer_pending(QEMUTimer *ts)
1185
{
1186
    QEMUTimer *t;
1187
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1188
        if (t == ts)
1189
            return 1;
1190
    }
1191
    return 0;
1192
}
1193

    
1194
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1195
{
1196
    if (!timer_head)
1197
        return 0;
1198
    return (timer_head->expire_time <= current_time);
1199
}
1200

    
1201
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1202
{
1203
    QEMUTimer *ts;
1204

    
1205
    for(;;) {
1206
        ts = *ptimer_head;
1207
        if (!ts || ts->expire_time > current_time)
1208
            break;
1209
        /* remove timer from the list before calling the callback */
1210
        *ptimer_head = ts->next;
1211
        ts->next = NULL;
1212

    
1213
        /* run the callback (the timer list can be modified) */
1214
        ts->cb(ts->opaque);
1215
    }
1216
}
1217

    
1218
int64_t qemu_get_clock(QEMUClock *clock)
1219
{
1220
    switch(clock->type) {
1221
    case QEMU_TIMER_REALTIME:
1222
        return get_clock() / 1000000;
1223
    default:
1224
    case QEMU_TIMER_VIRTUAL:
1225
        if (use_icount) {
1226
            return cpu_get_icount();
1227
        } else {
1228
            return cpu_get_clock();
1229
        }
1230
    }
1231
}
1232

    
1233
static void init_timers(void)
1234
{
1235
    init_get_clock();
1236
    ticks_per_sec = QEMU_TIMER_BASE;
1237
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1238
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1239
}
1240

    
1241
/* save a timer */
1242
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1243
{
1244
    uint64_t expire_time;
1245

    
1246
    if (qemu_timer_pending(ts)) {
1247
        expire_time = ts->expire_time;
1248
    } else {
1249
        expire_time = -1;
1250
    }
1251
    qemu_put_be64(f, expire_time);
1252
}
1253

    
1254
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1255
{
1256
    uint64_t expire_time;
1257

    
1258
    expire_time = qemu_get_be64(f);
1259
    if (expire_time != -1) {
1260
        qemu_mod_timer(ts, expire_time);
1261
    } else {
1262
        qemu_del_timer(ts);
1263
    }
1264
}
1265

    
1266
static void timer_save(QEMUFile *f, void *opaque)
1267
{
1268
    if (cpu_ticks_enabled) {
1269
        hw_error("cannot save state if virtual timers are running");
1270
    }
1271
    qemu_put_be64(f, cpu_ticks_offset);
1272
    qemu_put_be64(f, ticks_per_sec);
1273
    qemu_put_be64(f, cpu_clock_offset);
1274
}
1275

    
1276
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1277
{
1278
    if (version_id != 1 && version_id != 2)
1279
        return -EINVAL;
1280
    if (cpu_ticks_enabled) {
1281
        return -EINVAL;
1282
    }
1283
    cpu_ticks_offset=qemu_get_be64(f);
1284
    ticks_per_sec=qemu_get_be64(f);
1285
    if (version_id == 2) {
1286
        cpu_clock_offset=qemu_get_be64(f);
1287
    }
1288
    return 0;
1289
}
1290

    
1291
#ifdef _WIN32
1292
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1293
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1294
#else
1295
static void host_alarm_handler(int host_signum)
1296
#endif
1297
{
1298
#if 0
1299
#define DISP_FREQ 1000
1300
    {
1301
        static int64_t delta_min = INT64_MAX;
1302
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1303
        static int count;
1304
        ti = qemu_get_clock(vm_clock);
1305
        if (last_clock != 0) {
1306
            delta = ti - last_clock;
1307
            if (delta < delta_min)
1308
                delta_min = delta;
1309
            if (delta > delta_max)
1310
                delta_max = delta;
1311
            delta_cum += delta;
1312
            if (++count == DISP_FREQ) {
1313
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1314
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1315
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1316
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1317
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1318
                count = 0;
1319
                delta_min = INT64_MAX;
1320
                delta_max = 0;
1321
                delta_cum = 0;
1322
            }
1323
        }
1324
        last_clock = ti;
1325
    }
1326
#endif
1327
    if (alarm_has_dynticks(alarm_timer) ||
1328
        (!use_icount &&
1329
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1330
                               qemu_get_clock(vm_clock))) ||
1331
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1332
                           qemu_get_clock(rt_clock))) {
1333
        CPUState *env = next_cpu;
1334

    
1335
#ifdef _WIN32
1336
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1337
        SetEvent(data->host_alarm);
1338
#else
1339
        static const char byte = 0;
1340
        write(alarm_timer_wfd, &byte, sizeof(byte));
1341
#endif
1342
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1343

    
1344
        if (env) {
1345
            /* stop the currently executing cpu because a timer occured */
1346
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1347
#ifdef USE_KQEMU
1348
            if (env->kqemu_enabled) {
1349
                kqemu_cpu_interrupt(env);
1350
            }
1351
#endif
1352
        }
1353
        event_pending = 1;
1354
    }
1355
}
1356

    
1357
static int64_t qemu_next_deadline(void)
1358
{
1359
    int64_t delta;
1360

    
1361
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1362
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1363
                     qemu_get_clock(vm_clock);
1364
    } else {
1365
        /* To avoid problems with overflow limit this to 2^32.  */
1366
        delta = INT32_MAX;
1367
    }
1368

    
1369
    if (delta < 0)
1370
        delta = 0;
1371

    
1372
    return delta;
1373
}
1374

    
1375
#if defined(__linux__) || defined(_WIN32)
1376
static uint64_t qemu_next_deadline_dyntick(void)
1377
{
1378
    int64_t delta;
1379
    int64_t rtdelta;
1380

    
1381
    if (use_icount)
1382
        delta = INT32_MAX;
1383
    else
1384
        delta = (qemu_next_deadline() + 999) / 1000;
1385

    
1386
    if (active_timers[QEMU_TIMER_REALTIME]) {
1387
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1388
                 qemu_get_clock(rt_clock))*1000;
1389
        if (rtdelta < delta)
1390
            delta = rtdelta;
1391
    }
1392

    
1393
    if (delta < MIN_TIMER_REARM_US)
1394
        delta = MIN_TIMER_REARM_US;
1395

    
1396
    return delta;
1397
}
1398
#endif
1399

    
1400
#ifndef _WIN32
1401

    
1402
/* Sets a specific flag */
1403
static int fcntl_setfl(int fd, int flag)
1404
{
1405
    int flags;
1406

    
1407
    flags = fcntl(fd, F_GETFL);
1408
    if (flags == -1)
1409
        return -errno;
1410

    
1411
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1412
        return -errno;
1413

    
1414
    return 0;
1415
}
1416

    
1417
#if defined(__linux__)
1418

    
1419
#define RTC_FREQ 1024
1420

    
1421
static void enable_sigio_timer(int fd)
1422
{
1423
    struct sigaction act;
1424

    
1425
    /* timer signal */
1426
    sigfillset(&act.sa_mask);
1427
    act.sa_flags = 0;
1428
    act.sa_handler = host_alarm_handler;
1429

    
1430
    sigaction(SIGIO, &act, NULL);
1431
    fcntl_setfl(fd, O_ASYNC);
1432
    fcntl(fd, F_SETOWN, getpid());
1433
}
1434

    
1435
static int hpet_start_timer(struct qemu_alarm_timer *t)
1436
{
1437
    struct hpet_info info;
1438
    int r, fd;
1439

    
1440
    fd = open("/dev/hpet", O_RDONLY);
1441
    if (fd < 0)
1442
        return -1;
1443

    
1444
    /* Set frequency */
1445
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1446
    if (r < 0) {
1447
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1448
                "error, but for better emulation accuracy type:\n"
1449
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1450
        goto fail;
1451
    }
1452

    
1453
    /* Check capabilities */
1454
    r = ioctl(fd, HPET_INFO, &info);
1455
    if (r < 0)
1456
        goto fail;
1457

    
1458
    /* Enable periodic mode */
1459
    r = ioctl(fd, HPET_EPI, 0);
1460
    if (info.hi_flags && (r < 0))
1461
        goto fail;
1462

    
1463
    /* Enable interrupt */
1464
    r = ioctl(fd, HPET_IE_ON, 0);
1465
    if (r < 0)
1466
        goto fail;
1467

    
1468
    enable_sigio_timer(fd);
1469
    t->priv = (void *)(long)fd;
1470

    
1471
    return 0;
1472
fail:
1473
    close(fd);
1474
    return -1;
1475
}
1476

    
1477
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1478
{
1479
    int fd = (long)t->priv;
1480

    
1481
    close(fd);
1482
}
1483

    
1484
static int rtc_start_timer(struct qemu_alarm_timer *t)
1485
{
1486
    int rtc_fd;
1487
    unsigned long current_rtc_freq = 0;
1488

    
1489
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1490
    if (rtc_fd < 0)
1491
        return -1;
1492
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1493
    if (current_rtc_freq != RTC_FREQ &&
1494
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1495
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1496
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1497
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1498
        goto fail;
1499
    }
1500
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1501
    fail:
1502
        close(rtc_fd);
1503
        return -1;
1504
    }
1505

    
1506
    enable_sigio_timer(rtc_fd);
1507

    
1508
    t->priv = (void *)(long)rtc_fd;
1509

    
1510
    return 0;
1511
}
1512

    
1513
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1514
{
1515
    int rtc_fd = (long)t->priv;
1516

    
1517
    close(rtc_fd);
1518
}
1519

    
1520
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1521
{
1522
    struct sigevent ev;
1523
    timer_t host_timer;
1524
    struct sigaction act;
1525

    
1526
    sigfillset(&act.sa_mask);
1527
    act.sa_flags = 0;
1528
    act.sa_handler = host_alarm_handler;
1529

    
1530
    sigaction(SIGALRM, &act, NULL);
1531

    
1532
    ev.sigev_value.sival_int = 0;
1533
    ev.sigev_notify = SIGEV_SIGNAL;
1534
    ev.sigev_signo = SIGALRM;
1535

    
1536
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1537
        perror("timer_create");
1538

    
1539
        /* disable dynticks */
1540
        fprintf(stderr, "Dynamic Ticks disabled\n");
1541

    
1542
        return -1;
1543
    }
1544

    
1545
    t->priv = (void *)(long)host_timer;
1546

    
1547
    return 0;
1548
}
1549

    
1550
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1551
{
1552
    timer_t host_timer = (timer_t)(long)t->priv;
1553

    
1554
    timer_delete(host_timer);
1555
}
1556

    
1557
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1558
{
1559
    timer_t host_timer = (timer_t)(long)t->priv;
1560
    struct itimerspec timeout;
1561
    int64_t nearest_delta_us = INT64_MAX;
1562
    int64_t current_us;
1563

    
1564
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1565
                !active_timers[QEMU_TIMER_VIRTUAL])
1566
        return;
1567

    
1568
    nearest_delta_us = qemu_next_deadline_dyntick();
1569

    
1570
    /* check whether a timer is already running */
1571
    if (timer_gettime(host_timer, &timeout)) {
1572
        perror("gettime");
1573
        fprintf(stderr, "Internal timer error: aborting\n");
1574
        exit(1);
1575
    }
1576
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1577
    if (current_us && current_us <= nearest_delta_us)
1578
        return;
1579

    
1580
    timeout.it_interval.tv_sec = 0;
1581
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1582
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1583
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1584
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1585
        perror("settime");
1586
        fprintf(stderr, "Internal timer error: aborting\n");
1587
        exit(1);
1588
    }
1589
}
1590

    
1591
#endif /* defined(__linux__) */
1592

    
1593
static int unix_start_timer(struct qemu_alarm_timer *t)
1594
{
1595
    struct sigaction act;
1596
    struct itimerval itv;
1597
    int err;
1598

    
1599
    /* timer signal */
1600
    sigfillset(&act.sa_mask);
1601
    act.sa_flags = 0;
1602
    act.sa_handler = host_alarm_handler;
1603

    
1604
    sigaction(SIGALRM, &act, NULL);
1605

    
1606
    itv.it_interval.tv_sec = 0;
1607
    /* for i386 kernel 2.6 to get 1 ms */
1608
    itv.it_interval.tv_usec = 999;
1609
    itv.it_value.tv_sec = 0;
1610
    itv.it_value.tv_usec = 10 * 1000;
1611

    
1612
    err = setitimer(ITIMER_REAL, &itv, NULL);
1613
    if (err)
1614
        return -1;
1615

    
1616
    return 0;
1617
}
1618

    
1619
static void unix_stop_timer(struct qemu_alarm_timer *t)
1620
{
1621
    struct itimerval itv;
1622

    
1623
    memset(&itv, 0, sizeof(itv));
1624
    setitimer(ITIMER_REAL, &itv, NULL);
1625
}
1626

    
1627
#endif /* !defined(_WIN32) */
1628

    
1629
static void try_to_rearm_timer(void *opaque)
1630
{
1631
    struct qemu_alarm_timer *t = opaque;
1632
#ifndef _WIN32
1633
    ssize_t len;
1634

    
1635
    /* Drain the notify pipe */
1636
    do {
1637
        char buffer[512];
1638
        len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1639
    } while ((len == -1 && errno == EINTR) || len > 0);
1640
#endif
1641

    
1642
    if (t->flags & ALARM_FLAG_EXPIRED) {
1643
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1644
        qemu_rearm_alarm_timer(alarm_timer);
1645
    }
1646
}
1647

    
1648
#ifdef _WIN32
1649

    
1650
static int win32_start_timer(struct qemu_alarm_timer *t)
1651
{
1652
    TIMECAPS tc;
1653
    struct qemu_alarm_win32 *data = t->priv;
1654
    UINT flags;
1655

    
1656
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1657
    if (!data->host_alarm) {
1658
        perror("Failed CreateEvent");
1659
        return -1;
1660
    }
1661

    
1662
    memset(&tc, 0, sizeof(tc));
1663
    timeGetDevCaps(&tc, sizeof(tc));
1664

    
1665
    if (data->period < tc.wPeriodMin)
1666
        data->period = tc.wPeriodMin;
1667

    
1668
    timeBeginPeriod(data->period);
1669

    
1670
    flags = TIME_CALLBACK_FUNCTION;
1671
    if (alarm_has_dynticks(t))
1672
        flags |= TIME_ONESHOT;
1673
    else
1674
        flags |= TIME_PERIODIC;
1675

    
1676
    data->timerId = timeSetEvent(1,         // interval (ms)
1677
                        data->period,       // resolution
1678
                        host_alarm_handler, // function
1679
                        (DWORD)t,           // parameter
1680
                        flags);
1681

    
1682
    if (!data->timerId) {
1683
        perror("Failed to initialize win32 alarm timer");
1684

    
1685
        timeEndPeriod(data->period);
1686
        CloseHandle(data->host_alarm);
1687
        return -1;
1688
    }
1689

    
1690
    qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1691

    
1692
    return 0;
1693
}
1694

    
1695
static void win32_stop_timer(struct qemu_alarm_timer *t)
1696
{
1697
    struct qemu_alarm_win32 *data = t->priv;
1698

    
1699
    timeKillEvent(data->timerId);
1700
    timeEndPeriod(data->period);
1701

    
1702
    CloseHandle(data->host_alarm);
1703
}
1704

    
1705
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1706
{
1707
    struct qemu_alarm_win32 *data = t->priv;
1708
    uint64_t nearest_delta_us;
1709

    
1710
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1711
                !active_timers[QEMU_TIMER_VIRTUAL])
1712
        return;
1713

    
1714
    nearest_delta_us = qemu_next_deadline_dyntick();
1715
    nearest_delta_us /= 1000;
1716

    
1717
    timeKillEvent(data->timerId);
1718

    
1719
    data->timerId = timeSetEvent(1,
1720
                        data->period,
1721
                        host_alarm_handler,
1722
                        (DWORD)t,
1723
                        TIME_ONESHOT | TIME_PERIODIC);
1724

    
1725
    if (!data->timerId) {
1726
        perror("Failed to re-arm win32 alarm timer");
1727

    
1728
        timeEndPeriod(data->period);
1729
        CloseHandle(data->host_alarm);
1730
        exit(1);
1731
    }
1732
}
1733

    
1734
#endif /* _WIN32 */
1735

    
1736
static int init_timer_alarm(void)
1737
{
1738
    struct qemu_alarm_timer *t = NULL;
1739
    int i, err = -1;
1740

    
1741
#ifndef _WIN32
1742
    int fds[2];
1743

    
1744
    err = pipe(fds);
1745
    if (err == -1)
1746
        return -errno;
1747

    
1748
    err = fcntl_setfl(fds[0], O_NONBLOCK);
1749
    if (err < 0)
1750
        goto fail;
1751

    
1752
    err = fcntl_setfl(fds[1], O_NONBLOCK);
1753
    if (err < 0)
1754
        goto fail;
1755

    
1756
    alarm_timer_rfd = fds[0];
1757
    alarm_timer_wfd = fds[1];
1758
#endif
1759

    
1760
    for (i = 0; alarm_timers[i].name; i++) {
1761
        t = &alarm_timers[i];
1762

    
1763
        err = t->start(t);
1764
        if (!err)
1765
            break;
1766
    }
1767

    
1768
    if (err) {
1769
        err = -ENOENT;
1770
        goto fail;
1771
    }
1772

    
1773
#ifndef _WIN32
1774
    qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1775
                         try_to_rearm_timer, NULL, t);
1776
#endif
1777

    
1778
    alarm_timer = t;
1779

    
1780
    return 0;
1781

    
1782
fail:
1783
#ifndef _WIN32
1784
    close(fds[0]);
1785
    close(fds[1]);
1786
#endif
1787
    return err;
1788
}
1789

    
1790
static void quit_timers(void)
1791
{
1792
    alarm_timer->stop(alarm_timer);
1793
    alarm_timer = NULL;
1794
}
1795

    
1796
/***********************************************************/
1797
/* host time/date access */
1798
void qemu_get_timedate(struct tm *tm, int offset)
1799
{
1800
    time_t ti;
1801
    struct tm *ret;
1802

    
1803
    time(&ti);
1804
    ti += offset;
1805
    if (rtc_date_offset == -1) {
1806
        if (rtc_utc)
1807
            ret = gmtime(&ti);
1808
        else
1809
            ret = localtime(&ti);
1810
    } else {
1811
        ti -= rtc_date_offset;
1812
        ret = gmtime(&ti);
1813
    }
1814

    
1815
    memcpy(tm, ret, sizeof(struct tm));
1816
}
1817

    
1818
int qemu_timedate_diff(struct tm *tm)
1819
{
1820
    time_t seconds;
1821

    
1822
    if (rtc_date_offset == -1)
1823
        if (rtc_utc)
1824
            seconds = mktimegm(tm);
1825
        else
1826
            seconds = mktime(tm);
1827
    else
1828
        seconds = mktimegm(tm) + rtc_date_offset;
1829

    
1830
    return seconds - time(NULL);
1831
}
1832

    
1833
#ifdef _WIN32
1834
static void socket_cleanup(void)
1835
{
1836
    WSACleanup();
1837
}
1838

    
1839
static int socket_init(void)
1840
{
1841
    WSADATA Data;
1842
    int ret, err;
1843

    
1844
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1845
    if (ret != 0) {
1846
        err = WSAGetLastError();
1847
        fprintf(stderr, "WSAStartup: %d\n", err);
1848
        return -1;
1849
    }
1850
    atexit(socket_cleanup);
1851
    return 0;
1852
}
1853
#endif
1854

    
1855
const char *get_opt_name(char *buf, int buf_size, const char *p)
1856
{
1857
    char *q;
1858

    
1859
    q = buf;
1860
    while (*p != '\0' && *p != '=') {
1861
        if (q && (q - buf) < buf_size - 1)
1862
            *q++ = *p;
1863
        p++;
1864
    }
1865
    if (q)
1866
        *q = '\0';
1867

    
1868
    return p;
1869
}
1870

    
1871
const char *get_opt_value(char *buf, int buf_size, const char *p)
1872
{
1873
    char *q;
1874

    
1875
    q = buf;
1876
    while (*p != '\0') {
1877
        if (*p == ',') {
1878
            if (*(p + 1) != ',')
1879
                break;
1880
            p++;
1881
        }
1882
        if (q && (q - buf) < buf_size - 1)
1883
            *q++ = *p;
1884
        p++;
1885
    }
1886
    if (q)
1887
        *q = '\0';
1888

    
1889
    return p;
1890
}
1891

    
1892
int get_param_value(char *buf, int buf_size,
1893
                    const char *tag, const char *str)
1894
{
1895
    const char *p;
1896
    char option[128];
1897

    
1898
    p = str;
1899
    for(;;) {
1900
        p = get_opt_name(option, sizeof(option), p);
1901
        if (*p != '=')
1902
            break;
1903
        p++;
1904
        if (!strcmp(tag, option)) {
1905
            (void)get_opt_value(buf, buf_size, p);
1906
            return strlen(buf);
1907
        } else {
1908
            p = get_opt_value(NULL, 0, p);
1909
        }
1910
        if (*p != ',')
1911
            break;
1912
        p++;
1913
    }
1914
    return 0;
1915
}
1916

    
1917
int check_params(char *buf, int buf_size,
1918
                 const char * const *params, const char *str)
1919
{
1920
    const char *p;
1921
    int i;
1922

    
1923
    p = str;
1924
    for(;;) {
1925
        p = get_opt_name(buf, buf_size, p);
1926
        if (*p != '=')
1927
            return -1;
1928
        p++;
1929
        for(i = 0; params[i] != NULL; i++)
1930
            if (!strcmp(params[i], buf))
1931
                break;
1932
        if (params[i] == NULL)
1933
            return -1;
1934
        p = get_opt_value(NULL, 0, p);
1935
        if (*p != ',')
1936
            break;
1937
        p++;
1938
    }
1939
    return 0;
1940
}
1941

    
1942
/***********************************************************/
1943
/* Bluetooth support */
1944
static int nb_hcis;
1945
static int cur_hci;
1946
static struct HCIInfo *hci_table[MAX_NICS];
1947

    
1948
static struct bt_vlan_s {
1949
    struct bt_scatternet_s net;
1950
    int id;
1951
    struct bt_vlan_s *next;
1952
} *first_bt_vlan;
1953

    
1954
/* find or alloc a new bluetooth "VLAN" */
1955
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1956
{
1957
    struct bt_vlan_s **pvlan, *vlan;
1958
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1959
        if (vlan->id == id)
1960
            return &vlan->net;
1961
    }
1962
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1963
    vlan->id = id;
1964
    pvlan = &first_bt_vlan;
1965
    while (*pvlan != NULL)
1966
        pvlan = &(*pvlan)->next;
1967
    *pvlan = vlan;
1968
    return &vlan->net;
1969
}
1970

    
1971
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1972
{
1973
}
1974

    
1975
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1976
{
1977
    return -ENOTSUP;
1978
}
1979

    
1980
static struct HCIInfo null_hci = {
1981
    .cmd_send = null_hci_send,
1982
    .sco_send = null_hci_send,
1983
    .acl_send = null_hci_send,
1984
    .bdaddr_set = null_hci_addr_set,
1985
};
1986

    
1987
struct HCIInfo *qemu_next_hci(void)
1988
{
1989
    if (cur_hci == nb_hcis)
1990
        return &null_hci;
1991

    
1992
    return hci_table[cur_hci++];
1993
}
1994

    
1995
static struct HCIInfo *hci_init(const char *str)
1996
{
1997
    char *endp;
1998
    struct bt_scatternet_s *vlan = 0;
1999

    
2000
    if (!strcmp(str, "null"))
2001
        /* null */
2002
        return &null_hci;
2003
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2004
        /* host[:hciN] */
2005
        return bt_host_hci(str[4] ? str + 5 : "hci0");
2006
    else if (!strncmp(str, "hci", 3)) {
2007
        /* hci[,vlan=n] */
2008
        if (str[3]) {
2009
            if (!strncmp(str + 3, ",vlan=", 6)) {
2010
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2011
                if (*endp)
2012
                    vlan = 0;
2013
            }
2014
        } else
2015
            vlan = qemu_find_bt_vlan(0);
2016
        if (vlan)
2017
           return bt_new_hci(vlan);
2018
    }
2019

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

    
2022
    return 0;
2023
}
2024

    
2025
static int bt_hci_parse(const char *str)
2026
{
2027
    struct HCIInfo *hci;
2028
    bdaddr_t bdaddr;
2029

    
2030
    if (nb_hcis >= MAX_NICS) {
2031
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2032
        return -1;
2033
    }
2034

    
2035
    hci = hci_init(str);
2036
    if (!hci)
2037
        return -1;
2038

    
2039
    bdaddr.b[0] = 0x52;
2040
    bdaddr.b[1] = 0x54;
2041
    bdaddr.b[2] = 0x00;
2042
    bdaddr.b[3] = 0x12;
2043
    bdaddr.b[4] = 0x34;
2044
    bdaddr.b[5] = 0x56 + nb_hcis;
2045
    hci->bdaddr_set(hci, bdaddr.b);
2046

    
2047
    hci_table[nb_hcis++] = hci;
2048

    
2049
    return 0;
2050
}
2051

    
2052
static void bt_vhci_add(int vlan_id)
2053
{
2054
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2055

    
2056
    if (!vlan->slave)
2057
        fprintf(stderr, "qemu: warning: adding a VHCI to "
2058
                        "an empty scatternet %i\n", vlan_id);
2059

    
2060
    bt_vhci_init(bt_new_hci(vlan));
2061
}
2062

    
2063
static struct bt_device_s *bt_device_add(const char *opt)
2064
{
2065
    struct bt_scatternet_s *vlan;
2066
    int vlan_id = 0;
2067
    char *endp = strstr(opt, ",vlan=");
2068
    int len = (endp ? endp - opt : strlen(opt)) + 1;
2069
    char devname[10];
2070

    
2071
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
2072

    
2073
    if (endp) {
2074
        vlan_id = strtol(endp + 6, &endp, 0);
2075
        if (*endp) {
2076
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2077
            return 0;
2078
        }
2079
    }
2080

    
2081
    vlan = qemu_find_bt_vlan(vlan_id);
2082

    
2083
    if (!vlan->slave)
2084
        fprintf(stderr, "qemu: warning: adding a slave device to "
2085
                        "an empty scatternet %i\n", vlan_id);
2086

    
2087
    if (!strcmp(devname, "keyboard"))
2088
        return bt_keyboard_init(vlan);
2089

    
2090
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2091
    return 0;
2092
}
2093

    
2094
static int bt_parse(const char *opt)
2095
{
2096
    const char *endp, *p;
2097
    int vlan;
2098

    
2099
    if (strstart(opt, "hci", &endp)) {
2100
        if (!*endp || *endp == ',') {
2101
            if (*endp)
2102
                if (!strstart(endp, ",vlan=", 0))
2103
                    opt = endp + 1;
2104

    
2105
            return bt_hci_parse(opt);
2106
       }
2107
    } else if (strstart(opt, "vhci", &endp)) {
2108
        if (!*endp || *endp == ',') {
2109
            if (*endp) {
2110
                if (strstart(endp, ",vlan=", &p)) {
2111
                    vlan = strtol(p, (char **) &endp, 0);
2112
                    if (*endp) {
2113
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2114
                        return 1;
2115
                    }
2116
                } else {
2117
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2118
                    return 1;
2119
                }
2120
            } else
2121
                vlan = 0;
2122

    
2123
            bt_vhci_add(vlan);
2124
            return 0;
2125
        }
2126
    } else if (strstart(opt, "device:", &endp))
2127
        return !bt_device_add(endp);
2128

    
2129
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2130
    return 1;
2131
}
2132

    
2133
/***********************************************************/
2134
/* QEMU Block devices */
2135

    
2136
#define HD_ALIAS "index=%d,media=disk"
2137
#ifdef TARGET_PPC
2138
#define CDROM_ALIAS "index=1,media=cdrom"
2139
#else
2140
#define CDROM_ALIAS "index=2,media=cdrom"
2141
#endif
2142
#define FD_ALIAS "index=%d,if=floppy"
2143
#define PFLASH_ALIAS "if=pflash"
2144
#define MTD_ALIAS "if=mtd"
2145
#define SD_ALIAS "index=0,if=sd"
2146

    
2147
static int drive_add(const char *file, const char *fmt, ...)
2148
{
2149
    va_list ap;
2150

    
2151
    if (nb_drives_opt >= MAX_DRIVES) {
2152
        fprintf(stderr, "qemu: too many drives\n");
2153
        exit(1);
2154
    }
2155

    
2156
    drives_opt[nb_drives_opt].file = file;
2157
    va_start(ap, fmt);
2158
    vsnprintf(drives_opt[nb_drives_opt].opt,
2159
              sizeof(drives_opt[0].opt), fmt, ap);
2160
    va_end(ap);
2161

    
2162
    return nb_drives_opt++;
2163
}
2164

    
2165
int drive_get_index(BlockInterfaceType type, int bus, int unit)
2166
{
2167
    int index;
2168

    
2169
    /* seek interface, bus and unit */
2170

    
2171
    for (index = 0; index < nb_drives; index++)
2172
        if (drives_table[index].type == type &&
2173
            drives_table[index].bus == bus &&
2174
            drives_table[index].unit == unit)
2175
        return index;
2176

    
2177
    return -1;
2178
}
2179

    
2180
int drive_get_max_bus(BlockInterfaceType type)
2181
{
2182
    int max_bus;
2183
    int index;
2184

    
2185
    max_bus = -1;
2186
    for (index = 0; index < nb_drives; index++) {
2187
        if(drives_table[index].type == type &&
2188
           drives_table[index].bus > max_bus)
2189
            max_bus = drives_table[index].bus;
2190
    }
2191
    return max_bus;
2192
}
2193

    
2194
const char *drive_get_serial(BlockDriverState *bdrv)
2195
{
2196
    int index;
2197

    
2198
    for (index = 0; index < nb_drives; index++)
2199
        if (drives_table[index].bdrv == bdrv)
2200
            return drives_table[index].serial;
2201

    
2202
    return "\0";
2203
}
2204

    
2205
static void bdrv_format_print(void *opaque, const char *name)
2206
{
2207
    fprintf(stderr, " %s", name);
2208
}
2209

    
2210
static int drive_init(struct drive_opt *arg, int snapshot,
2211
                      QEMUMachine *machine)
2212
{
2213
    char buf[128];
2214
    char file[1024];
2215
    char devname[128];
2216
    char serial[21];
2217
    const char *mediastr = "";
2218
    BlockInterfaceType type;
2219
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2220
    int bus_id, unit_id;
2221
    int cyls, heads, secs, translation;
2222
    BlockDriverState *bdrv;
2223
    BlockDriver *drv = NULL;
2224
    int max_devs;
2225
    int index;
2226
    int cache;
2227
    int bdrv_flags;
2228
    char *str = arg->opt;
2229
    static const char * const params[] = { "bus", "unit", "if", "index",
2230
                                           "cyls", "heads", "secs", "trans",
2231
                                           "media", "snapshot", "file",
2232
                                           "cache", "format", "serial", NULL };
2233

    
2234
    if (check_params(buf, sizeof(buf), params, str) < 0) {
2235
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2236
                         buf, str);
2237
         return -1;
2238
    }
2239

    
2240
    file[0] = 0;
2241
    cyls = heads = secs = 0;
2242
    bus_id = 0;
2243
    unit_id = -1;
2244
    translation = BIOS_ATA_TRANSLATION_AUTO;
2245
    index = -1;
2246
    cache = 3;
2247

    
2248
    if (machine->use_scsi) {
2249
        type = IF_SCSI;
2250
        max_devs = MAX_SCSI_DEVS;
2251
        pstrcpy(devname, sizeof(devname), "scsi");
2252
    } else {
2253
        type = IF_IDE;
2254
        max_devs = MAX_IDE_DEVS;
2255
        pstrcpy(devname, sizeof(devname), "ide");
2256
    }
2257
    media = MEDIA_DISK;
2258

    
2259
    /* extract parameters */
2260

    
2261
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2262
        bus_id = strtol(buf, NULL, 0);
2263
        if (bus_id < 0) {
2264
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2265
            return -1;
2266
        }
2267
    }
2268

    
2269
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2270
        unit_id = strtol(buf, NULL, 0);
2271
        if (unit_id < 0) {
2272
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2273
            return -1;
2274
        }
2275
    }
2276

    
2277
    if (get_param_value(buf, sizeof(buf), "if", str)) {
2278
        pstrcpy(devname, sizeof(devname), buf);
2279
        if (!strcmp(buf, "ide")) {
2280
            type = IF_IDE;
2281
            max_devs = MAX_IDE_DEVS;
2282
        } else if (!strcmp(buf, "scsi")) {
2283
            type = IF_SCSI;
2284
            max_devs = MAX_SCSI_DEVS;
2285
        } else if (!strcmp(buf, "floppy")) {
2286
            type = IF_FLOPPY;
2287
            max_devs = 0;
2288
        } else if (!strcmp(buf, "pflash")) {
2289
            type = IF_PFLASH;
2290
            max_devs = 0;
2291
        } else if (!strcmp(buf, "mtd")) {
2292
            type = IF_MTD;
2293
            max_devs = 0;
2294
        } else if (!strcmp(buf, "sd")) {
2295
            type = IF_SD;
2296
            max_devs = 0;
2297
        } else if (!strcmp(buf, "virtio")) {
2298
            type = IF_VIRTIO;
2299
            max_devs = 0;
2300
        } else {
2301
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2302
            return -1;
2303
        }
2304
    }
2305

    
2306
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2307
        index = strtol(buf, NULL, 0);
2308
        if (index < 0) {
2309
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2310
            return -1;
2311
        }
2312
    }
2313

    
2314
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2315
        cyls = strtol(buf, NULL, 0);
2316
    }
2317

    
2318
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2319
        heads = strtol(buf, NULL, 0);
2320
    }
2321

    
2322
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2323
        secs = strtol(buf, NULL, 0);
2324
    }
2325

    
2326
    if (cyls || heads || secs) {
2327
        if (cyls < 1 || cyls > 16383) {
2328
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2329
            return -1;
2330
        }
2331
        if (heads < 1 || heads > 16) {
2332
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2333
            return -1;
2334
        }
2335
        if (secs < 1 || secs > 63) {
2336
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2337
            return -1;
2338
        }
2339
    }
2340

    
2341
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2342
        if (!cyls) {
2343
            fprintf(stderr,
2344
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2345
                    str);
2346
            return -1;
2347
        }
2348
        if (!strcmp(buf, "none"))
2349
            translation = BIOS_ATA_TRANSLATION_NONE;
2350
        else if (!strcmp(buf, "lba"))
2351
            translation = BIOS_ATA_TRANSLATION_LBA;
2352
        else if (!strcmp(buf, "auto"))
2353
            translation = BIOS_ATA_TRANSLATION_AUTO;
2354
        else {
2355
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2356
            return -1;
2357
        }
2358
    }
2359

    
2360
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2361
        if (!strcmp(buf, "disk")) {
2362
            media = MEDIA_DISK;
2363
        } else if (!strcmp(buf, "cdrom")) {
2364
            if (cyls || secs || heads) {
2365
                fprintf(stderr,
2366
                        "qemu: '%s' invalid physical CHS format\n", str);
2367
                return -1;
2368
            }
2369
            media = MEDIA_CDROM;
2370
        } else {
2371
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2372
            return -1;
2373
        }
2374
    }
2375

    
2376
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2377
        if (!strcmp(buf, "on"))
2378
            snapshot = 1;
2379
        else if (!strcmp(buf, "off"))
2380
            snapshot = 0;
2381
        else {
2382
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2383
            return -1;
2384
        }
2385
    }
2386

    
2387
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2388
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2389
            cache = 0;
2390
        else if (!strcmp(buf, "writethrough"))
2391
            cache = 1;
2392
        else if (!strcmp(buf, "writeback"))
2393
            cache = 2;
2394
        else {
2395
           fprintf(stderr, "qemu: invalid cache option\n");
2396
           return -1;
2397
        }
2398
    }
2399

    
2400
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2401
       if (strcmp(buf, "?") == 0) {
2402
            fprintf(stderr, "qemu: Supported formats:");
2403
            bdrv_iterate_format(bdrv_format_print, NULL);
2404
            fprintf(stderr, "\n");
2405
            return -1;
2406
        }
2407
        drv = bdrv_find_format(buf);
2408
        if (!drv) {
2409
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2410
            return -1;
2411
        }
2412
    }
2413

    
2414
    if (arg->file == NULL)
2415
        get_param_value(file, sizeof(file), "file", str);
2416
    else
2417
        pstrcpy(file, sizeof(file), arg->file);
2418

    
2419
    if (!get_param_value(serial, sizeof(serial), "serial", str))
2420
            memset(serial, 0,  sizeof(serial));
2421

    
2422
    /* compute bus and unit according index */
2423

    
2424
    if (index != -1) {
2425
        if (bus_id != 0 || unit_id != -1) {
2426
            fprintf(stderr,
2427
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2428
            return -1;
2429
        }
2430
        if (max_devs == 0)
2431
        {
2432
            unit_id = index;
2433
            bus_id = 0;
2434
        } else {
2435
            unit_id = index % max_devs;
2436
            bus_id = index / max_devs;
2437
        }
2438
    }
2439

    
2440
    /* if user doesn't specify a unit_id,
2441
     * try to find the first free
2442
     */
2443

    
2444
    if (unit_id == -1) {
2445
       unit_id = 0;
2446
       while (drive_get_index(type, bus_id, unit_id) != -1) {
2447
           unit_id++;
2448
           if (max_devs && unit_id >= max_devs) {
2449
               unit_id -= max_devs;
2450
               bus_id++;
2451
           }
2452
       }
2453
    }
2454

    
2455
    /* check unit id */
2456

    
2457
    if (max_devs && unit_id >= max_devs) {
2458
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2459
                        str, unit_id, max_devs - 1);
2460
        return -1;
2461
    }
2462

    
2463
    /*
2464
     * ignore multiple definitions
2465
     */
2466

    
2467
    if (drive_get_index(type, bus_id, unit_id) != -1)
2468
        return 0;
2469

    
2470
    /* init */
2471

    
2472
    if (type == IF_IDE || type == IF_SCSI)
2473
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2474
    if (max_devs)
2475
        snprintf(buf, sizeof(buf), "%s%i%s%i",
2476
                 devname, bus_id, mediastr, unit_id);
2477
    else
2478
        snprintf(buf, sizeof(buf), "%s%s%i",
2479
                 devname, mediastr, unit_id);
2480
    bdrv = bdrv_new(buf);
2481
    drives_table[nb_drives].bdrv = bdrv;
2482
    drives_table[nb_drives].type = type;
2483
    drives_table[nb_drives].bus = bus_id;
2484
    drives_table[nb_drives].unit = unit_id;
2485
    strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2486
    nb_drives++;
2487

    
2488
    switch(type) {
2489
    case IF_IDE:
2490
    case IF_SCSI:
2491
        switch(media) {
2492
        case MEDIA_DISK:
2493
            if (cyls != 0) {
2494
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2495
                bdrv_set_translation_hint(bdrv, translation);
2496
            }
2497
            break;
2498
        case MEDIA_CDROM:
2499
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2500
            break;
2501
        }
2502
        break;
2503
    case IF_SD:
2504
        /* FIXME: This isn't really a floppy, but it's a reasonable
2505
           approximation.  */
2506
    case IF_FLOPPY:
2507
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2508
        break;
2509
    case IF_PFLASH:
2510
    case IF_MTD:
2511
    case IF_VIRTIO:
2512
        break;
2513
    }
2514
    if (!file[0])
2515
        return 0;
2516
    bdrv_flags = 0;
2517
    if (snapshot) {
2518
        bdrv_flags |= BDRV_O_SNAPSHOT;
2519
        cache = 2; /* always use write-back with snapshot */
2520
    }
2521
    if (cache == 0) /* no caching */
2522
        bdrv_flags |= BDRV_O_NOCACHE;
2523
    else if (cache == 2) /* write-back */
2524
        bdrv_flags |= BDRV_O_CACHE_WB;
2525
    else if (cache == 3) /* not specified */
2526
        bdrv_flags |= BDRV_O_CACHE_DEF;
2527
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2528
        fprintf(stderr, "qemu: could not open disk image %s\n",
2529
                        file);
2530
        return -1;
2531
    }
2532
    return 0;
2533
}
2534

    
2535
/***********************************************************/
2536
/* USB devices */
2537

    
2538
static USBPort *used_usb_ports;
2539
static USBPort *free_usb_ports;
2540

    
2541
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2542
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2543
                            usb_attachfn attach)
2544
{
2545
    port->opaque = opaque;
2546
    port->index = index;
2547
    port->attach = attach;
2548
    port->next = free_usb_ports;
2549
    free_usb_ports = port;
2550
}
2551

    
2552
int usb_device_add_dev(USBDevice *dev)
2553
{
2554
    USBPort *port;
2555

    
2556
    /* Find a USB port to add the device to.  */
2557
    port = free_usb_ports;
2558
    if (!port->next) {
2559
        USBDevice *hub;
2560

    
2561
        /* Create a new hub and chain it on.  */
2562
        free_usb_ports = NULL;
2563
        port->next = used_usb_ports;
2564
        used_usb_ports = port;
2565

    
2566
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2567
        usb_attach(port, hub);
2568
        port = free_usb_ports;
2569
    }
2570

    
2571
    free_usb_ports = port->next;
2572
    port->next = used_usb_ports;
2573
    used_usb_ports = port;
2574
    usb_attach(port, dev);
2575
    return 0;
2576
}
2577

    
2578
static int usb_device_add(const char *devname)
2579
{
2580
    const char *p;
2581
    USBDevice *dev;
2582

    
2583
    if (!free_usb_ports)
2584
        return -1;
2585

    
2586
    if (strstart(devname, "host:", &p)) {
2587
        dev = usb_host_device_open(p);
2588
    } else if (!strcmp(devname, "mouse")) {
2589
        dev = usb_mouse_init();
2590
    } else if (!strcmp(devname, "tablet")) {
2591
        dev = usb_tablet_init();
2592
    } else if (!strcmp(devname, "keyboard")) {
2593
        dev = usb_keyboard_init();
2594
    } else if (strstart(devname, "disk:", &p)) {
2595
        dev = usb_msd_init(p);
2596
    } else if (!strcmp(devname, "wacom-tablet")) {
2597
        dev = usb_wacom_init();
2598
    } else if (strstart(devname, "serial:", &p)) {
2599
        dev = usb_serial_init(p);
2600
#ifdef CONFIG_BRLAPI
2601
    } else if (!strcmp(devname, "braille")) {
2602
        dev = usb_baum_init();
2603
#endif
2604
    } else if (strstart(devname, "net:", &p)) {
2605
        int nic = nb_nics;
2606

    
2607
        if (net_client_init("nic", p) < 0)
2608
            return -1;
2609
        nd_table[nic].model = "usb";
2610
        dev = usb_net_init(&nd_table[nic]);
2611
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2612
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2613
                        bt_new_hci(qemu_find_bt_vlan(0)));
2614
    } else {
2615
        return -1;
2616
    }
2617
    if (!dev)
2618
        return -1;
2619

    
2620
    return usb_device_add_dev(dev);
2621
}
2622

    
2623
int usb_device_del_addr(int bus_num, int addr)
2624
{
2625
    USBPort *port;
2626
    USBPort **lastp;
2627
    USBDevice *dev;
2628

    
2629
    if (!used_usb_ports)
2630
        return -1;
2631

    
2632
    if (bus_num != 0)
2633
        return -1;
2634

    
2635
    lastp = &used_usb_ports;
2636
    port = used_usb_ports;
2637
    while (port && port->dev->addr != addr) {
2638
        lastp = &port->next;
2639
        port = port->next;
2640
    }
2641

    
2642
    if (!port)
2643
        return -1;
2644

    
2645
    dev = port->dev;
2646
    *lastp = port->next;
2647
    usb_attach(port, NULL);
2648
    dev->handle_destroy(dev);
2649
    port->next = free_usb_ports;
2650
    free_usb_ports = port;
2651
    return 0;
2652
}
2653

    
2654
static int usb_device_del(const char *devname)
2655
{
2656
    int bus_num, addr;
2657
    const char *p;
2658

    
2659
    if (strstart(devname, "host:", &p))
2660
        return usb_host_device_close(p);
2661

    
2662
    if (!used_usb_ports)
2663
        return -1;
2664

    
2665
    p = strchr(devname, '.');
2666
    if (!p)
2667
        return -1;
2668
    bus_num = strtoul(devname, NULL, 0);
2669
    addr = strtoul(p + 1, NULL, 0);
2670

    
2671
    return usb_device_del_addr(bus_num, addr);
2672
}
2673

    
2674
void do_usb_add(const char *devname)
2675
{
2676
    usb_device_add(devname);
2677
}
2678

    
2679
void do_usb_del(const char *devname)
2680
{
2681
    usb_device_del(devname);
2682
}
2683

    
2684
void usb_info(void)
2685
{
2686
    USBDevice *dev;
2687
    USBPort *port;
2688
    const char *speed_str;
2689

    
2690
    if (!usb_enabled) {
2691
        term_printf("USB support not enabled\n");
2692
        return;
2693
    }
2694

    
2695
    for (port = used_usb_ports; port; port = port->next) {
2696
        dev = port->dev;
2697
        if (!dev)
2698
            continue;
2699
        switch(dev->speed) {
2700
        case USB_SPEED_LOW:
2701
            speed_str = "1.5";
2702
            break;
2703
        case USB_SPEED_FULL:
2704
            speed_str = "12";
2705
            break;
2706
        case USB_SPEED_HIGH:
2707
            speed_str = "480";
2708
            break;
2709
        default:
2710
            speed_str = "?";
2711
            break;
2712
        }
2713
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
2714
                    0, dev->addr, speed_str, dev->devname);
2715
    }
2716
}
2717

    
2718
/***********************************************************/
2719
/* PCMCIA/Cardbus */
2720

    
2721
static struct pcmcia_socket_entry_s {
2722
    struct pcmcia_socket_s *socket;
2723
    struct pcmcia_socket_entry_s *next;
2724
} *pcmcia_sockets = 0;
2725

    
2726
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2727
{
2728
    struct pcmcia_socket_entry_s *entry;
2729

    
2730
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2731
    entry->socket = socket;
2732
    entry->next = pcmcia_sockets;
2733
    pcmcia_sockets = entry;
2734
}
2735

    
2736
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2737
{
2738
    struct pcmcia_socket_entry_s *entry, **ptr;
2739

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

    
2748
void pcmcia_info(void)
2749
{
2750
    struct pcmcia_socket_entry_s *iter;
2751
    if (!pcmcia_sockets)
2752
        term_printf("No PCMCIA sockets\n");
2753

    
2754
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2755
        term_printf("%s: %s\n", iter->socket->slot_string,
2756
                    iter->socket->attached ? iter->socket->card_string :
2757
                    "Empty");
2758
}
2759

    
2760
/***********************************************************/
2761
/* dumb display */
2762

    
2763
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2764
{
2765
}
2766

    
2767
static void dumb_resize(DisplayState *ds, int w, int h)
2768
{
2769
}
2770

    
2771
static void dumb_display_init(DisplayState *ds)
2772
{
2773
    ds->data = NULL;
2774
    ds->linesize = 0;
2775
    ds->depth = 0;
2776
    ds->dpy_update = dumb_update;
2777
    ds->dpy_resize = dumb_resize;
2778
    ds->dpy_refresh = NULL;
2779
    ds->gui_timer_interval = 0;
2780
    ds->idle = 1;
2781
}
2782

    
2783
/***********************************************************/
2784
/* I/O handling */
2785

    
2786
#define MAX_IO_HANDLERS 64
2787

    
2788
typedef struct IOHandlerRecord {
2789
    int fd;
2790
    IOCanRWHandler *fd_read_poll;
2791
    IOHandler *fd_read;
2792
    IOHandler *fd_write;
2793
    int deleted;
2794
    void *opaque;
2795
    /* temporary data */
2796
    struct pollfd *ufd;
2797
    struct IOHandlerRecord *next;
2798
} IOHandlerRecord;
2799

    
2800
static IOHandlerRecord *first_io_handler;
2801

    
2802
/* XXX: fd_read_poll should be suppressed, but an API change is
2803
   necessary in the character devices to suppress fd_can_read(). */
2804
int qemu_set_fd_handler2(int fd,
2805
                         IOCanRWHandler *fd_read_poll,
2806
                         IOHandler *fd_read,
2807
                         IOHandler *fd_write,
2808
                         void *opaque)
2809
{
2810
    IOHandlerRecord **pioh, *ioh;
2811

    
2812
    if (!fd_read && !fd_write) {
2813
        pioh = &first_io_handler;
2814
        for(;;) {
2815
            ioh = *pioh;
2816
            if (ioh == NULL)
2817
                break;
2818
            if (ioh->fd == fd) {
2819
                ioh->deleted = 1;
2820
                break;
2821
            }
2822
            pioh = &ioh->next;
2823
        }
2824
    } else {
2825
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2826
            if (ioh->fd == fd)
2827
                goto found;
2828
        }
2829
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2830
        if (!ioh)
2831
            return -1;
2832
        ioh->next = first_io_handler;
2833
        first_io_handler = ioh;
2834
    found:
2835
        ioh->fd = fd;
2836
        ioh->fd_read_poll = fd_read_poll;
2837
        ioh->fd_read = fd_read;
2838
        ioh->fd_write = fd_write;
2839
        ioh->opaque = opaque;
2840
        ioh->deleted = 0;
2841
    }
2842
    return 0;
2843
}
2844

    
2845
int qemu_set_fd_handler(int fd,
2846
                        IOHandler *fd_read,
2847
                        IOHandler *fd_write,
2848
                        void *opaque)
2849
{
2850
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2851
}
2852

    
2853
#ifdef _WIN32
2854
/***********************************************************/
2855
/* Polling handling */
2856

    
2857
typedef struct PollingEntry {
2858
    PollingFunc *func;
2859
    void *opaque;
2860
    struct PollingEntry *next;
2861
} PollingEntry;
2862

    
2863
static PollingEntry *first_polling_entry;
2864

    
2865
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2866
{
2867
    PollingEntry **ppe, *pe;
2868
    pe = qemu_mallocz(sizeof(PollingEntry));
2869
    if (!pe)
2870
        return -1;
2871
    pe->func = func;
2872
    pe->opaque = opaque;
2873
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2874
    *ppe = pe;
2875
    return 0;
2876
}
2877

    
2878
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2879
{
2880
    PollingEntry **ppe, *pe;
2881
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2882
        pe = *ppe;
2883
        if (pe->func == func && pe->opaque == opaque) {
2884
            *ppe = pe->next;
2885
            qemu_free(pe);
2886
            break;
2887
        }
2888
    }
2889
}
2890

    
2891
/***********************************************************/
2892
/* Wait objects support */
2893
typedef struct WaitObjects {
2894
    int num;
2895
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2896
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2897
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2898
} WaitObjects;
2899

    
2900
static WaitObjects wait_objects = {0};
2901

    
2902
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2903
{
2904
    WaitObjects *w = &wait_objects;
2905

    
2906
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2907
        return -1;
2908
    w->events[w->num] = handle;
2909
    w->func[w->num] = func;
2910
    w->opaque[w->num] = opaque;
2911
    w->num++;
2912
    return 0;
2913
}
2914

    
2915
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2916
{
2917
    int i, found;
2918
    WaitObjects *w = &wait_objects;
2919

    
2920
    found = 0;
2921
    for (i = 0; i < w->num; i++) {
2922
        if (w->events[i] == handle)
2923
            found = 1;
2924
        if (found) {
2925
            w->events[i] = w->events[i + 1];
2926
            w->func[i] = w->func[i + 1];
2927
            w->opaque[i] = w->opaque[i + 1];
2928
        }
2929
    }
2930
    if (found)
2931
        w->num--;
2932
}
2933
#endif
2934

    
2935
/***********************************************************/
2936
/* ram save/restore */
2937

    
2938
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
2939
{
2940
    int v;
2941

    
2942
    v = qemu_get_byte(f);
2943
    switch(v) {
2944
    case 0:
2945
        if (qemu_get_buffer(f, buf, len) != len)
2946
            return -EIO;
2947
        break;
2948
    case 1:
2949
        v = qemu_get_byte(f);
2950
        memset(buf, v, len);
2951
        break;
2952
    default:
2953
        return -EINVAL;
2954
    }
2955

    
2956
    if (qemu_file_has_error(f))
2957
        return -EIO;
2958

    
2959
    return 0;
2960
}
2961

    
2962
static int ram_load_v1(QEMUFile *f, void *opaque)
2963
{
2964
    int ret;
2965
    ram_addr_t i;
2966

    
2967
    if (qemu_get_be32(f) != phys_ram_size)
2968
        return -EINVAL;
2969
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
2970
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
2971
        if (ret)
2972
            return ret;
2973
    }
2974
    return 0;
2975
}
2976

    
2977
#define BDRV_HASH_BLOCK_SIZE 1024
2978
#define IOBUF_SIZE 4096
2979
#define RAM_CBLOCK_MAGIC 0xfabe
2980

    
2981
typedef struct RamDecompressState {
2982
    z_stream zstream;
2983
    QEMUFile *f;
2984
    uint8_t buf[IOBUF_SIZE];
2985
} RamDecompressState;
2986

    
2987
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
2988
{
2989
    int ret;
2990
    memset(s, 0, sizeof(*s));
2991
    s->f = f;
2992
    ret = inflateInit(&s->zstream);
2993
    if (ret != Z_OK)
2994
        return -1;
2995
    return 0;
2996
}
2997

    
2998
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
2999
{
3000
    int ret, clen;
3001

    
3002
    s->zstream.avail_out = len;
3003
    s->zstream.next_out = buf;
3004
    while (s->zstream.avail_out > 0) {
3005
        if (s->zstream.avail_in == 0) {
3006
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3007
                return -1;
3008
            clen = qemu_get_be16(s->f);
3009
            if (clen > IOBUF_SIZE)
3010
                return -1;
3011
            qemu_get_buffer(s->f, s->buf, clen);
3012
            s->zstream.avail_in = clen;
3013
            s->zstream.next_in = s->buf;
3014
        }
3015
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3016
        if (ret != Z_OK && ret != Z_STREAM_END) {
3017
            return -1;
3018
        }
3019
    }
3020
    return 0;
3021
}
3022

    
3023
static void ram_decompress_close(RamDecompressState *s)
3024
{
3025
    inflateEnd(&s->zstream);
3026
}
3027

    
3028
#define RAM_SAVE_FLAG_FULL        0x01
3029
#define RAM_SAVE_FLAG_COMPRESS        0x02
3030
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
3031
#define RAM_SAVE_FLAG_PAGE        0x08
3032
#define RAM_SAVE_FLAG_EOS        0x10
3033

    
3034
static int is_dup_page(uint8_t *page, uint8_t ch)
3035
{
3036
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3037
    uint32_t *array = (uint32_t *)page;
3038
    int i;
3039

    
3040
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3041
        if (array[i] != val)
3042
            return 0;
3043
    }
3044

    
3045
    return 1;
3046
}
3047

    
3048
static int ram_save_block(QEMUFile *f)
3049
{
3050
    static ram_addr_t current_addr = 0;
3051
    ram_addr_t saved_addr = current_addr;
3052
    ram_addr_t addr = 0;
3053
    int found = 0;
3054

    
3055
    while (addr < phys_ram_size) {
3056
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3057
            uint8_t ch;
3058

    
3059
            cpu_physical_memory_reset_dirty(current_addr,
3060
                                            current_addr + TARGET_PAGE_SIZE,
3061
                                            MIGRATION_DIRTY_FLAG);
3062

    
3063
            ch = *(phys_ram_base + current_addr);
3064

    
3065
            if (is_dup_page(phys_ram_base + current_addr, ch)) {
3066
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3067
                qemu_put_byte(f, ch);
3068
            } else {
3069
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3070
                qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3071
            }
3072

    
3073
            found = 1;
3074
            break;
3075
        }
3076
        addr += TARGET_PAGE_SIZE;
3077
        current_addr = (saved_addr + addr) % phys_ram_size;
3078
    }
3079

    
3080
    return found;
3081
}
3082

    
3083
static ram_addr_t ram_save_threshold = 10;
3084

    
3085
static ram_addr_t ram_save_remaining(void)
3086
{
3087
    ram_addr_t addr;
3088
    ram_addr_t count = 0;
3089

    
3090
    for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3091
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3092
            count++;
3093
    }
3094

    
3095
    return count;
3096
}
3097

    
3098
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3099
{
3100
    ram_addr_t addr;
3101

    
3102
    if (stage == 1) {
3103
        /* Make sure all dirty bits are set */
3104
        for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3105
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3106
                cpu_physical_memory_set_dirty(addr);
3107
        }
3108
        
3109
        /* Enable dirty memory tracking */
3110
        cpu_physical_memory_set_dirty_tracking(1);
3111

    
3112
        qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3113
    }
3114

    
3115
    while (!qemu_file_rate_limit(f)) {
3116
        int ret;
3117

    
3118
        ret = ram_save_block(f);
3119
        if (ret == 0) /* no more blocks */
3120
            break;
3121
    }
3122

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

    
3125
    if (stage == 3) {
3126
        cpu_physical_memory_set_dirty_tracking(0);
3127

    
3128
        /* flush all remaining blocks regardless of rate limiting */
3129
        while (ram_save_block(f) != 0);
3130
    }
3131

    
3132
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3133

    
3134
    return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3135
}
3136

    
3137
static int ram_load_dead(QEMUFile *f, void *opaque)
3138
{
3139
    RamDecompressState s1, *s = &s1;
3140
    uint8_t buf[10];
3141
    ram_addr_t i;
3142

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

    
3163
    return 0;
3164
}
3165

    
3166
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3167
{
3168
    ram_addr_t addr;
3169
    int flags;
3170

    
3171
    if (version_id == 1)
3172
        return ram_load_v1(f, opaque);
3173

    
3174
    if (version_id == 2) {
3175
        if (qemu_get_be32(f) != phys_ram_size)
3176
            return -EINVAL;
3177
        return ram_load_dead(f, opaque);
3178
    }
3179

    
3180
    if (version_id != 3)
3181
        return -EINVAL;
3182

    
3183
    do {
3184
        addr = qemu_get_be64(f);
3185

    
3186
        flags = addr & ~TARGET_PAGE_MASK;
3187
        addr &= TARGET_PAGE_MASK;
3188

    
3189
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3190
            if (addr != phys_ram_size)
3191
                return -EINVAL;
3192
        }
3193

    
3194
        if (flags & RAM_SAVE_FLAG_FULL) {
3195
            if (ram_load_dead(f, opaque) < 0)
3196
                return -EINVAL;
3197
        }
3198
        
3199
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3200
            uint8_t ch = qemu_get_byte(f);
3201
            memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
3202
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3203
            qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
3204
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3205

    
3206
    return 0;
3207
}
3208

    
3209
void qemu_service_io(void)
3210
{
3211
    CPUState *env = cpu_single_env;
3212
    if (env) {
3213
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3214
#ifdef USE_KQEMU
3215
        if (env->kqemu_enabled) {
3216
            kqemu_cpu_interrupt(env);
3217
        }
3218
#endif
3219
    }
3220
}
3221

    
3222
/***********************************************************/
3223
/* bottom halves (can be seen as timers which expire ASAP) */
3224

    
3225
struct QEMUBH {
3226
    QEMUBHFunc *cb;
3227
    void *opaque;
3228
    int scheduled;
3229
    int idle;
3230
    int deleted;
3231
    QEMUBH *next;
3232
};
3233

    
3234
static QEMUBH *first_bh = NULL;
3235

    
3236
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3237
{
3238
    QEMUBH *bh;
3239
    bh = qemu_mallocz(sizeof(QEMUBH));
3240
    if (!bh)
3241
        return NULL;
3242
    bh->cb = cb;
3243
    bh->opaque = opaque;
3244
    bh->next = first_bh;
3245
    first_bh = bh;
3246
    return bh;
3247
}
3248

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

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

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

    
3276
    return ret;
3277
}
3278

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

    
3287
void qemu_bh_schedule(QEMUBH *bh)
3288
{
3289
    CPUState *env = cpu_single_env;
3290
    if (bh->scheduled)
3291
        return;
3292
    bh->scheduled = 1;
3293
    bh->idle = 0;
3294
    /* stop the currently executing CPU to execute the BH ASAP */
3295
    if (env) {
3296
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
3297
    }
3298
}
3299

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

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

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

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

    
3331
/***********************************************************/
3332
/* machine registration */
3333

    
3334
static QEMUMachine *first_machine = NULL;
3335

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

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

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

    
3358
/***********************************************************/
3359
/* main execution loop */
3360

    
3361
static void gui_update(void *opaque)
3362
{
3363
    DisplayState *ds = opaque;
3364
    ds->dpy_refresh(ds);
3365
    qemu_mod_timer(ds->gui_timer,
3366
        (ds->gui_timer_interval ?
3367
            ds->gui_timer_interval :
3368
            GUI_REFRESH_INTERVAL)
3369
        + qemu_get_clock(rt_clock));
3370
}
3371

    
3372
struct vm_change_state_entry {
3373
    VMChangeStateHandler *cb;
3374
    void *opaque;
3375
    LIST_ENTRY (vm_change_state_entry) entries;
3376
};
3377

    
3378
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3379

    
3380
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3381
                                                     void *opaque)
3382
{
3383
    VMChangeStateEntry *e;
3384

    
3385
    e = qemu_mallocz(sizeof (*e));
3386
    if (!e)
3387
        return NULL;
3388

    
3389
    e->cb = cb;
3390
    e->opaque = opaque;
3391
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3392
    return e;
3393
}
3394

    
3395
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3396
{
3397
    LIST_REMOVE (e, entries);
3398
    qemu_free (e);
3399
}
3400

    
3401
static void vm_state_notify(int running)
3402
{
3403
    VMChangeStateEntry *e;
3404

    
3405
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3406
        e->cb(e->opaque, running);
3407
    }
3408
}
3409

    
3410
/* XXX: support several handlers */
3411
static VMStopHandler *vm_stop_cb;
3412
static void *vm_stop_opaque;
3413

    
3414
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3415
{
3416
    vm_stop_cb = cb;
3417
    vm_stop_opaque = opaque;
3418
    return 0;
3419
}
3420

    
3421
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3422
{
3423
    vm_stop_cb = NULL;
3424
}
3425

    
3426
void vm_start(void)
3427
{
3428
    if (!vm_running) {
3429
        cpu_enable_ticks();
3430
        vm_running = 1;
3431
        vm_state_notify(1);
3432
        qemu_rearm_alarm_timer(alarm_timer);
3433
    }
3434
}
3435

    
3436
void vm_stop(int reason)
3437
{
3438
    if (vm_running) {
3439
        cpu_disable_ticks();
3440
        vm_running = 0;
3441
        if (reason != 0) {
3442
            if (vm_stop_cb) {
3443
                vm_stop_cb(vm_stop_opaque, reason);
3444
            }
3445
        }
3446
        vm_state_notify(0);
3447
    }
3448
}
3449

    
3450
/* reset/shutdown handler */
3451

    
3452
typedef struct QEMUResetEntry {
3453
    QEMUResetHandler *func;
3454
    void *opaque;
3455
    struct QEMUResetEntry *next;
3456
} QEMUResetEntry;
3457

    
3458
static QEMUResetEntry *first_reset_entry;
3459
static int reset_requested;
3460
static int shutdown_requested;
3461
static int powerdown_requested;
3462

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

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

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

    
3484
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3485
{
3486
    QEMUResetEntry **pre, *re;
3487

    
3488
    pre = &first_reset_entry;
3489
    while (*pre != NULL)
3490
        pre = &(*pre)->next;
3491
    re = qemu_mallocz(sizeof(QEMUResetEntry));
3492
    re->func = func;
3493
    re->opaque = opaque;
3494
    re->next = NULL;
3495
    *pre = re;
3496
}
3497

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

    
3502
    /* reset all devices */
3503
    for(re = first_reset_entry; re != NULL; re = re->next) {
3504
        re->func(re->opaque);
3505
    }
3506
}
3507

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

    
3519
void qemu_system_shutdown_request(void)
3520
{
3521
    shutdown_requested = 1;
3522
    if (cpu_single_env)
3523
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3524
}
3525

    
3526
void qemu_system_powerdown_request(void)
3527
{
3528
    powerdown_requested = 1;
3529
    if (cpu_single_env)
3530
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3531
}
3532

    
3533
#ifdef _WIN32
3534
static void host_main_loop_wait(int *timeout)
3535
{
3536
    int ret, ret2, i;
3537
    PollingEntry *pe;
3538

    
3539

    
3540
    /* XXX: need to suppress polling by better using win32 events */
3541
    ret = 0;
3542
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3543
        ret |= pe->func(pe->opaque);
3544
    }
3545
    if (ret == 0) {
3546
        int err;
3547
        WaitObjects *w = &wait_objects;
3548

    
3549
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3550
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3551
            if (w->func[ret - WAIT_OBJECT_0])
3552
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3553

    
3554
            /* Check for additional signaled events */
3555
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3556

    
3557
                /* Check if event is signaled */
3558
                ret2 = WaitForSingleObject(w->events[i], 0);
3559
                if(ret2 == WAIT_OBJECT_0) {
3560
                    if (w->func[i])
3561
                        w->func[i](w->opaque[i]);
3562
                } else if (ret2 == WAIT_TIMEOUT) {
3563
                } else {
3564
                    err = GetLastError();
3565
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3566
                }
3567
            }
3568
        } else if (ret == WAIT_TIMEOUT) {
3569
        } else {
3570
            err = GetLastError();
3571
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3572
        }
3573
    }
3574

    
3575
    *timeout = 0;
3576
}
3577
#else
3578
static void host_main_loop_wait(int *timeout)
3579
{
3580
}
3581
#endif
3582

    
3583
void main_loop_wait(int timeout)
3584
{
3585
    IOHandlerRecord *ioh;
3586
    fd_set rfds, wfds, xfds;
3587
    int ret, nfds;
3588
    struct timeval tv;
3589

    
3590
    qemu_bh_update_timeout(&timeout);
3591

    
3592
    host_main_loop_wait(&timeout);
3593

    
3594
    /* poll any events */
3595
    /* XXX: separate device handlers from system ones */
3596
    nfds = -1;
3597
    FD_ZERO(&rfds);
3598
    FD_ZERO(&wfds);
3599
    FD_ZERO(&xfds);
3600
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3601
        if (ioh->deleted)
3602
            continue;
3603
        if (ioh->fd_read &&
3604
            (!ioh->fd_read_poll ||
3605
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3606
            FD_SET(ioh->fd, &rfds);
3607
            if (ioh->fd > nfds)
3608
                nfds = ioh->fd;
3609
        }
3610
        if (ioh->fd_write) {
3611
            FD_SET(ioh->fd, &wfds);
3612
            if (ioh->fd > nfds)
3613
                nfds = ioh->fd;
3614
        }
3615
    }
3616

    
3617
    tv.tv_sec = timeout / 1000;
3618
    tv.tv_usec = (timeout % 1000) * 1000;
3619

    
3620
#if defined(CONFIG_SLIRP)
3621
    if (slirp_is_inited()) {
3622
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3623
    }
3624
#endif
3625
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3626
    if (ret > 0) {
3627
        IOHandlerRecord **pioh;
3628

    
3629
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3630
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3631
                ioh->fd_read(ioh->opaque);
3632
            }
3633
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3634
                ioh->fd_write(ioh->opaque);
3635
            }
3636
        }
3637

    
3638
        /* remove deleted IO handlers */
3639
        pioh = &first_io_handler;
3640
        while (*pioh) {
3641
            ioh = *pioh;
3642
            if (ioh->deleted) {
3643
                *pioh = ioh->next;
3644
                qemu_free(ioh);
3645
            } else
3646
                pioh = &ioh->next;
3647
        }
3648
    }
3649
#if defined(CONFIG_SLIRP)
3650
    if (slirp_is_inited()) {
3651
        if (ret < 0) {
3652
            FD_ZERO(&rfds);
3653
            FD_ZERO(&wfds);
3654
            FD_ZERO(&xfds);
3655
        }
3656
        slirp_select_poll(&rfds, &wfds, &xfds);
3657
    }
3658
#endif
3659

    
3660
    /* vm time timers */
3661
    if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3662
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3663
                        qemu_get_clock(vm_clock));
3664

    
3665
    /* real time timers */
3666
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3667
                    qemu_get_clock(rt_clock));
3668

    
3669
    /* Check bottom-halves last in case any of the earlier events triggered
3670
       them.  */
3671
    qemu_bh_poll();
3672

    
3673
}
3674

    
3675
static int main_loop(void)
3676
{
3677
    int ret, timeout;
3678
#ifdef CONFIG_PROFILER
3679
    int64_t ti;
3680
#endif
3681
    CPUState *env;
3682

    
3683
    cur_cpu = first_cpu;
3684
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
3685
    for(;;) {
3686
        if (vm_running) {
3687

    
3688
            for(;;) {
3689
                /* get next cpu */
3690
                env = next_cpu;
3691
#ifdef CONFIG_PROFILER
3692
                ti = profile_getclock();
3693
#endif
3694
                if (use_icount) {
3695
                    int64_t count;
3696
                    int decr;
3697
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3698
                    env->icount_decr.u16.low = 0;
3699
                    env->icount_extra = 0;
3700
                    count = qemu_next_deadline();
3701
                    count = (count + (1 << icount_time_shift) - 1)
3702
                            >> icount_time_shift;
3703
                    qemu_icount += count;
3704
                    decr = (count > 0xffff) ? 0xffff : count;
3705
                    count -= decr;
3706
                    env->icount_decr.u16.low = decr;
3707
                    env->icount_extra = count;
3708
                }
3709
                ret = cpu_exec(env);
3710
#ifdef CONFIG_PROFILER
3711
                qemu_time += profile_getclock() - ti;
3712
#endif
3713
                if (use_icount) {
3714
                    /* Fold pending instructions back into the
3715
                       instruction counter, and clear the interrupt flag.  */
3716
                    qemu_icount -= (env->icount_decr.u16.low
3717
                                    + env->icount_extra);
3718
                    env->icount_decr.u32 = 0;
3719
                    env->icount_extra = 0;
3720
                }
3721
                next_cpu = env->next_cpu ?: first_cpu;
3722
                if (event_pending && likely(ret != EXCP_DEBUG)) {
3723
                    ret = EXCP_INTERRUPT;
3724
                    event_pending = 0;
3725
                    break;
3726
                }
3727
                if (ret == EXCP_HLT) {
3728
                    /* Give the next CPU a chance to run.  */
3729
                    cur_cpu = env;
3730
                    continue;
3731
                }
3732
                if (ret != EXCP_HALTED)
3733
                    break;
3734
                /* all CPUs are halted ? */
3735
                if (env == cur_cpu)
3736
                    break;
3737
            }
3738
            cur_cpu = env;
3739

    
3740
            if (shutdown_requested) {
3741
                ret = EXCP_INTERRUPT;
3742
                if (no_shutdown) {
3743
                    vm_stop(0);
3744
                    no_shutdown = 0;
3745
                }
3746
                else
3747
                    break;
3748
            }
3749
            if (reset_requested) {
3750
                reset_requested = 0;
3751
                qemu_system_reset();
3752
                ret = EXCP_INTERRUPT;
3753
            }
3754
            if (powerdown_requested) {
3755
                powerdown_requested = 0;
3756
                qemu_system_powerdown();
3757
                ret = EXCP_INTERRUPT;
3758
            }
3759
            if (unlikely(ret == EXCP_DEBUG)) {
3760
                gdb_set_stop_cpu(cur_cpu);
3761
                vm_stop(EXCP_DEBUG);
3762
            }
3763
            /* If all cpus are halted then wait until the next IRQ */
3764
            /* XXX: use timeout computed from timers */
3765
            if (ret == EXCP_HALTED) {
3766
                if (use_icount) {
3767
                    int64_t add;
3768
                    int64_t delta;
3769
                    /* Advance virtual time to the next event.  */
3770
                    if (use_icount == 1) {
3771
                        /* When not using an adaptive execution frequency
3772
                           we tend to get badly out of sync with real time,
3773
                           so just delay for a reasonable amount of time.  */
3774
                        delta = 0;
3775
                    } else {
3776
                        delta = cpu_get_icount() - cpu_get_clock();
3777
                    }
3778
                    if (delta > 0) {
3779
                        /* If virtual time is ahead of real time then just
3780
                           wait for IO.  */
3781
                        timeout = (delta / 1000000) + 1;
3782
                    } else {
3783
                        /* Wait for either IO to occur or the next
3784
                           timer event.  */
3785
                        add = qemu_next_deadline();
3786
                        /* We advance the timer before checking for IO.
3787
                           Limit the amount we advance so that early IO
3788
                           activity won't get the guest too far ahead.  */
3789
                        if (add > 10000000)
3790
                            add = 10000000;
3791
                        delta += add;
3792
                        add = (add + (1 << icount_time_shift) - 1)
3793
                              >> icount_time_shift;
3794
                        qemu_icount += add;
3795
                        timeout = delta / 1000000;
3796
                        if (timeout < 0)
3797
                            timeout = 0;
3798
                    }
3799
                } else {
3800
                    timeout = 5000;
3801
                }
3802
            } else {
3803
                timeout = 0;
3804
            }
3805
        } else {
3806
            if (shutdown_requested) {
3807
                ret = EXCP_INTERRUPT;
3808
                break;
3809
            }
3810
            timeout = 5000;
3811
        }
3812
#ifdef CONFIG_PROFILER
3813
        ti = profile_getclock();
3814
#endif
3815
        main_loop_wait(timeout);
3816
#ifdef CONFIG_PROFILER
3817
        dev_time += profile_getclock() - ti;
3818
#endif
3819
    }
3820
    cpu_disable_ticks();
3821
    return ret;
3822
}
3823

    
3824
static void help(int exitcode)
3825
{
3826
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
3827
           "usage: %s [options] [disk_image]\n"
3828
           "\n"
3829
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3830
           "\n"
3831
           "Standard options:\n"
3832
           "-M machine      select emulated machine (-M ? for list)\n"
3833
           "-cpu cpu        select CPU (-cpu ? for list)\n"
3834
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
3835
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
3836
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
3837
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
3838
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
3839
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
3840
           "       [,cache=writethrough|writeback|none][,format=f][,serial=s]\n"
3841
           "                use 'file' as a drive image\n"
3842
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
3843
           "-sd file        use 'file' as SecureDigital card image\n"
3844
           "-pflash file    use 'file' as a parallel flash image\n"
3845
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
3846
           "-snapshot       write to temporary files instead of disk image files\n"
3847
#ifdef CONFIG_SDL
3848
           "-no-frame       open SDL window without a frame and window decorations\n"
3849
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
3850
           "-no-quit        disable SDL window close capability\n"
3851
#endif
3852
#ifdef TARGET_I386
3853
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
3854
#endif
3855
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
3856
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
3857
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
3858
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
3859
#ifndef _WIN32
3860
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
3861
#endif
3862
#ifdef HAS_AUDIO
3863
           "-audio-help     print list of audio drivers and their options\n"
3864
           "-soundhw c1,... enable audio support\n"
3865
           "                and only specified sound cards (comma separated list)\n"
3866
           "                use -soundhw ? to get the list of supported cards\n"
3867
           "                use -soundhw all to enable all of them\n"
3868
#endif
3869
           "-vga [std|cirrus|vmware|none]\n"
3870
           "                select video card type\n"
3871
           "-localtime      set the real time clock to local time [default=utc]\n"
3872
           "-full-screen    start in full screen\n"
3873
#ifdef TARGET_I386
3874
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
3875
           "-rtc-td-hack    use it to fix time drift in Windows ACPI HAL\n"
3876
#endif
3877
           "-usb            enable the USB driver (will be the default soon)\n"
3878
           "-usbdevice name add the host or guest USB device 'name'\n"
3879
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
3880
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
3881
#endif
3882
           "-name string    set the name of the guest\n"
3883
           "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
3884
           "\n"
3885
           "Network options:\n"
3886
           "-net nic[,vlan=n][,macaddr=addr][,model=type][,name=str]\n"
3887
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
3888
#ifdef CONFIG_SLIRP
3889
           "-net user[,vlan=n][,name=str][,hostname=host]\n"
3890
           "                connect the user mode network stack to VLAN 'n' and send\n"
3891
           "                hostname 'host' to DHCP clients\n"
3892
#endif
3893
#ifdef _WIN32
3894
           "-net tap[,vlan=n][,name=str],ifname=name\n"
3895
           "                connect the host TAP network interface to VLAN 'n'\n"
3896
#else
3897
           "-net tap[,vlan=n][,name=str][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
3898
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
3899
           "                network scripts 'file' (default=%s)\n"
3900
           "                and 'dfile' (default=%s);\n"
3901
           "                use '[down]script=no' to disable script execution;\n"
3902
           "                use 'fd=h' to connect to an already opened TAP interface\n"
3903
#endif
3904
           "-net socket[,vlan=n][,name=str][,fd=h][,listen=[host]:port][,connect=host:port]\n"
3905
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
3906
           "-net socket[,vlan=n][,name=str][,fd=h][,mcast=maddr:port]\n"
3907
           "                connect the vlan 'n' to multicast maddr and port\n"
3908
#ifdef CONFIG_VDE
3909
           "-net vde[,vlan=n][,name=str][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
3910
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
3911
           "                on host and listening for incoming connections on 'socketpath'.\n"
3912
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
3913
           "                ownership and permissions for communication port.\n"
3914
#endif
3915
           "-net none       use it alone to have zero network devices; if no -net option\n"
3916
           "                is provided, the default is '-net nic -net user'\n"
3917
           "\n"
3918
           "-bt hci,null    Dumb bluetooth HCI - doesn't respond to commands\n"
3919
           "-bt hci,host[:id]\n"
3920
           "                Use host's HCI with the given name\n"
3921
           "-bt hci[,vlan=n]\n"
3922
           "                Emulate a standard HCI in virtual scatternet 'n'\n"
3923
           "-bt vhci[,vlan=n]\n"
3924
           "                Add host computer to virtual scatternet 'n' using VHCI\n"
3925
           "-bt device:dev[,vlan=n]\n"
3926
           "                Emulate a bluetooth device 'dev' in scatternet 'n'\n"
3927
           "\n"
3928
#ifdef CONFIG_SLIRP
3929
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
3930
           "-bootp file     advertise file in BOOTP replies\n"
3931
#ifndef _WIN32
3932
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
3933
#endif
3934
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
3935
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
3936
#endif
3937
           "\n"
3938
           "Linux boot specific:\n"
3939
           "-kernel bzImage use 'bzImage' as kernel image\n"
3940
           "-append cmdline use 'cmdline' as kernel command line\n"
3941
           "-initrd file    use 'file' as initial ram disk\n"
3942
           "\n"
3943
           "Debug/Expert options:\n"
3944
           "-monitor dev    redirect the monitor to char device 'dev'\n"
3945
           "-serial dev     redirect the serial port to char device 'dev'\n"
3946
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
3947
           "-pidfile file   Write PID to 'file'\n"
3948
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
3949
           "-s              wait gdb connection to port\n"
3950
           "-p port         set gdb connection port [default=%s]\n"
3951
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
3952
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
3953
           "                translation (t=none or lba) (usually qemu can guess them)\n"
3954
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
3955
#ifdef USE_KQEMU
3956
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
3957
           "-no-kqemu       disable KQEMU kernel module usage\n"
3958
#endif
3959
#ifdef CONFIG_KVM
3960
           "-enable-kvm     enable KVM full virtualization support\n"
3961
#endif
3962
#ifdef TARGET_I386
3963
           "-no-acpi        disable ACPI\n"
3964
           "-no-hpet        disable HPET\n"
3965
#endif
3966
#ifdef CONFIG_CURSES
3967
           "-curses         use a curses/ncurses interface instead of SDL\n"
3968
#endif
3969
           "-no-reboot      exit instead of rebooting\n"
3970
           "-no-shutdown    stop before shutdown\n"
3971
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
3972
           "-vnc display    start a VNC server on display\n"
3973
#ifndef _WIN32
3974
           "-daemonize      daemonize QEMU after initializing\n"
3975
#endif
3976
           "-option-rom rom load a file, rom, into the option ROM space\n"
3977
#ifdef TARGET_SPARC
3978
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
3979
#endif
3980
           "-clock          force the use of the given methods for timer alarm.\n"
3981
           "                To see what timers are available use -clock ?\n"
3982
           "-startdate      select initial date of the clock\n"
3983
           "-icount [N|auto]\n"
3984
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
3985
           "\n"
3986
           "During emulation, the following keys are useful:\n"
3987
           "ctrl-alt-f      toggle full screen\n"
3988
           "ctrl-alt-n      switch to virtual console 'n'\n"
3989
           "ctrl-alt        toggle mouse and keyboard grab\n"
3990
           "\n"
3991
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
3992
           ,
3993
           "qemu",
3994
           DEFAULT_RAM_SIZE,
3995
#ifndef _WIN32
3996
           DEFAULT_NETWORK_SCRIPT,
3997
           DEFAULT_NETWORK_DOWN_SCRIPT,
3998
#endif
3999
           DEFAULT_GDBSTUB_PORT,
4000
           "/tmp/qemu.log");
4001
    exit(exitcode);
4002
}
4003

    
4004
#define HAS_ARG 0x0001
4005

    
4006
enum {
4007
    QEMU_OPTION_h,
4008

    
4009
    QEMU_OPTION_M,
4010
    QEMU_OPTION_cpu,
4011
    QEMU_OPTION_fda,
4012
    QEMU_OPTION_fdb,
4013
    QEMU_OPTION_hda,
4014
    QEMU_OPTION_hdb,
4015
    QEMU_OPTION_hdc,
4016
    QEMU_OPTION_hdd,
4017
    QEMU_OPTION_drive,
4018
    QEMU_OPTION_cdrom,
4019
    QEMU_OPTION_mtdblock,
4020
    QEMU_OPTION_sd,
4021
    QEMU_OPTION_pflash,
4022
    QEMU_OPTION_boot,
4023
    QEMU_OPTION_snapshot,
4024
#ifdef TARGET_I386
4025
    QEMU_OPTION_no_fd_bootchk,
4026
#endif
4027
    QEMU_OPTION_m,
4028
    QEMU_OPTION_nographic,
4029
    QEMU_OPTION_portrait,
4030
#ifdef HAS_AUDIO
4031
    QEMU_OPTION_audio_help,
4032
    QEMU_OPTION_soundhw,
4033
#endif
4034

    
4035
    QEMU_OPTION_net,
4036
    QEMU_OPTION_tftp,
4037
    QEMU_OPTION_bootp,
4038
    QEMU_OPTION_smb,
4039
    QEMU_OPTION_redir,
4040
    QEMU_OPTION_bt,
4041

    
4042
    QEMU_OPTION_kernel,
4043
    QEMU_OPTION_append,
4044
    QEMU_OPTION_initrd,
4045

    
4046
    QEMU_OPTION_S,
4047
    QEMU_OPTION_s,
4048
    QEMU_OPTION_p,
4049
    QEMU_OPTION_d,
4050
    QEMU_OPTION_hdachs,
4051
    QEMU_OPTION_L,
4052
    QEMU_OPTION_bios,
4053
    QEMU_OPTION_k,
4054
    QEMU_OPTION_localtime,
4055
    QEMU_OPTION_g,
4056
    QEMU_OPTION_vga,
4057
    QEMU_OPTION_echr,
4058
    QEMU_OPTION_monitor,
4059
    QEMU_OPTION_serial,
4060
    QEMU_OPTION_virtiocon,
4061
    QEMU_OPTION_parallel,
4062
    QEMU_OPTION_loadvm,
4063
    QEMU_OPTION_full_screen,
4064
    QEMU_OPTION_no_frame,
4065
    QEMU_OPTION_alt_grab,
4066
    QEMU_OPTION_no_quit,
4067
    QEMU_OPTION_pidfile,
4068
    QEMU_OPTION_no_kqemu,
4069
    QEMU_OPTION_kernel_kqemu,
4070
    QEMU_OPTION_enable_kvm,
4071
    QEMU_OPTION_win2k_hack,
4072
    QEMU_OPTION_rtc_td_hack,
4073
    QEMU_OPTION_usb,
4074
    QEMU_OPTION_usbdevice,
4075
    QEMU_OPTION_smp,
4076
    QEMU_OPTION_vnc,
4077
    QEMU_OPTION_no_acpi,
4078
    QEMU_OPTION_no_hpet,
4079
    QEMU_OPTION_curses,
4080
    QEMU_OPTION_no_reboot,
4081
    QEMU_OPTION_no_shutdown,
4082
    QEMU_OPTION_show_cursor,
4083
    QEMU_OPTION_daemonize,
4084
    QEMU_OPTION_option_rom,
4085
    QEMU_OPTION_semihosting,
4086
    QEMU_OPTION_name,
4087
    QEMU_OPTION_prom_env,
4088
    QEMU_OPTION_old_param,
4089
    QEMU_OPTION_clock,
4090
    QEMU_OPTION_startdate,
4091
    QEMU_OPTION_tb_size,
4092
    QEMU_OPTION_icount,
4093
    QEMU_OPTION_uuid,
4094
    QEMU_OPTION_incoming,
4095
};
4096

    
4097
typedef struct QEMUOption {
4098
    const char *name;
4099
    int flags;
4100
    int index;
4101
} QEMUOption;
4102

    
4103
static const QEMUOption qemu_options[] = {
4104
    { "h", 0, QEMU_OPTION_h },
4105
    { "help", 0, QEMU_OPTION_h },
4106

    
4107
    { "M", HAS_ARG, QEMU_OPTION_M },
4108
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4109
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4110
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4111
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4112
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4113
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4114
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4115
    { "drive", HAS_ARG, QEMU_OPTION_drive },
4116
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4117
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4118
    { "sd", HAS_ARG, QEMU_OPTION_sd },
4119
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4120
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4121
    { "snapshot", 0, QEMU_OPTION_snapshot },
4122
#ifdef TARGET_I386
4123
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4124
#endif
4125
    { "m", HAS_ARG, QEMU_OPTION_m },
4126
    { "nographic", 0, QEMU_OPTION_nographic },
4127
    { "portrait", 0, QEMU_OPTION_portrait },
4128
    { "k", HAS_ARG, QEMU_OPTION_k },
4129
#ifdef HAS_AUDIO
4130
    { "audio-help", 0, QEMU_OPTION_audio_help },
4131
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4132
#endif
4133

    
4134
    { "net", HAS_ARG, QEMU_OPTION_net},
4135
#ifdef CONFIG_SLIRP
4136
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4137
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4138
#ifndef _WIN32
4139
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4140
#endif
4141
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4142
#endif
4143
    { "bt", HAS_ARG, QEMU_OPTION_bt },
4144

    
4145
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4146
    { "append", HAS_ARG, QEMU_OPTION_append },
4147
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4148

    
4149
    { "S", 0, QEMU_OPTION_S },
4150
    { "s", 0, QEMU_OPTION_s },
4151
    { "p", HAS_ARG, QEMU_OPTION_p },
4152
    { "d", HAS_ARG, QEMU_OPTION_d },
4153
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4154
    { "L", HAS_ARG, QEMU_OPTION_L },
4155
    { "bios", HAS_ARG, QEMU_OPTION_bios },
4156
#ifdef USE_KQEMU
4157
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4158
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4159
#endif
4160
#ifdef CONFIG_KVM
4161
    { "enable-kvm", 0, QEMU_OPTION_enable_kvm },
4162
#endif
4163
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4164
    { "g", 1, QEMU_OPTION_g },
4165
#endif
4166
    { "localtime", 0, QEMU_OPTION_localtime },
4167
    { "vga", HAS_ARG, QEMU_OPTION_vga },
4168
    { "echr", HAS_ARG, QEMU_OPTION_echr },
4169
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4170
    { "serial", HAS_ARG, QEMU_OPTION_serial },
4171
    { "virtioconsole", HAS_ARG, QEMU_OPTION_virtiocon },
4172
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4173
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4174
    { "full-screen", 0, QEMU_OPTION_full_screen },
4175
#ifdef CONFIG_SDL
4176
    { "no-frame", 0, QEMU_OPTION_no_frame },
4177
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
4178
    { "no-quit", 0, QEMU_OPTION_no_quit },
4179
#endif
4180
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4181
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4182
    { "rtc-td-hack", 0, QEMU_OPTION_rtc_td_hack },
4183
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4184
    { "smp", HAS_ARG, QEMU_OPTION_smp },
4185
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
4186
#ifdef CONFIG_CURSES
4187
    { "curses", 0, QEMU_OPTION_curses },
4188
#endif
4189
    { "uuid", HAS_ARG, QEMU_OPTION_uuid },
4190

    
4191
    /* temporary options */
4192
    { "usb", 0, QEMU_OPTION_usb },
4193
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
4194
    { "no-hpet", 0, QEMU_OPTION_no_hpet },
4195
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
4196
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
4197
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
4198
    { "daemonize", 0, QEMU_OPTION_daemonize },
4199
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
4200
#if defined(TARGET_ARM) || defined(TARGET_M68K)
4201
    { "semihosting", 0, QEMU_OPTION_semihosting },
4202
#endif
4203
    { "name", HAS_ARG, QEMU_OPTION_name },
4204
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
4205
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
4206
#endif
4207
#if defined(TARGET_ARM)
4208
    { "old-param", 0, QEMU_OPTION_old_param },
4209
#endif
4210
    { "clock", HAS_ARG, QEMU_OPTION_clock },
4211
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
4212
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
4213
    { "icount", HAS_ARG, QEMU_OPTION_icount },
4214
    { "incoming", HAS_ARG, QEMU_OPTION_incoming },
4215
    { NULL },
4216
};
4217

    
4218
/* password input */
4219

    
4220
int qemu_key_check(BlockDriverState *bs, const char *name)
4221
{
4222
    char password[256];
4223
    int i;
4224

    
4225
    if (!bdrv_is_encrypted(bs))
4226
        return 0;
4227

    
4228
    term_printf("%s is encrypted.\n", name);
4229
    for(i = 0; i < 3; i++) {
4230
        monitor_readline("Password: ", 1, password, sizeof(password));
4231
        if (bdrv_set_key(bs, password) == 0)
4232
            return 0;
4233
        term_printf("invalid password\n");
4234
    }
4235
    return -EPERM;
4236
}
4237

    
4238
static BlockDriverState *get_bdrv(int index)
4239
{
4240
    if (index > nb_drives)
4241
        return NULL;
4242
    return drives_table[index].bdrv;
4243
}
4244

    
4245
static void read_passwords(void)
4246
{
4247
    BlockDriverState *bs;
4248
    int i;
4249

    
4250
    for(i = 0; i < 6; i++) {
4251
        bs = get_bdrv(i);
4252
        if (bs)
4253
            qemu_key_check(bs, bdrv_get_device_name(bs));
4254
    }
4255
}
4256

    
4257
#ifdef HAS_AUDIO
4258
struct soundhw soundhw[] = {
4259
#ifdef HAS_AUDIO_CHOICE
4260
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4261
    {
4262
        "pcspk",
4263
        "PC speaker",
4264
        0,
4265
        1,
4266
        { .init_isa = pcspk_audio_init }
4267
    },
4268
#endif
4269

    
4270
#ifdef CONFIG_SB16
4271
    {
4272
        "sb16",
4273
        "Creative Sound Blaster 16",
4274
        0,
4275
        1,
4276
        { .init_isa = SB16_init }
4277
    },
4278
#endif
4279

    
4280
#ifdef CONFIG_CS4231A
4281
    {
4282
        "cs4231a",
4283
        "CS4231A",
4284
        0,
4285
        1,
4286
        { .init_isa = cs4231a_init }
4287
    },
4288
#endif
4289

    
4290
#ifdef CONFIG_ADLIB
4291
    {
4292
        "adlib",
4293
#ifdef HAS_YMF262
4294
        "Yamaha YMF262 (OPL3)",
4295
#else
4296
        "Yamaha YM3812 (OPL2)",
4297
#endif
4298
        0,
4299
        1,
4300
        { .init_isa = Adlib_init }
4301
    },
4302
#endif
4303

    
4304
#ifdef CONFIG_GUS
4305
    {
4306
        "gus",
4307
        "Gravis Ultrasound GF1",
4308
        0,
4309
        1,
4310
        { .init_isa = GUS_init }
4311
    },
4312
#endif
4313

    
4314
#ifdef CONFIG_AC97
4315
    {
4316
        "ac97",
4317
        "Intel 82801AA AC97 Audio",
4318
        0,
4319
        0,
4320
        { .init_pci = ac97_init }
4321
    },
4322
#endif
4323

    
4324
#ifdef CONFIG_ES1370
4325
    {
4326
        "es1370",
4327
        "ENSONIQ AudioPCI ES1370",
4328
        0,
4329
        0,
4330
        { .init_pci = es1370_init }
4331
    },
4332
#endif
4333

    
4334
#endif /* HAS_AUDIO_CHOICE */
4335

    
4336
    { NULL, NULL, 0, 0, { NULL } }
4337
};
4338

    
4339
static void select_soundhw (const char *optarg)
4340
{
4341
    struct soundhw *c;
4342

    
4343
    if (*optarg == '?') {
4344
    show_valid_cards:
4345

    
4346
        printf ("Valid sound card names (comma separated):\n");
4347
        for (c = soundhw; c->name; ++c) {
4348
            printf ("%-11s %s\n", c->name, c->descr);
4349
        }
4350
        printf ("\n-soundhw all will enable all of the above\n");
4351
        exit (*optarg != '?');
4352
    }
4353
    else {
4354
        size_t l;
4355
        const char *p;
4356
        char *e;
4357
        int bad_card = 0;
4358

    
4359
        if (!strcmp (optarg, "all")) {
4360
            for (c = soundhw; c->name; ++c) {
4361
                c->enabled = 1;
4362
            }
4363
            return;
4364
        }
4365

    
4366
        p = optarg;
4367
        while (*p) {
4368
            e = strchr (p, ',');
4369
            l = !e ? strlen (p) : (size_t) (e - p);
4370

    
4371
            for (c = soundhw; c->name; ++c) {
4372
                if (!strncmp (c->name, p, l)) {
4373
                    c->enabled = 1;
4374
                    break;
4375
                }
4376
            }
4377

    
4378
            if (!c->name) {
4379
                if (l > 80) {
4380
                    fprintf (stderr,
4381
                             "Unknown sound card name (too big to show)\n");
4382
                }
4383
                else {
4384
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4385
                             (int) l, p);
4386
                }
4387
                bad_card = 1;
4388
            }
4389
            p += l + (e != NULL);
4390
        }
4391

    
4392
        if (bad_card)
4393
            goto show_valid_cards;
4394
    }
4395
}
4396
#endif
4397

    
4398
static void select_vgahw (const char *p)
4399
{
4400
    const char *opts;
4401

    
4402
    if (strstart(p, "std", &opts)) {
4403
        std_vga_enabled = 1;
4404
        cirrus_vga_enabled = 0;
4405
        vmsvga_enabled = 0;
4406
    } else if (strstart(p, "cirrus", &opts)) {
4407
        cirrus_vga_enabled = 1;
4408
        std_vga_enabled = 0;
4409
        vmsvga_enabled = 0;
4410
    } else if (strstart(p, "vmware", &opts)) {
4411
        cirrus_vga_enabled = 0;
4412
        std_vga_enabled = 0;
4413
        vmsvga_enabled = 1;
4414
    } else if (strstart(p, "none", &opts)) {
4415
        cirrus_vga_enabled = 0;
4416
        std_vga_enabled = 0;
4417
        vmsvga_enabled = 0;
4418
    } else {
4419
    invalid_vga:
4420
        fprintf(stderr, "Unknown vga type: %s\n", p);
4421
        exit(1);
4422
    }
4423
    while (*opts) {
4424
        const char *nextopt;
4425

    
4426
        if (strstart(opts, ",retrace=", &nextopt)) {
4427
            opts = nextopt;
4428
            if (strstart(opts, "dumb", &nextopt))
4429
                vga_retrace_method = VGA_RETRACE_DUMB;
4430
            else if (strstart(opts, "precise", &nextopt))
4431
                vga_retrace_method = VGA_RETRACE_PRECISE;
4432
            else goto invalid_vga;
4433
        } else goto invalid_vga;
4434
        opts = nextopt;
4435
    }
4436
}
4437

    
4438
#ifdef _WIN32
4439
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4440
{
4441
    exit(STATUS_CONTROL_C_EXIT);
4442
    return TRUE;
4443
}
4444
#endif
4445

    
4446
static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4447
{
4448
    int ret;
4449

    
4450
    if(strlen(str) != 36)
4451
        return -1;
4452

    
4453
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4454
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4455
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4456

    
4457
    if(ret != 16)
4458
        return -1;
4459

    
4460
    return 0;
4461
}
4462

    
4463
#define MAX_NET_CLIENTS 32
4464

    
4465
#ifndef _WIN32
4466

    
4467
static void termsig_handler(int signal)
4468
{
4469
    qemu_system_shutdown_request();
4470
}
4471

    
4472
static void termsig_setup(void)
4473
{
4474
    struct sigaction act;
4475

    
4476
    memset(&act, 0, sizeof(act));
4477
    act.sa_handler = termsig_handler;
4478
    sigaction(SIGINT,  &act, NULL);
4479
    sigaction(SIGHUP,  &act, NULL);
4480
    sigaction(SIGTERM, &act, NULL);
4481
}
4482

    
4483
#endif
4484

    
4485
int main(int argc, char **argv, char **envp)
4486
{
4487
#ifdef CONFIG_GDBSTUB
4488
    int use_gdbstub;
4489
    const char *gdbstub_port;
4490
#endif
4491
    uint32_t boot_devices_bitmap = 0;
4492
    int i;
4493
    int snapshot, linux_boot, net_boot;
4494
    const char *initrd_filename;
4495
    const char *kernel_filename, *kernel_cmdline;
4496
    const char *boot_devices = "";
4497
    DisplayState *ds = &display_state;
4498
    int cyls, heads, secs, translation;
4499
    const char *net_clients[MAX_NET_CLIENTS];
4500
    int nb_net_clients;
4501
    const char *bt_opts[MAX_BT_CMDLINE];
4502
    int nb_bt_opts;
4503
    int hda_index;
4504
    int optind;
4505
    const char *r, *optarg;
4506
    CharDriverState *monitor_hd;
4507
    const char *monitor_device;
4508
    const char *serial_devices[MAX_SERIAL_PORTS];
4509
    int serial_device_index;
4510
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4511
    int parallel_device_index;
4512
    const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4513
    int virtio_console_index;
4514
    const char *loadvm = NULL;
4515
    QEMUMachine *machine;
4516
    const char *cpu_model;
4517
    const char *usb_devices[MAX_USB_CMDLINE];
4518
    int usb_devices_index;
4519
    int fds[2];
4520
    int tb_size;
4521
    const char *pid_file = NULL;
4522
    int autostart;
4523
    const char *incoming = NULL;
4524

    
4525
    qemu_cache_utils_init(envp);
4526

    
4527
    LIST_INIT (&vm_change_state_head);
4528
#ifndef _WIN32
4529
    {
4530
        struct sigaction act;
4531
        sigfillset(&act.sa_mask);
4532
        act.sa_flags = 0;
4533
        act.sa_handler = SIG_IGN;
4534
        sigaction(SIGPIPE, &act, NULL);
4535
    }
4536
#else
4537
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4538
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4539
       QEMU to run on a single CPU */
4540
    {
4541
        HANDLE h;
4542
        DWORD mask, smask;
4543
        int i;
4544
        h = GetCurrentProcess();
4545
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4546
            for(i = 0; i < 32; i++) {
4547
                if (mask & (1 << i))
4548
                    break;
4549
            }
4550
            if (i != 32) {
4551
                mask = 1 << i;
4552
                SetProcessAffinityMask(h, mask);
4553
            }
4554
        }
4555
    }
4556
#endif
4557

    
4558
    register_machines();
4559
    machine = first_machine;
4560
    cpu_model = NULL;
4561
    initrd_filename = NULL;
4562
    ram_size = 0;
4563
    vga_ram_size = VGA_RAM_SIZE;
4564
#ifdef CONFIG_GDBSTUB
4565
    use_gdbstub = 0;
4566
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
4567
#endif
4568
    snapshot = 0;
4569
    nographic = 0;
4570
    curses = 0;
4571
    kernel_filename = NULL;
4572
    kernel_cmdline = "";
4573
    cyls = heads = secs = 0;
4574
    translation = BIOS_ATA_TRANSLATION_AUTO;
4575
    monitor_device = "vc";
4576

    
4577
    serial_devices[0] = "vc:80Cx24C";
4578
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4579
        serial_devices[i] = NULL;
4580
    serial_device_index = 0;
4581

    
4582
    parallel_devices[0] = "vc:640x480";
4583
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4584
        parallel_devices[i] = NULL;
4585
    parallel_device_index = 0;
4586

    
4587
    virtio_consoles[0] = "vc:80Cx24C";
4588
    for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4589
        virtio_consoles[i] = NULL;
4590
    virtio_console_index = 0;
4591

    
4592
    usb_devices_index = 0;
4593

    
4594
    nb_net_clients = 0;
4595
    nb_bt_opts = 0;
4596
    nb_drives = 0;
4597
    nb_drives_opt = 0;
4598
    hda_index = -1;
4599

    
4600
    nb_nics = 0;
4601

    
4602
    tb_size = 0;
4603
    autostart= 1;
4604

    
4605
    optind = 1;
4606
    for(;;) {
4607
        if (optind >= argc)
4608
            break;
4609
        r = argv[optind];
4610
        if (r[0] != '-') {
4611
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4612
        } else {
4613
            const QEMUOption *popt;
4614

    
4615
            optind++;
4616
            /* Treat --foo the same as -foo.  */
4617
            if (r[1] == '-')
4618
                r++;
4619
            popt = qemu_options;
4620
            for(;;) {
4621
                if (!popt->name) {
4622
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4623
                            argv[0], r);
4624
                    exit(1);
4625
                }
4626
                if (!strcmp(popt->name, r + 1))
4627
                    break;
4628
                popt++;
4629
            }
4630
            if (popt->flags & HAS_ARG) {
4631
                if (optind >= argc) {
4632
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4633
                            argv[0], r);
4634
                    exit(1);
4635
                }
4636
                optarg = argv[optind++];
4637
            } else {
4638
                optarg = NULL;
4639
            }
4640

    
4641
            switch(popt->index) {
4642
            case QEMU_OPTION_M:
4643
                machine = find_machine(optarg);
4644
                if (!machine) {
4645
                    QEMUMachine *m;
4646
                    printf("Supported machines are:\n");
4647
                    for(m = first_machine; m != NULL; m = m->next) {
4648
                        printf("%-10s %s%s\n",
4649
                               m->name, m->desc,
4650
                               m == first_machine ? " (default)" : "");
4651
                    }
4652
                    exit(*optarg != '?');
4653
                }
4654
                break;
4655
            case QEMU_OPTION_cpu:
4656
                /* hw initialization will check this */
4657
                if (*optarg == '?') {
4658
/* XXX: implement xxx_cpu_list for targets that still miss it */
4659
#if defined(cpu_list)
4660
                    cpu_list(stdout, &fprintf);
4661
#endif
4662
                    exit(0);
4663
                } else {
4664
                    cpu_model = optarg;
4665
                }
4666
                break;
4667
            case QEMU_OPTION_initrd:
4668
                initrd_filename = optarg;
4669
                break;
4670
            case QEMU_OPTION_hda:
4671
                if (cyls == 0)
4672
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
4673
                else
4674
                    hda_index = drive_add(optarg, HD_ALIAS
4675
                             ",cyls=%d,heads=%d,secs=%d%s",
4676
                             0, cyls, heads, secs,
4677
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4678
                                 ",trans=lba" :
4679
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4680
                                 ",trans=none" : "");
4681
                 break;
4682
            case QEMU_OPTION_hdb:
4683
            case QEMU_OPTION_hdc:
4684
            case QEMU_OPTION_hdd:
4685
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4686
                break;
4687
            case QEMU_OPTION_drive:
4688
                drive_add(NULL, "%s", optarg);
4689
                break;
4690
            case QEMU_OPTION_mtdblock:
4691
                drive_add(optarg, MTD_ALIAS);
4692
                break;
4693
            case QEMU_OPTION_sd:
4694
                drive_add(optarg, SD_ALIAS);
4695
                break;
4696
            case QEMU_OPTION_pflash:
4697
                drive_add(optarg, PFLASH_ALIAS);
4698
                break;
4699
            case QEMU_OPTION_snapshot:
4700
                snapshot = 1;
4701
                break;
4702
            case QEMU_OPTION_hdachs:
4703
                {
4704
                    const char *p;
4705
                    p = optarg;
4706
                    cyls = strtol(p, (char **)&p, 0);
4707
                    if (cyls < 1 || cyls > 16383)
4708
                        goto chs_fail;
4709
                    if (*p != ',')
4710
                        goto chs_fail;
4711
                    p++;
4712
                    heads = strtol(p, (char **)&p, 0);
4713
                    if (heads < 1 || heads > 16)
4714
                        goto chs_fail;
4715
                    if (*p != ',')
4716
                        goto chs_fail;
4717
                    p++;
4718
                    secs = strtol(p, (char **)&p, 0);
4719
                    if (secs < 1 || secs > 63)
4720
                        goto chs_fail;
4721
                    if (*p == ',') {
4722
                        p++;
4723
                        if (!strcmp(p, "none"))
4724
                            translation = BIOS_ATA_TRANSLATION_NONE;
4725
                        else if (!strcmp(p, "lba"))
4726
                            translation = BIOS_ATA_TRANSLATION_LBA;
4727
                        else if (!strcmp(p, "auto"))
4728
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4729
                        else
4730
                            goto chs_fail;
4731
                    } else if (*p != '\0') {
4732
                    chs_fail:
4733
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4734
                        exit(1);
4735
                    }
4736
                    if (hda_index != -1)
4737
                        snprintf(drives_opt[hda_index].opt,
4738
                                 sizeof(drives_opt[hda_index].opt),
4739
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4740
                                 0, cyls, heads, secs,
4741
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
4742
                                         ",trans=lba" :
4743
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
4744
                                     ",trans=none" : "");
4745
                }
4746
                break;
4747
            case QEMU_OPTION_nographic:
4748
                nographic = 1;
4749
                break;
4750
#ifdef CONFIG_CURSES
4751
            case QEMU_OPTION_curses:
4752
                curses = 1;
4753
                break;
4754
#endif
4755
            case QEMU_OPTION_portrait:
4756
                graphic_rotate = 1;
4757
                break;
4758
            case QEMU_OPTION_kernel:
4759
                kernel_filename = optarg;
4760
                break;
4761
            case QEMU_OPTION_append:
4762
                kernel_cmdline = optarg;
4763
                break;
4764
            case QEMU_OPTION_cdrom:
4765
                drive_add(optarg, CDROM_ALIAS);
4766
                break;
4767
            case QEMU_OPTION_boot:
4768
                boot_devices = optarg;
4769
                /* We just do some generic consistency checks */
4770
                {
4771
                    /* Could easily be extended to 64 devices if needed */
4772
                    const char *p;
4773
                    
4774
                    boot_devices_bitmap = 0;
4775
                    for (p = boot_devices; *p != '\0'; p++) {
4776
                        /* Allowed boot devices are:
4777
                         * a b     : floppy disk drives
4778
                         * c ... f : IDE disk drives
4779
                         * g ... m : machine implementation dependant drives
4780
                         * n ... p : network devices
4781
                         * It's up to each machine implementation to check
4782
                         * if the given boot devices match the actual hardware
4783
                         * implementation and firmware features.
4784
                         */
4785
                        if (*p < 'a' || *p > 'q') {
4786
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
4787
                            exit(1);
4788
                        }
4789
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4790
                            fprintf(stderr,
4791
                                    "Boot device '%c' was given twice\n",*p);
4792
                            exit(1);
4793
                        }
4794
                        boot_devices_bitmap |= 1 << (*p - 'a');
4795
                    }
4796
                }
4797
                break;
4798
            case QEMU_OPTION_fda:
4799
            case QEMU_OPTION_fdb:
4800
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4801
                break;
4802
#ifdef TARGET_I386
4803
            case QEMU_OPTION_no_fd_bootchk:
4804
                fd_bootchk = 0;
4805
                break;
4806
#endif
4807
            case QEMU_OPTION_net:
4808
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4809
                    fprintf(stderr, "qemu: too many network clients\n");
4810
                    exit(1);
4811
                }
4812
                net_clients[nb_net_clients] = optarg;
4813
                nb_net_clients++;
4814
                break;
4815
#ifdef CONFIG_SLIRP
4816
            case QEMU_OPTION_tftp:
4817
                tftp_prefix = optarg;
4818
                break;
4819
            case QEMU_OPTION_bootp:
4820
                bootp_filename = optarg;
4821
                break;
4822
#ifndef _WIN32
4823
            case QEMU_OPTION_smb:
4824
                net_slirp_smb(optarg);
4825
                break;
4826
#endif
4827
            case QEMU_OPTION_redir:
4828
                net_slirp_redir(optarg);
4829
                break;
4830
#endif
4831
            case QEMU_OPTION_bt:
4832
                if (nb_bt_opts >= MAX_BT_CMDLINE) {
4833
                    fprintf(stderr, "qemu: too many bluetooth options\n");
4834
                    exit(1);
4835
                }
4836
                bt_opts[nb_bt_opts++] = optarg;
4837
                break;
4838
#ifdef HAS_AUDIO
4839
            case QEMU_OPTION_audio_help:
4840
                AUD_help ();
4841
                exit (0);
4842
                break;
4843
            case QEMU_OPTION_soundhw:
4844
                select_soundhw (optarg);
4845
                break;
4846
#endif
4847
            case QEMU_OPTION_h:
4848
                help(0);
4849
                break;
4850
            case QEMU_OPTION_m: {
4851
                uint64_t value;
4852
                char *ptr;
4853

    
4854
                value = strtoul(optarg, &ptr, 10);
4855
                switch (*ptr) {
4856
                case 0: case 'M': case 'm':
4857
                    value <<= 20;
4858
                    break;
4859
                case 'G': case 'g':
4860
                    value <<= 30;
4861
                    break;
4862
                default:
4863
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4864
                    exit(1);
4865
                }
4866

    
4867
                /* On 32-bit hosts, QEMU is limited by virtual address space */
4868
                if (value > (2047 << 20)
4869
#ifndef USE_KQEMU
4870
                    && HOST_LONG_BITS == 32
4871
#endif
4872
                    ) {
4873
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4874
                    exit(1);
4875
                }
4876
                if (value != (uint64_t)(ram_addr_t)value) {
4877
                    fprintf(stderr, "qemu: ram size too large\n");
4878
                    exit(1);
4879
                }
4880
                ram_size = value;
4881
                break;
4882
            }
4883
            case QEMU_OPTION_d:
4884
                {
4885
                    int mask;
4886
                    const CPULogItem *item;
4887

    
4888
                    mask = cpu_str_to_log_mask(optarg);
4889
                    if (!mask) {
4890
                        printf("Log items (comma separated):\n");
4891
                    for(item = cpu_log_items; item->mask != 0; item++) {
4892
                        printf("%-10s %s\n", item->name, item->help);
4893
                    }
4894
                    exit(1);
4895
                    }
4896
                    cpu_set_log(mask);
4897
                }
4898
                break;
4899
#ifdef CONFIG_GDBSTUB
4900
            case QEMU_OPTION_s:
4901
                use_gdbstub = 1;
4902
                break;
4903
            case QEMU_OPTION_p:
4904
                gdbstub_port = optarg;
4905
                break;
4906
#endif
4907
            case QEMU_OPTION_L:
4908
                bios_dir = optarg;
4909
                break;
4910
            case QEMU_OPTION_bios:
4911
                bios_name = optarg;
4912
                break;
4913
            case QEMU_OPTION_S:
4914
                autostart = 0;
4915
                break;
4916
            case QEMU_OPTION_k:
4917
                keyboard_layout = optarg;
4918
                break;
4919
            case QEMU_OPTION_localtime:
4920
                rtc_utc = 0;
4921
                break;
4922
            case QEMU_OPTION_vga:
4923
                select_vgahw (optarg);
4924
                break;
4925
            case QEMU_OPTION_g:
4926
                {
4927
                    const char *p;
4928
                    int w, h, depth;
4929
                    p = optarg;
4930
                    w = strtol(p, (char **)&p, 10);
4931
                    if (w <= 0) {
4932
                    graphic_error:
4933
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
4934
                        exit(1);
4935
                    }
4936
                    if (*p != 'x')
4937
                        goto graphic_error;
4938
                    p++;
4939
                    h = strtol(p, (char **)&p, 10);
4940
                    if (h <= 0)
4941
                        goto graphic_error;
4942
                    if (*p == 'x') {
4943
                        p++;
4944
                        depth = strtol(p, (char **)&p, 10);
4945
                        if (depth != 8 && depth != 15 && depth != 16 &&
4946
                            depth != 24 && depth != 32)
4947
                            goto graphic_error;
4948
                    } else if (*p == '\0') {
4949
                        depth = graphic_depth;
4950
                    } else {
4951
                        goto graphic_error;
4952
                    }
4953

    
4954
                    graphic_width = w;
4955
                    graphic_height = h;
4956
                    graphic_depth = depth;
4957
                }
4958
                break;
4959
            case QEMU_OPTION_echr:
4960
                {
4961
                    char *r;
4962
                    term_escape_char = strtol(optarg, &r, 0);
4963
                    if (r == optarg)
4964
                        printf("Bad argument to echr\n");
4965
                    break;
4966
                }
4967
            case QEMU_OPTION_monitor:
4968
                monitor_device = optarg;
4969
                break;
4970
            case QEMU_OPTION_serial:
4971
                if (serial_device_index >= MAX_SERIAL_PORTS) {
4972
                    fprintf(stderr, "qemu: too many serial ports\n");
4973
                    exit(1);
4974
                }
4975
                serial_devices[serial_device_index] = optarg;
4976
                serial_device_index++;
4977
                break;
4978
            case QEMU_OPTION_virtiocon:
4979
                if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4980
                    fprintf(stderr, "qemu: too many virtio consoles\n");
4981
                    exit(1);
4982
                }
4983
                virtio_consoles[virtio_console_index] = optarg;
4984
                virtio_console_index++;
4985
                break;
4986
            case QEMU_OPTION_parallel:
4987
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4988
                    fprintf(stderr, "qemu: too many parallel ports\n");
4989
                    exit(1);
4990
                }
4991
                parallel_devices[parallel_device_index] = optarg;
4992
                parallel_device_index++;
4993
                break;
4994
            case QEMU_OPTION_loadvm:
4995
                loadvm = optarg;
4996
                break;
4997
            case QEMU_OPTION_full_screen:
4998
                full_screen = 1;
4999
                break;
5000
#ifdef CONFIG_SDL
5001
            case QEMU_OPTION_no_frame:
5002
                no_frame = 1;
5003
                break;
5004
            case QEMU_OPTION_alt_grab:
5005
                alt_grab = 1;
5006
                break;
5007
            case QEMU_OPTION_no_quit:
5008
                no_quit = 1;
5009
                break;
5010
#endif
5011
            case QEMU_OPTION_pidfile:
5012
                pid_file = optarg;
5013
                break;
5014
#ifdef TARGET_I386
5015
            case QEMU_OPTION_win2k_hack:
5016
                win2k_install_hack = 1;
5017
                break;
5018
            case QEMU_OPTION_rtc_td_hack:
5019
                rtc_td_hack = 1;
5020
                break;
5021
#endif
5022
#ifdef USE_KQEMU
5023
            case QEMU_OPTION_no_kqemu:
5024
                kqemu_allowed = 0;
5025
                break;
5026
            case QEMU_OPTION_kernel_kqemu:
5027
                kqemu_allowed = 2;
5028
                break;
5029
#endif
5030
#ifdef CONFIG_KVM
5031
            case QEMU_OPTION_enable_kvm:
5032
                kvm_allowed = 1;
5033
#ifdef USE_KQEMU
5034
                kqemu_allowed = 0;
5035
#endif
5036
                break;
5037
#endif
5038
            case QEMU_OPTION_usb:
5039
                usb_enabled = 1;
5040
                break;
5041
            case QEMU_OPTION_usbdevice:
5042
                usb_enabled = 1;
5043
                if (usb_devices_index >= MAX_USB_CMDLINE) {
5044
                    fprintf(stderr, "Too many USB devices\n");
5045
                    exit(1);
5046
                }
5047
                usb_devices[usb_devices_index] = optarg;
5048
                usb_devices_index++;
5049
                break;
5050
            case QEMU_OPTION_smp:
5051
                smp_cpus = atoi(optarg);
5052
                if (smp_cpus < 1) {
5053
                    fprintf(stderr, "Invalid number of CPUs\n");
5054
                    exit(1);
5055
                }
5056
                break;
5057
            case QEMU_OPTION_vnc:
5058
                vnc_display = optarg;
5059
                break;
5060
            case QEMU_OPTION_no_acpi:
5061
                acpi_enabled = 0;
5062
                break;
5063
            case QEMU_OPTION_no_hpet:
5064
                no_hpet = 1;
5065
                break;
5066
            case QEMU_OPTION_no_reboot:
5067
                no_reboot = 1;
5068
                break;
5069
            case QEMU_OPTION_no_shutdown:
5070
                no_shutdown = 1;
5071
                break;
5072
            case QEMU_OPTION_show_cursor:
5073
                cursor_hide = 0;
5074
                break;
5075
            case QEMU_OPTION_uuid:
5076
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5077
                    fprintf(stderr, "Fail to parse UUID string."
5078
                            " Wrong format.\n");
5079
                    exit(1);
5080
                }
5081
                break;
5082
            case QEMU_OPTION_daemonize:
5083
                daemonize = 1;
5084
                break;
5085
            case QEMU_OPTION_option_rom:
5086
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5087
                    fprintf(stderr, "Too many option ROMs\n");
5088
                    exit(1);
5089
                }
5090
                option_rom[nb_option_roms] = optarg;
5091
                nb_option_roms++;
5092
                break;
5093
            case QEMU_OPTION_semihosting:
5094
                semihosting_enabled = 1;
5095
                break;
5096
            case QEMU_OPTION_name:
5097
                qemu_name = optarg;
5098
                break;
5099
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
5100
            case QEMU_OPTION_prom_env:
5101
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5102
                    fprintf(stderr, "Too many prom variables\n");
5103
                    exit(1);
5104
                }
5105
                prom_envs[nb_prom_envs] = optarg;
5106
                nb_prom_envs++;
5107
                break;
5108
#endif
5109
#ifdef TARGET_ARM
5110
            case QEMU_OPTION_old_param:
5111
                old_param = 1;
5112
                break;
5113
#endif
5114
            case QEMU_OPTION_clock:
5115
                configure_alarms(optarg);
5116
                break;
5117
            case QEMU_OPTION_startdate:
5118
                {
5119
                    struct tm tm;
5120
                    time_t rtc_start_date;
5121
                    if (!strcmp(optarg, "now")) {
5122
                        rtc_date_offset = -1;
5123
                    } else {
5124
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5125
                               &tm.tm_year,
5126
                               &tm.tm_mon,
5127
                               &tm.tm_mday,
5128
                               &tm.tm_hour,
5129
                               &tm.tm_min,
5130
                               &tm.tm_sec) == 6) {
5131
                            /* OK */
5132
                        } else if (sscanf(optarg, "%d-%d-%d",
5133
                                          &tm.tm_year,
5134
                                          &tm.tm_mon,
5135
                                          &tm.tm_mday) == 3) {
5136
                            tm.tm_hour = 0;
5137
                            tm.tm_min = 0;
5138
                            tm.tm_sec = 0;
5139
                        } else {
5140
                            goto date_fail;
5141
                        }
5142
                        tm.tm_year -= 1900;
5143
                        tm.tm_mon--;
5144
                        rtc_start_date = mktimegm(&tm);
5145
                        if (rtc_start_date == -1) {
5146
                        date_fail:
5147
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
5148
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5149
                            exit(1);
5150
                        }
5151
                        rtc_date_offset = time(NULL) - rtc_start_date;
5152
                    }
5153
                }
5154
                break;
5155
            case QEMU_OPTION_tb_size:
5156
                tb_size = strtol(optarg, NULL, 0);
5157
                if (tb_size < 0)
5158
                    tb_size = 0;
5159
                break;
5160
            case QEMU_OPTION_icount:
5161
                use_icount = 1;
5162
                if (strcmp(optarg, "auto") == 0) {
5163
                    icount_time_shift = -1;
5164
                } else {
5165
                    icount_time_shift = strtol(optarg, NULL, 0);
5166
                }
5167
                break;
5168
            case QEMU_OPTION_incoming:
5169
                incoming = optarg;
5170
                break;
5171
            }
5172
        }
5173
    }
5174

    
5175
#if defined(CONFIG_KVM) && defined(USE_KQEMU)
5176
    if (kvm_allowed && kqemu_allowed) {
5177
        fprintf(stderr,
5178
                "You can not enable both KVM and kqemu at the same time\n");
5179
        exit(1);
5180
    }
5181
#endif
5182

    
5183
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5184
    if (smp_cpus > machine->max_cpus) {
5185
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5186
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5187
                machine->max_cpus);
5188
        exit(1);
5189
    }
5190

    
5191
    if (nographic) {
5192
       if (serial_device_index == 0)
5193
           serial_devices[0] = "stdio";
5194
       if (parallel_device_index == 0)
5195
           parallel_devices[0] = "null";
5196
       if (strncmp(monitor_device, "vc", 2) == 0)
5197
           monitor_device = "stdio";
5198
       if (virtio_console_index == 0)
5199
           virtio_consoles[0] = "null";
5200
    }
5201

    
5202
#ifndef _WIN32
5203
    if (daemonize) {
5204
        pid_t pid;
5205

    
5206
        if (pipe(fds) == -1)
5207
            exit(1);
5208

    
5209
        pid = fork();
5210
        if (pid > 0) {
5211
            uint8_t status;
5212
            ssize_t len;
5213

    
5214
            close(fds[1]);
5215

    
5216
        again:
5217
            len = read(fds[0], &status, 1);
5218
            if (len == -1 && (errno == EINTR))
5219
                goto again;
5220

    
5221
            if (len != 1)
5222
                exit(1);
5223
            else if (status == 1) {
5224
                fprintf(stderr, "Could not acquire pidfile\n");
5225
                exit(1);
5226
            } else
5227
                exit(0);
5228
        } else if (pid < 0)
5229
            exit(1);
5230

    
5231
        setsid();
5232

    
5233
        pid = fork();
5234
        if (pid > 0)
5235
            exit(0);
5236
        else if (pid < 0)
5237
            exit(1);
5238

    
5239
        umask(027);
5240

    
5241
        signal(SIGTSTP, SIG_IGN);
5242
        signal(SIGTTOU, SIG_IGN);
5243
        signal(SIGTTIN, SIG_IGN);
5244
    }
5245
#endif
5246

    
5247
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5248
        if (daemonize) {
5249
            uint8_t status = 1;
5250
            write(fds[1], &status, 1);
5251
        } else
5252
            fprintf(stderr, "Could not acquire pid file\n");
5253
        exit(1);
5254
    }
5255

    
5256
#ifdef USE_KQEMU
5257
    if (smp_cpus > 1)
5258
        kqemu_allowed = 0;
5259
#endif
5260
    linux_boot = (kernel_filename != NULL);
5261
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5262

    
5263
    if (!linux_boot && net_boot == 0 &&
5264
        !machine->nodisk_ok && nb_drives_opt == 0)
5265
        help(1);
5266

    
5267
    if (!linux_boot && *kernel_cmdline != '\0') {
5268
        fprintf(stderr, "-append only allowed with -kernel option\n");
5269
        exit(1);
5270
    }
5271

    
5272
    if (!linux_boot && initrd_filename != NULL) {
5273
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5274
        exit(1);
5275
    }
5276

    
5277
    /* boot to floppy or the default cd if no hard disk defined yet */
5278
    if (!boot_devices[0]) {
5279
        boot_devices = "cad";
5280
    }
5281
    setvbuf(stdout, NULL, _IOLBF, 0);
5282

    
5283
    init_timers();
5284
    if (init_timer_alarm() < 0) {
5285
        fprintf(stderr, "could not initialize alarm timer\n");
5286
        exit(1);
5287
    }
5288
    if (use_icount && icount_time_shift < 0) {
5289
        use_icount = 2;
5290
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5291
           It will be corrected fairly quickly anyway.  */
5292
        icount_time_shift = 3;
5293
        init_icount_adjust();
5294
    }
5295

    
5296
#ifdef _WIN32
5297
    socket_init();
5298
#endif
5299

    
5300
    /* init network clients */
5301
    if (nb_net_clients == 0) {
5302
        /* if no clients, we use a default config */
5303
        net_clients[nb_net_clients++] = "nic";
5304
#ifdef CONFIG_SLIRP
5305
        net_clients[nb_net_clients++] = "user";
5306
#endif
5307
    }
5308

    
5309
    for(i = 0;i < nb_net_clients; i++) {
5310
        if (net_client_parse(net_clients[i]) < 0)
5311
            exit(1);
5312
    }
5313
    net_client_check();
5314

    
5315
#ifdef TARGET_I386
5316
    /* XXX: this should be moved in the PC machine instantiation code */
5317
    if (net_boot != 0) {
5318
        int netroms = 0;
5319
        for (i = 0; i < nb_nics && i < 4; i++) {
5320
            const char *model = nd_table[i].model;
5321
            char buf[1024];
5322
            if (net_boot & (1 << i)) {
5323
                if (model == NULL)
5324
                    model = "ne2k_pci";
5325
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5326
                if (get_image_size(buf) > 0) {
5327
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
5328
                        fprintf(stderr, "Too many option ROMs\n");
5329
                        exit(1);
5330
                    }
5331
                    option_rom[nb_option_roms] = strdup(buf);
5332
                    nb_option_roms++;
5333
                    netroms++;
5334
                }
5335
            }
5336
        }
5337
        if (netroms == 0) {
5338
            fprintf(stderr, "No valid PXE rom found for network device\n");
5339
            exit(1);
5340
        }
5341
    }
5342
#endif
5343

    
5344
    /* init the bluetooth world */
5345
    for (i = 0; i < nb_bt_opts; i++)
5346
        if (bt_parse(bt_opts[i]))
5347
            exit(1);
5348

    
5349
    /* init the memory */
5350
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5351

    
5352
    if (machine->ram_require & RAMSIZE_FIXED) {
5353
        if (ram_size > 0) {
5354
            if (ram_size < phys_ram_size) {
5355
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5356
                                machine->name, (unsigned long long) phys_ram_size);
5357
                exit(-1);
5358
            }
5359

    
5360
            phys_ram_size = ram_size;
5361
        } else
5362
            ram_size = phys_ram_size;
5363
    } else {
5364
        if (ram_size == 0)
5365
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5366

    
5367
        phys_ram_size += ram_size;
5368
    }
5369

    
5370
    phys_ram_base = qemu_vmalloc(phys_ram_size);
5371
    if (!phys_ram_base) {
5372
        fprintf(stderr, "Could not allocate physical memory\n");
5373
        exit(1);
5374
    }
5375

    
5376
    /* init the dynamic translator */
5377
    cpu_exec_init_all(tb_size * 1024 * 1024);
5378

    
5379
    bdrv_init();
5380

    
5381
    /* we always create the cdrom drive, even if no disk is there */
5382

    
5383
    if (nb_drives_opt < MAX_DRIVES)
5384
        drive_add(NULL, CDROM_ALIAS);
5385

    
5386
    /* we always create at least one floppy */
5387

    
5388
    if (nb_drives_opt < MAX_DRIVES)
5389
        drive_add(NULL, FD_ALIAS, 0);
5390

    
5391
    /* we always create one sd slot, even if no card is in it */
5392

    
5393
    if (nb_drives_opt < MAX_DRIVES)
5394
        drive_add(NULL, SD_ALIAS);
5395

    
5396
    /* open the virtual block devices */
5397

    
5398
    for(i = 0; i < nb_drives_opt; i++)
5399
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5400
            exit(1);
5401

    
5402
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5403
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5404

    
5405
    /* terminal init */
5406
    memset(&display_state, 0, sizeof(display_state));
5407
    if (nographic) {
5408
        if (curses) {
5409
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5410
            exit(1);
5411
        }
5412
        /* nearly nothing to do */
5413
        dumb_display_init(ds);
5414
    } else if (vnc_display != NULL) {
5415
        vnc_display_init(ds);
5416
        if (vnc_display_open(ds, vnc_display) < 0)
5417
            exit(1);
5418
    } else
5419
#if defined(CONFIG_CURSES)
5420
    if (curses) {
5421
        curses_display_init(ds, full_screen);
5422
    } else
5423
#endif
5424
    {
5425
#if defined(CONFIG_SDL)
5426
        sdl_display_init(ds, full_screen, no_frame);
5427
#elif defined(CONFIG_COCOA)
5428
        cocoa_display_init(ds, full_screen);
5429
#else
5430
        dumb_display_init(ds);
5431
#endif
5432
    }
5433

    
5434
#ifndef _WIN32
5435
    /* must be after terminal init, SDL library changes signal handlers */
5436
    termsig_setup();
5437
#endif
5438

    
5439
    /* Maintain compatibility with multiple stdio monitors */
5440
    if (!strcmp(monitor_device,"stdio")) {
5441
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5442
            const char *devname = serial_devices[i];
5443
            if (devname && !strcmp(devname,"mon:stdio")) {
5444
                monitor_device = NULL;
5445
                break;
5446
            } else if (devname && !strcmp(devname,"stdio")) {
5447
                monitor_device = NULL;
5448
                serial_devices[i] = "mon:stdio";
5449
                break;
5450
            }
5451
        }
5452
    }
5453
    if (monitor_device) {
5454
        monitor_hd = qemu_chr_open("monitor", monitor_device);
5455
        if (!monitor_hd) {
5456
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5457
            exit(1);
5458
        }
5459
        monitor_init(monitor_hd, !nographic);
5460
    }
5461

    
5462
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5463
        const char *devname = serial_devices[i];
5464
        if (devname && strcmp(devname, "none")) {
5465
            char label[32];
5466
            snprintf(label, sizeof(label), "serial%d", i);
5467
            serial_hds[i] = qemu_chr_open(label, devname);
5468
            if (!serial_hds[i]) {
5469
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5470
                        devname);
5471
                exit(1);
5472
            }
5473
            if (strstart(devname, "vc", 0))
5474
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5475
        }
5476
    }
5477

    
5478
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5479
        const char *devname = parallel_devices[i];
5480
        if (devname && strcmp(devname, "none")) {
5481
            char label[32];
5482
            snprintf(label, sizeof(label), "parallel%d", i);
5483
            parallel_hds[i] = qemu_chr_open(label, devname);
5484
            if (!parallel_hds[i]) {
5485
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5486
                        devname);
5487
                exit(1);
5488
            }
5489
            if (strstart(devname, "vc", 0))
5490
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5491
        }
5492
    }
5493

    
5494
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5495
        const char *devname = virtio_consoles[i];
5496
        if (devname && strcmp(devname, "none")) {
5497
            char label[32];
5498
            snprintf(label, sizeof(label), "virtcon%d", i);
5499
            virtcon_hds[i] = qemu_chr_open(label, devname);
5500
            if (!virtcon_hds[i]) {
5501
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5502
                        devname);
5503
                exit(1);
5504
            }
5505
            if (strstart(devname, "vc", 0))
5506
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5507
        }
5508
    }
5509

    
5510
    if (kvm_enabled()) {
5511
        int ret;
5512

    
5513
        ret = kvm_init(smp_cpus);
5514
        if (ret < 0) {
5515
            fprintf(stderr, "failed to initialize KVM\n");
5516
            exit(1);
5517
        }
5518
    }
5519

    
5520
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
5521
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5522

    
5523
    /* Set KVM's vcpu state to qemu's initial CPUState. */
5524
    if (kvm_enabled()) {
5525
        int ret;
5526

    
5527
        ret = kvm_sync_vcpus();
5528
        if (ret < 0) {
5529
            fprintf(stderr, "failed to initialize vcpus\n");
5530
            exit(1);
5531
        }
5532
    }
5533

    
5534
    /* init USB devices */
5535
    if (usb_enabled) {
5536
        for(i = 0; i < usb_devices_index; i++) {
5537
            if (usb_device_add(usb_devices[i]) < 0) {
5538
                fprintf(stderr, "Warning: could not add USB device %s\n",
5539
                        usb_devices[i]);
5540
            }
5541
        }
5542
    }
5543

    
5544
    if (display_state.dpy_refresh) {
5545
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5546
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5547
    }
5548

    
5549
#ifdef CONFIG_GDBSTUB
5550
    if (use_gdbstub) {
5551
        /* XXX: use standard host:port notation and modify options
5552
           accordingly. */
5553
        if (gdbserver_start(gdbstub_port) < 0) {
5554
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5555
                    gdbstub_port);
5556
            exit(1);
5557
        }
5558
    }
5559
#endif
5560

    
5561
    if (loadvm)
5562
        do_loadvm(loadvm);
5563

    
5564
    if (incoming) {
5565
        autostart = 0; /* fixme how to deal with -daemonize */
5566
        qemu_start_incoming_migration(incoming);
5567
    }
5568

    
5569
    {
5570
        /* XXX: simplify init */
5571
        read_passwords();
5572
        if (autostart) {
5573
            vm_start();
5574
        }
5575
    }
5576

    
5577
    if (daemonize) {
5578
        uint8_t status = 0;
5579
        ssize_t len;
5580
        int fd;
5581

    
5582
    again1:
5583
        len = write(fds[1], &status, 1);
5584
        if (len == -1 && (errno == EINTR))
5585
            goto again1;
5586

    
5587
        if (len != 1)
5588
            exit(1);
5589

    
5590
        chdir("/");
5591
        TFR(fd = open("/dev/null", O_RDWR));
5592
        if (fd == -1)
5593
            exit(1);
5594

    
5595
        dup2(fd, 0);
5596
        dup2(fd, 1);
5597
        dup2(fd, 2);
5598

    
5599
        close(fd);
5600
    }
5601

    
5602
    main_loop();
5603
    quit_timers();
5604
    net_cleanup();
5605

    
5606
    return 0;
5607
}