Statistics
| Branch: | Revision:

root / vl.c @ 93fcfe39

History | View | Annotate | Download (150.1 kB)

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

    
164
#ifdef TARGET_PPC
165
#define DEFAULT_RAM_SIZE 144
166
#else
167
#define DEFAULT_RAM_SIZE 128
168
#endif
169

    
170
/* Max number of USB devices that can be specified on the commandline.  */
171
#define MAX_USB_CMDLINE 8
172

    
173
/* Max number of bluetooth switches on the commandline.  */
174
#define MAX_BT_CMDLINE 10
175

    
176
/* XXX: use a two level table to limit memory usage */
177
#define MAX_IOPORTS 65536
178

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

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

    
267
uint8_t qemu_uuid[16];
268

    
269
/***********************************************************/
270
/* x86 ISA bus support */
271

    
272
target_phys_addr_t isa_mem_base = 0;
273
PicState2 *isa_pic;
274

    
275
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
276
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
277

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

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

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

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

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

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

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

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

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

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

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

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

    
401
void isa_unassign_ioport(int start, int length)
402
{
403
    int i;
404

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

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

    
416
/***********************************************************/
417

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

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

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

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

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

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

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

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

    
509
static QEMUBalloonEvent *qemu_balloon_event;
510
void *qemu_balloon_event_opaque;
511

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

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

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

    
531
/***********************************************************/
532
/* keyboard/mouse */
533

    
534
static QEMUPutKBDEvent *qemu_put_kbd_event;
535
static void *qemu_put_kbd_event_opaque;
536
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
537
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
538

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

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

    
551
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
552
    if (!s)
553
        return NULL;
554

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

    
561
    if (!qemu_put_mouse_event_head) {
562
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
563
        return s;
564
    }
565

    
566
    cursor = qemu_put_mouse_event_head;
567
    while (cursor->next != NULL)
568
        cursor = cursor->next;
569

    
570
    cursor->next = s;
571
    qemu_put_mouse_event_current = s;
572

    
573
    return s;
574
}
575

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

    
580
    if (!qemu_put_mouse_event_head || entry == NULL)
581
        return;
582

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

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

    
600
    prev->next = entry->next;
601

    
602
    if (qemu_put_mouse_event_current == entry)
603
        qemu_put_mouse_event_current = prev;
604

    
605
    qemu_free(entry->qemu_put_mouse_event_name);
606
    qemu_free(entry);
607
}
608

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

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

    
622
    if (!qemu_put_mouse_event_current) {
623
        return;
624
    }
625

    
626
    mouse_event =
627
        qemu_put_mouse_event_current->qemu_put_mouse_event;
628
    mouse_event_opaque =
629
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
630

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

    
645
int kbd_mouse_is_absolute(void)
646
{
647
    if (!qemu_put_mouse_event_current)
648
        return 0;
649

    
650
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
651
}
652

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

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

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

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

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

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

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

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

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

    
720
/***********************************************************/
721
/* real time host monotonic timer */
722

    
723
#define QEMU_TIMER_BASE 1000000000LL
724

    
725
#ifdef WIN32
726

    
727
static int64_t clock_freq;
728

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

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

    
748
#else
749

    
750
static int use_rt_clock;
751

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

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

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

    
798
/***********************************************************/
799
/* guest cycle counter */
800

    
801
static int64_t cpu_ticks_prev;
802
static int64_t cpu_ticks_offset;
803
static int64_t cpu_clock_offset;
804
static int cpu_ticks_enabled;
805

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

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

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

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

    
860
/***********************************************************/
861
/* timers */
862

    
863
#define QEMU_TIMER_REALTIME 0
864
#define QEMU_TIMER_VIRTUAL  1
865

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

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

    
879
struct qemu_alarm_timer {
880
    char const *name;
881
    unsigned int flags;
882

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

    
889
#define ALARM_FLAG_DYNTICKS  0x1
890
#define ALARM_FLAG_EXPIRED   0x2
891

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

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

    
902
    t->rearm(t);
903
}
904

    
905
/* TODO: MIN_TIMER_REARM_US should be optimized */
906
#define MIN_TIMER_REARM_US 250
907

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

    
913
#ifdef _WIN32
914

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

    
921
static int win32_start_timer(struct qemu_alarm_timer *t);
922
static void win32_stop_timer(struct qemu_alarm_timer *t);
923
static void win32_rearm_timer(struct qemu_alarm_timer *t);
924

    
925
#else
926

    
927
static int unix_start_timer(struct qemu_alarm_timer *t);
928
static void unix_stop_timer(struct qemu_alarm_timer *t);
929

    
930
#ifdef __linux__
931

    
932
static int dynticks_start_timer(struct qemu_alarm_timer *t);
933
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
934
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
935

    
936
static int hpet_start_timer(struct qemu_alarm_timer *t);
937
static void hpet_stop_timer(struct qemu_alarm_timer *t);
938

    
939
static int rtc_start_timer(struct qemu_alarm_timer *t);
940
static void rtc_stop_timer(struct qemu_alarm_timer *t);
941

    
942
#endif /* __linux__ */
943

    
944
#endif /* _WIN32 */
945

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

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

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

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

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

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

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

    
1031
static void show_available_alarms(void)
1032
{
1033
    int i;
1034

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

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

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

    
1054
    arg = strdup(opt);
1055

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

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

    
1069
        if (i < cur)
1070
            /* Ignore */
1071
            goto next;
1072

    
1073
        /* Swap */
1074
        tmp = alarm_timers[i];
1075
        alarm_timers[i] = alarm_timers[cur];
1076
        alarm_timers[cur] = tmp;
1077

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

    
1083
    free(arg);
1084

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

    
1095
QEMUClock *rt_clock;
1096
QEMUClock *vm_clock;
1097

    
1098
static QEMUTimer *active_timers[2];
1099

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

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

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

    
1121
void qemu_free_timer(QEMUTimer *ts)
1122
{
1123
    qemu_free(ts);
1124
}
1125

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

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

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

    
1152
    qemu_del_timer(ts);
1153

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1355
static int64_t qemu_next_deadline(void)
1356
{
1357
    int64_t delta;
1358

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

    
1367
    if (delta < 0)
1368
        delta = 0;
1369

    
1370
    return delta;
1371
}
1372

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

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

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

    
1391
    if (delta < MIN_TIMER_REARM_US)
1392
        delta = MIN_TIMER_REARM_US;
1393

    
1394
    return delta;
1395
}
1396
#endif
1397

    
1398
#ifndef _WIN32
1399

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

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

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

    
1412
    return 0;
1413
}
1414

    
1415
#if defined(__linux__)
1416

    
1417
#define RTC_FREQ 1024
1418

    
1419
static void enable_sigio_timer(int fd)
1420
{
1421
    struct sigaction act;
1422

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

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

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

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

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

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

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

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

    
1466
    enable_sigio_timer(fd);
1467
    t->priv = (void *)(long)fd;
1468

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

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

    
1479
    close(fd);
1480
}
1481

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

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

    
1504
    enable_sigio_timer(rtc_fd);
1505

    
1506
    t->priv = (void *)(long)rtc_fd;
1507

    
1508
    return 0;
1509
}
1510

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

    
1515
    close(rtc_fd);
1516
}
1517

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

    
1524
    sigfillset(&act.sa_mask);
1525
    act.sa_flags = 0;
1526
    act.sa_handler = host_alarm_handler;
1527

    
1528
    sigaction(SIGALRM, &act, NULL);
1529

    
1530
    ev.sigev_value.sival_int = 0;
1531
    ev.sigev_notify = SIGEV_SIGNAL;
1532
    ev.sigev_signo = SIGALRM;
1533

    
1534
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1535
        perror("timer_create");
1536

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

    
1540
        return -1;
1541
    }
1542

    
1543
    t->priv = (void *)(long)host_timer;
1544

    
1545
    return 0;
1546
}
1547

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

    
1552
    timer_delete(host_timer);
1553
}
1554

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

    
1562
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1563
                !active_timers[QEMU_TIMER_VIRTUAL])
1564
        return;
1565

    
1566
    nearest_delta_us = qemu_next_deadline_dyntick();
1567

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

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

    
1589
#endif /* defined(__linux__) */
1590

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

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

    
1602
    sigaction(SIGALRM, &act, NULL);
1603

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

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

    
1614
    return 0;
1615
}
1616

    
1617
static void unix_stop_timer(struct qemu_alarm_timer *t)
1618
{
1619
    struct itimerval itv;
1620

    
1621
    memset(&itv, 0, sizeof(itv));
1622
    setitimer(ITIMER_REAL, &itv, NULL);
1623
}
1624

    
1625
#endif /* !defined(_WIN32) */
1626

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

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

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

    
1646
#ifdef _WIN32
1647

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

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

    
1660
    memset(&tc, 0, sizeof(tc));
1661
    timeGetDevCaps(&tc, sizeof(tc));
1662

    
1663
    if (data->period < tc.wPeriodMin)
1664
        data->period = tc.wPeriodMin;
1665

    
1666
    timeBeginPeriod(data->period);
1667

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

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

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

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

    
1688
    qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1689

    
1690
    return 0;
1691
}
1692

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

    
1697
    timeKillEvent(data->timerId);
1698
    timeEndPeriod(data->period);
1699

    
1700
    CloseHandle(data->host_alarm);
1701
}
1702

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

    
1708
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1709
                !active_timers[QEMU_TIMER_VIRTUAL])
1710
        return;
1711

    
1712
    nearest_delta_us = qemu_next_deadline_dyntick();
1713
    nearest_delta_us /= 1000;
1714

    
1715
    timeKillEvent(data->timerId);
1716

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

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

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

    
1732
#endif /* _WIN32 */
1733

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

    
1739
#ifndef _WIN32
1740
    int fds[2];
1741

    
1742
    err = pipe(fds);
1743
    if (err == -1)
1744
        return -errno;
1745

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

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

    
1754
    alarm_timer_rfd = fds[0];
1755
    alarm_timer_wfd = fds[1];
1756
#endif
1757

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

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

    
1766
    if (err) {
1767
        err = -ENOENT;
1768
        goto fail;
1769
    }
1770

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

    
1776
    alarm_timer = t;
1777

    
1778
    return 0;
1779

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

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

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

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

    
1813
    memcpy(tm, ret, sizeof(struct tm));
1814
}
1815

    
1816
int qemu_timedate_diff(struct tm *tm)
1817
{
1818
    time_t seconds;
1819

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

    
1828
    return seconds - time(NULL);
1829
}
1830

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

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

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

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

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

    
1866
    return p;
1867
}
1868

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

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

    
1887
    return p;
1888
}
1889

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

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

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

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

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

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

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

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

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

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

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

    
1990
    return hci_table[cur_hci++];
1991
}
1992

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

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

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

    
2020
    return 0;
2021
}
2022

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

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

    
2033
    hci = hci_init(str);
2034
    if (!hci)
2035
        return -1;
2036

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

    
2045
    hci_table[nb_hcis++] = hci;
2046

    
2047
    return 0;
2048
}
2049

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

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

    
2058
    bt_vhci_init(bt_new_hci(vlan));
2059
}
2060

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

    
2069
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
2070

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

    
2079
    vlan = qemu_find_bt_vlan(vlan_id);
2080

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

    
2085
    if (!strcmp(devname, "keyboard"))
2086
        return bt_keyboard_init(vlan);
2087

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

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

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

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

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

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

    
2131
/***********************************************************/
2132
/* QEMU Block devices */
2133

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

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

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

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

    
2160
    return nb_drives_opt++;
2161
}
2162

    
2163
int drive_get_index(BlockInterfaceType type, int bus, int unit)
2164
{
2165
    int index;
2166

    
2167
    /* seek interface, bus and unit */
2168

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

    
2175
    return -1;
2176
}
2177

    
2178
int drive_get_max_bus(BlockInterfaceType type)
2179
{
2180
    int max_bus;
2181
    int index;
2182

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

    
2192
const char *drive_get_serial(BlockDriverState *bdrv)
2193
{
2194
    int index;
2195

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

    
2200
    return "\0";
2201
}
2202

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

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

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

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

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

    
2257
    /* extract parameters */
2258

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2417
    if (!get_param_value(serial, sizeof(serial), "serial", str))
2418
            memset(serial, 0,  sizeof(serial));
2419

    
2420
    /* compute bus and unit according index */
2421

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

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

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

    
2453
    /* check unit id */
2454

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

    
2461
    /*
2462
     * ignore multiple definitions
2463
     */
2464

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

    
2468
    /* init */
2469

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

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

    
2533
/***********************************************************/
2534
/* USB devices */
2535

    
2536
static USBPort *used_usb_ports;
2537
static USBPort *free_usb_ports;
2538

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

    
2550
int usb_device_add_dev(USBDevice *dev)
2551
{
2552
    USBPort *port;
2553

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

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

    
2564
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2565
        usb_attach(port, hub);
2566
        port = free_usb_ports;
2567
    }
2568

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

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

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

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

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

    
2618
    return usb_device_add_dev(dev);
2619
}
2620

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

    
2627
    if (!used_usb_ports)
2628
        return -1;
2629

    
2630
    if (bus_num != 0)
2631
        return -1;
2632

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

    
2640
    if (!port)
2641
        return -1;
2642

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

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

    
2657
    if (strstart(devname, "host:", &p))
2658
        return usb_host_device_close(p);
2659

    
2660
    if (!used_usb_ports)
2661
        return -1;
2662

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

    
2669
    return usb_device_del_addr(bus_num, addr);
2670
}
2671

    
2672
void do_usb_add(const char *devname)
2673
{
2674
    usb_device_add(devname);
2675
}
2676

    
2677
void do_usb_del(const char *devname)
2678
{
2679
    usb_device_del(devname);
2680
}
2681

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

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

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

    
2716
/***********************************************************/
2717
/* PCMCIA/Cardbus */
2718

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

    
2724
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2725
{
2726
    struct pcmcia_socket_entry_s *entry;
2727

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

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

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

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

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

    
2758
/***********************************************************/
2759
/* dumb display */
2760

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

    
2765
static void dumb_resize(DisplayState *ds)
2766
{
2767
}
2768

    
2769
static void dumb_display_init(DisplayState *ds)
2770
{
2771
    DisplayChangeListener *dcl = qemu_mallocz(sizeof(DisplayChangeListener));
2772
    if (!dcl)
2773
        exit(1);
2774
    dcl->dpy_update = dumb_update;
2775
    dcl->dpy_resize = dumb_resize;
2776
    dcl->dpy_refresh = NULL;
2777
    dcl->idle = 1;
2778
    dcl->gui_timer_interval = 500;
2779
    register_displaychangelistener(ds, dcl);
2780
}
2781

    
2782
/***********************************************************/
2783
/* I/O handling */
2784

    
2785
#define MAX_IO_HANDLERS 64
2786

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

    
2799
static IOHandlerRecord *first_io_handler;
2800

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

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

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

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

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

    
2862
static PollingEntry *first_polling_entry;
2863

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

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

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

    
2899
static WaitObjects wait_objects = {0};
2900

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

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

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

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

    
2934
/***********************************************************/
2935
/* ram save/restore */
2936

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

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

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

    
2958
    return 0;
2959
}
2960

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

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

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

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

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

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

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

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

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

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

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

    
3044
    return 1;
3045
}
3046

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

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

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

    
3062
            ch = *(phys_ram_base + current_addr);
3063

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

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

    
3079
    return found;
3080
}
3081

    
3082
static ram_addr_t ram_save_threshold = 10;
3083

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

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

    
3094
    return count;
3095
}
3096

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

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

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

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

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

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

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

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

    
3131
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3132

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

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

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

    
3162
    return 0;
3163
}
3164

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

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

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

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

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

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

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

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

    
3205
    return 0;
3206
}
3207

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

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

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

    
3233
static QEMUBH *first_bh = NULL;
3234

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

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

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

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

    
3275
    return ret;
3276
}
3277

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

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

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

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

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

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

    
3330
/***********************************************************/
3331
/* machine registration */
3332

    
3333
static QEMUMachine *first_machine = NULL;
3334

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

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

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

    
3357
/***********************************************************/
3358
/* main execution loop */
3359

    
3360
static void gui_update(void *opaque)
3361
{
3362
    uint64_t interval = GUI_REFRESH_INTERVAL;
3363
    DisplayState *ds = opaque;
3364
    DisplayChangeListener *dcl = ds->listeners;
3365

    
3366
    dpy_refresh(ds);
3367

    
3368
    while (dcl != NULL) {
3369
        if (dcl->gui_timer_interval &&
3370
            dcl->gui_timer_interval < interval)
3371
            interval = dcl->gui_timer_interval;
3372
        dcl = dcl->next;
3373
    }
3374
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3375
}
3376

    
3377
struct vm_change_state_entry {
3378
    VMChangeStateHandler *cb;
3379
    void *opaque;
3380
    LIST_ENTRY (vm_change_state_entry) entries;
3381
};
3382

    
3383
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3384

    
3385
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3386
                                                     void *opaque)
3387
{
3388
    VMChangeStateEntry *e;
3389

    
3390
    e = qemu_mallocz(sizeof (*e));
3391
    if (!e)
3392
        return NULL;
3393

    
3394
    e->cb = cb;
3395
    e->opaque = opaque;
3396
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3397
    return e;
3398
}
3399

    
3400
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3401
{
3402
    LIST_REMOVE (e, entries);
3403
    qemu_free (e);
3404
}
3405

    
3406
static void vm_state_notify(int running)
3407
{
3408
    VMChangeStateEntry *e;
3409

    
3410
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3411
        e->cb(e->opaque, running);
3412
    }
3413
}
3414

    
3415
/* XXX: support several handlers */
3416
static VMStopHandler *vm_stop_cb;
3417
static void *vm_stop_opaque;
3418

    
3419
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
3420
{
3421
    vm_stop_cb = cb;
3422
    vm_stop_opaque = opaque;
3423
    return 0;
3424
}
3425

    
3426
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
3427
{
3428
    vm_stop_cb = NULL;
3429
}
3430

    
3431
void vm_start(void)
3432
{
3433
    if (!vm_running) {
3434
        cpu_enable_ticks();
3435
        vm_running = 1;
3436
        vm_state_notify(1);
3437
        qemu_rearm_alarm_timer(alarm_timer);
3438
    }
3439
}
3440

    
3441
void vm_stop(int reason)
3442
{
3443
    if (vm_running) {
3444
        cpu_disable_ticks();
3445
        vm_running = 0;
3446
        if (reason != 0) {
3447
            if (vm_stop_cb) {
3448
                vm_stop_cb(vm_stop_opaque, reason);
3449
            }
3450
        }
3451
        vm_state_notify(0);
3452
    }
3453
}
3454

    
3455
/* reset/shutdown handler */
3456

    
3457
typedef struct QEMUResetEntry {
3458
    QEMUResetHandler *func;
3459
    void *opaque;
3460
    struct QEMUResetEntry *next;
3461
} QEMUResetEntry;
3462

    
3463
static QEMUResetEntry *first_reset_entry;
3464
static int reset_requested;
3465
static int shutdown_requested;
3466
static int powerdown_requested;
3467

    
3468
int qemu_shutdown_requested(void)
3469
{
3470
    int r = shutdown_requested;
3471
    shutdown_requested = 0;
3472
    return r;
3473
}
3474

    
3475
int qemu_reset_requested(void)
3476
{
3477
    int r = reset_requested;
3478
    reset_requested = 0;
3479
    return r;
3480
}
3481

    
3482
int qemu_powerdown_requested(void)
3483
{
3484
    int r = powerdown_requested;
3485
    powerdown_requested = 0;
3486
    return r;
3487
}
3488

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

    
3493
    pre = &first_reset_entry;
3494
    while (*pre != NULL)
3495
        pre = &(*pre)->next;
3496
    re = qemu_mallocz(sizeof(QEMUResetEntry));
3497
    re->func = func;
3498
    re->opaque = opaque;
3499
    re->next = NULL;
3500
    *pre = re;
3501
}
3502

    
3503
void qemu_system_reset(void)
3504
{
3505
    QEMUResetEntry *re;
3506

    
3507
    /* reset all devices */
3508
    for(re = first_reset_entry; re != NULL; re = re->next) {
3509
        re->func(re->opaque);
3510
    }
3511
}
3512

    
3513
void qemu_system_reset_request(void)
3514
{
3515
    if (no_reboot) {
3516
        shutdown_requested = 1;
3517
    } else {
3518
        reset_requested = 1;
3519
    }
3520
    if (cpu_single_env)
3521
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3522
}
3523

    
3524
void qemu_system_shutdown_request(void)
3525
{
3526
    shutdown_requested = 1;
3527
    if (cpu_single_env)
3528
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3529
}
3530

    
3531
void qemu_system_powerdown_request(void)
3532
{
3533
    powerdown_requested = 1;
3534
    if (cpu_single_env)
3535
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
3536
}
3537

    
3538
#ifdef _WIN32
3539
static void host_main_loop_wait(int *timeout)
3540
{
3541
    int ret, ret2, i;
3542
    PollingEntry *pe;
3543

    
3544

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

    
3554
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3555
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3556
            if (w->func[ret - WAIT_OBJECT_0])
3557
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3558

    
3559
            /* Check for additional signaled events */
3560
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3561

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

    
3580
    *timeout = 0;
3581
}
3582
#else
3583
static void host_main_loop_wait(int *timeout)
3584
{
3585
}
3586
#endif
3587

    
3588
void main_loop_wait(int timeout)
3589
{
3590
    IOHandlerRecord *ioh;
3591
    fd_set rfds, wfds, xfds;
3592
    int ret, nfds;
3593
    struct timeval tv;
3594

    
3595
    qemu_bh_update_timeout(&timeout);
3596

    
3597
    host_main_loop_wait(&timeout);
3598

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

    
3622
    tv.tv_sec = timeout / 1000;
3623
    tv.tv_usec = (timeout % 1000) * 1000;
3624

    
3625
#if defined(CONFIG_SLIRP)
3626
    if (slirp_is_inited()) {
3627
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3628
    }
3629
#endif
3630
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3631
    if (ret > 0) {
3632
        IOHandlerRecord **pioh;
3633

    
3634
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3635
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3636
                ioh->fd_read(ioh->opaque);
3637
            }
3638
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3639
                ioh->fd_write(ioh->opaque);
3640
            }
3641
        }
3642

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

    
3665
    /* vm time timers */
3666
    if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3667
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3668
                        qemu_get_clock(vm_clock));
3669

    
3670
    /* real time timers */
3671
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3672
                    qemu_get_clock(rt_clock));
3673

    
3674
    /* Check bottom-halves last in case any of the earlier events triggered
3675
       them.  */
3676
    qemu_bh_poll();
3677

    
3678
}
3679

    
3680
static int main_loop(void)
3681
{
3682
    int ret, timeout;
3683
#ifdef CONFIG_PROFILER
3684
    int64_t ti;
3685
#endif
3686
    CPUState *env;
3687

    
3688
    cur_cpu = first_cpu;
3689
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
3690
    for(;;) {
3691
        if (vm_running) {
3692

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

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

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

    
4010
#define HAS_ARG 0x0001
4011

    
4012
enum {
4013
    QEMU_OPTION_h,
4014

    
4015
    QEMU_OPTION_M,
4016
    QEMU_OPTION_cpu,
4017
    QEMU_OPTION_fda,
4018
    QEMU_OPTION_fdb,
4019
    QEMU_OPTION_hda,
4020
    QEMU_OPTION_hdb,
4021
    QEMU_OPTION_hdc,
4022
    QEMU_OPTION_hdd,
4023
    QEMU_OPTION_drive,
4024
    QEMU_OPTION_cdrom,
4025
    QEMU_OPTION_mtdblock,
4026
    QEMU_OPTION_sd,
4027
    QEMU_OPTION_pflash,
4028
    QEMU_OPTION_boot,
4029
    QEMU_OPTION_snapshot,
4030
#ifdef TARGET_I386
4031
    QEMU_OPTION_no_fd_bootchk,
4032
#endif
4033
    QEMU_OPTION_m,
4034
    QEMU_OPTION_nographic,
4035
    QEMU_OPTION_portrait,
4036
#ifdef HAS_AUDIO
4037
    QEMU_OPTION_audio_help,
4038
    QEMU_OPTION_soundhw,
4039
#endif
4040

    
4041
    QEMU_OPTION_net,
4042
    QEMU_OPTION_tftp,
4043
    QEMU_OPTION_bootp,
4044
    QEMU_OPTION_smb,
4045
    QEMU_OPTION_redir,
4046
    QEMU_OPTION_bt,
4047

    
4048
    QEMU_OPTION_kernel,
4049
    QEMU_OPTION_append,
4050
    QEMU_OPTION_initrd,
4051

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

    
4104
typedef struct QEMUOption {
4105
    const char *name;
4106
    int flags;
4107
    int index;
4108
} QEMUOption;
4109

    
4110
static const QEMUOption qemu_options[] = {
4111
    { "h", 0, QEMU_OPTION_h },
4112
    { "help", 0, QEMU_OPTION_h },
4113

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

    
4141
    { "net", HAS_ARG, QEMU_OPTION_net},
4142
#ifdef CONFIG_SLIRP
4143
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4144
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4145
#ifndef _WIN32
4146
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4147
#endif
4148
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4149
#endif
4150
    { "bt", HAS_ARG, QEMU_OPTION_bt },
4151

    
4152
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4153
    { "append", HAS_ARG, QEMU_OPTION_append },
4154
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4155

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

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

    
4226
/* password input */
4227

    
4228
int qemu_key_check(BlockDriverState *bs, const char *name)
4229
{
4230
    char password[256];
4231
    int i;
4232

    
4233
    if (!bdrv_is_encrypted(bs))
4234
        return 0;
4235

    
4236
    term_printf("%s is encrypted.\n", name);
4237
    for(i = 0; i < 3; i++) {
4238
        monitor_readline("Password: ", 1, password, sizeof(password));
4239
        if (bdrv_set_key(bs, password) == 0)
4240
            return 0;
4241
        term_printf("invalid password\n");
4242
    }
4243
    return -EPERM;
4244
}
4245

    
4246
static BlockDriverState *get_bdrv(int index)
4247
{
4248
    if (index > nb_drives)
4249
        return NULL;
4250
    return drives_table[index].bdrv;
4251
}
4252

    
4253
static void read_passwords(void)
4254
{
4255
    BlockDriverState *bs;
4256
    int i;
4257

    
4258
    for(i = 0; i < 6; i++) {
4259
        bs = get_bdrv(i);
4260
        if (bs)
4261
            qemu_key_check(bs, bdrv_get_device_name(bs));
4262
    }
4263
}
4264

    
4265
#ifdef HAS_AUDIO
4266
struct soundhw soundhw[] = {
4267
#ifdef HAS_AUDIO_CHOICE
4268
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4269
    {
4270
        "pcspk",
4271
        "PC speaker",
4272
        0,
4273
        1,
4274
        { .init_isa = pcspk_audio_init }
4275
    },
4276
#endif
4277

    
4278
#ifdef CONFIG_SB16
4279
    {
4280
        "sb16",
4281
        "Creative Sound Blaster 16",
4282
        0,
4283
        1,
4284
        { .init_isa = SB16_init }
4285
    },
4286
#endif
4287

    
4288
#ifdef CONFIG_CS4231A
4289
    {
4290
        "cs4231a",
4291
        "CS4231A",
4292
        0,
4293
        1,
4294
        { .init_isa = cs4231a_init }
4295
    },
4296
#endif
4297

    
4298
#ifdef CONFIG_ADLIB
4299
    {
4300
        "adlib",
4301
#ifdef HAS_YMF262
4302
        "Yamaha YMF262 (OPL3)",
4303
#else
4304
        "Yamaha YM3812 (OPL2)",
4305
#endif
4306
        0,
4307
        1,
4308
        { .init_isa = Adlib_init }
4309
    },
4310
#endif
4311

    
4312
#ifdef CONFIG_GUS
4313
    {
4314
        "gus",
4315
        "Gravis Ultrasound GF1",
4316
        0,
4317
        1,
4318
        { .init_isa = GUS_init }
4319
    },
4320
#endif
4321

    
4322
#ifdef CONFIG_AC97
4323
    {
4324
        "ac97",
4325
        "Intel 82801AA AC97 Audio",
4326
        0,
4327
        0,
4328
        { .init_pci = ac97_init }
4329
    },
4330
#endif
4331

    
4332
#ifdef CONFIG_ES1370
4333
    {
4334
        "es1370",
4335
        "ENSONIQ AudioPCI ES1370",
4336
        0,
4337
        0,
4338
        { .init_pci = es1370_init }
4339
    },
4340
#endif
4341

    
4342
#endif /* HAS_AUDIO_CHOICE */
4343

    
4344
    { NULL, NULL, 0, 0, { NULL } }
4345
};
4346

    
4347
static void select_soundhw (const char *optarg)
4348
{
4349
    struct soundhw *c;
4350

    
4351
    if (*optarg == '?') {
4352
    show_valid_cards:
4353

    
4354
        printf ("Valid sound card names (comma separated):\n");
4355
        for (c = soundhw; c->name; ++c) {
4356
            printf ("%-11s %s\n", c->name, c->descr);
4357
        }
4358
        printf ("\n-soundhw all will enable all of the above\n");
4359
        exit (*optarg != '?');
4360
    }
4361
    else {
4362
        size_t l;
4363
        const char *p;
4364
        char *e;
4365
        int bad_card = 0;
4366

    
4367
        if (!strcmp (optarg, "all")) {
4368
            for (c = soundhw; c->name; ++c) {
4369
                c->enabled = 1;
4370
            }
4371
            return;
4372
        }
4373

    
4374
        p = optarg;
4375
        while (*p) {
4376
            e = strchr (p, ',');
4377
            l = !e ? strlen (p) : (size_t) (e - p);
4378

    
4379
            for (c = soundhw; c->name; ++c) {
4380
                if (!strncmp (c->name, p, l)) {
4381
                    c->enabled = 1;
4382
                    break;
4383
                }
4384
            }
4385

    
4386
            if (!c->name) {
4387
                if (l > 80) {
4388
                    fprintf (stderr,
4389
                             "Unknown sound card name (too big to show)\n");
4390
                }
4391
                else {
4392
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4393
                             (int) l, p);
4394
                }
4395
                bad_card = 1;
4396
            }
4397
            p += l + (e != NULL);
4398
        }
4399

    
4400
        if (bad_card)
4401
            goto show_valid_cards;
4402
    }
4403
}
4404
#endif
4405

    
4406
static void select_vgahw (const char *p)
4407
{
4408
    const char *opts;
4409

    
4410
    if (strstart(p, "std", &opts)) {
4411
        std_vga_enabled = 1;
4412
        cirrus_vga_enabled = 0;
4413
        vmsvga_enabled = 0;
4414
    } else if (strstart(p, "cirrus", &opts)) {
4415
        cirrus_vga_enabled = 1;
4416
        std_vga_enabled = 0;
4417
        vmsvga_enabled = 0;
4418
    } else if (strstart(p, "vmware", &opts)) {
4419
        cirrus_vga_enabled = 0;
4420
        std_vga_enabled = 0;
4421
        vmsvga_enabled = 1;
4422
    } else if (strstart(p, "none", &opts)) {
4423
        cirrus_vga_enabled = 0;
4424
        std_vga_enabled = 0;
4425
        vmsvga_enabled = 0;
4426
    } else {
4427
    invalid_vga:
4428
        fprintf(stderr, "Unknown vga type: %s\n", p);
4429
        exit(1);
4430
    }
4431
    while (*opts) {
4432
        const char *nextopt;
4433

    
4434
        if (strstart(opts, ",retrace=", &nextopt)) {
4435
            opts = nextopt;
4436
            if (strstart(opts, "dumb", &nextopt))
4437
                vga_retrace_method = VGA_RETRACE_DUMB;
4438
            else if (strstart(opts, "precise", &nextopt))
4439
                vga_retrace_method = VGA_RETRACE_PRECISE;
4440
            else goto invalid_vga;
4441
        } else goto invalid_vga;
4442
        opts = nextopt;
4443
    }
4444
}
4445

    
4446
#ifdef _WIN32
4447
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4448
{
4449
    exit(STATUS_CONTROL_C_EXIT);
4450
    return TRUE;
4451
}
4452
#endif
4453

    
4454
static int qemu_uuid_parse(const char *str, uint8_t *uuid)
4455
{
4456
    int ret;
4457

    
4458
    if(strlen(str) != 36)
4459
        return -1;
4460

    
4461
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4462
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4463
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4464

    
4465
    if(ret != 16)
4466
        return -1;
4467

    
4468
    return 0;
4469
}
4470

    
4471
#define MAX_NET_CLIENTS 32
4472

    
4473
#ifndef _WIN32
4474

    
4475
static void termsig_handler(int signal)
4476
{
4477
    qemu_system_shutdown_request();
4478
}
4479

    
4480
static void termsig_setup(void)
4481
{
4482
    struct sigaction act;
4483

    
4484
    memset(&act, 0, sizeof(act));
4485
    act.sa_handler = termsig_handler;
4486
    sigaction(SIGINT,  &act, NULL);
4487
    sigaction(SIGHUP,  &act, NULL);
4488
    sigaction(SIGTERM, &act, NULL);
4489
}
4490

    
4491
#endif
4492

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

    
4534
    qemu_cache_utils_init(envp);
4535

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

    
4567
    register_machines();
4568
    machine = first_machine;
4569
    cpu_model = NULL;
4570
    initrd_filename = NULL;
4571
    ram_size = 0;
4572
    vga_ram_size = VGA_RAM_SIZE;
4573
#ifdef CONFIG_GDBSTUB
4574
    use_gdbstub = 0;
4575
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
4576
#endif
4577
    snapshot = 0;
4578
    nographic = 0;
4579
    curses = 0;
4580
    kernel_filename = NULL;
4581
    kernel_cmdline = "";
4582
    cyls = heads = secs = 0;
4583
    translation = BIOS_ATA_TRANSLATION_AUTO;
4584
    monitor_device = "vc";
4585

    
4586
    serial_devices[0] = "vc:80Cx24C";
4587
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4588
        serial_devices[i] = NULL;
4589
    serial_device_index = 0;
4590

    
4591
    parallel_devices[0] = "vc:640x480";
4592
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4593
        parallel_devices[i] = NULL;
4594
    parallel_device_index = 0;
4595

    
4596
    virtio_consoles[0] = "vc:80Cx24C";
4597
    for(i = 1; i < MAX_VIRTIO_CONSOLES; i++)
4598
        virtio_consoles[i] = NULL;
4599
    virtio_console_index = 0;
4600

    
4601
    usb_devices_index = 0;
4602

    
4603
    nb_net_clients = 0;
4604
    nb_bt_opts = 0;
4605
    nb_drives = 0;
4606
    nb_drives_opt = 0;
4607
    hda_index = -1;
4608

    
4609
    nb_nics = 0;
4610

    
4611
    tb_size = 0;
4612
    autostart= 1;
4613

    
4614
    optind = 1;
4615
    for(;;) {
4616
        if (optind >= argc)
4617
            break;
4618
        r = argv[optind];
4619
        if (r[0] != '-') {
4620
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4621
        } else {
4622
            const QEMUOption *popt;
4623

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

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

    
4863
                value = strtoul(optarg, &ptr, 10);
4864
                switch (*ptr) {
4865
                case 0: case 'M': case 'm':
4866
                    value <<= 20;
4867
                    break;
4868
                case 'G': case 'g':
4869
                    value <<= 30;
4870
                    break;
4871
                default:
4872
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4873
                    exit(1);
4874
                }
4875

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

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

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

    
5187
#if defined(CONFIG_KVM) && defined(USE_KQEMU)
5188
    if (kvm_allowed && kqemu_allowed) {
5189
        fprintf(stderr,
5190
                "You can not enable both KVM and kqemu at the same time\n");
5191
        exit(1);
5192
    }
5193
#endif
5194

    
5195
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5196
    if (smp_cpus > machine->max_cpus) {
5197
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5198
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5199
                machine->max_cpus);
5200
        exit(1);
5201
    }
5202

    
5203
    if (nographic) {
5204
       if (serial_device_index == 0)
5205
           serial_devices[0] = "stdio";
5206
       if (parallel_device_index == 0)
5207
           parallel_devices[0] = "null";
5208
       if (strncmp(monitor_device, "vc", 2) == 0)
5209
           monitor_device = "stdio";
5210
       if (virtio_console_index == 0)
5211
           virtio_consoles[0] = "null";
5212
    }
5213

    
5214
#ifndef _WIN32
5215
    if (daemonize) {
5216
        pid_t pid;
5217

    
5218
        if (pipe(fds) == -1)
5219
            exit(1);
5220

    
5221
        pid = fork();
5222
        if (pid > 0) {
5223
            uint8_t status;
5224
            ssize_t len;
5225

    
5226
            close(fds[1]);
5227

    
5228
        again:
5229
            len = read(fds[0], &status, 1);
5230
            if (len == -1 && (errno == EINTR))
5231
                goto again;
5232

    
5233
            if (len != 1)
5234
                exit(1);
5235
            else if (status == 1) {
5236
                fprintf(stderr, "Could not acquire pidfile\n");
5237
                exit(1);
5238
            } else
5239
                exit(0);
5240
        } else if (pid < 0)
5241
            exit(1);
5242

    
5243
        setsid();
5244

    
5245
        pid = fork();
5246
        if (pid > 0)
5247
            exit(0);
5248
        else if (pid < 0)
5249
            exit(1);
5250

    
5251
        umask(027);
5252

    
5253
        signal(SIGTSTP, SIG_IGN);
5254
        signal(SIGTTOU, SIG_IGN);
5255
        signal(SIGTTIN, SIG_IGN);
5256
    }
5257
#endif
5258

    
5259
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5260
        if (daemonize) {
5261
            uint8_t status = 1;
5262
            write(fds[1], &status, 1);
5263
        } else
5264
            fprintf(stderr, "Could not acquire pid file\n");
5265
        exit(1);
5266
    }
5267

    
5268
#ifdef USE_KQEMU
5269
    if (smp_cpus > 1)
5270
        kqemu_allowed = 0;
5271
#endif
5272
    linux_boot = (kernel_filename != NULL);
5273
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5274

    
5275
    if (!linux_boot && net_boot == 0 &&
5276
        !machine->nodisk_ok && nb_drives_opt == 0)
5277
        help(1);
5278

    
5279
    if (!linux_boot && *kernel_cmdline != '\0') {
5280
        fprintf(stderr, "-append only allowed with -kernel option\n");
5281
        exit(1);
5282
    }
5283

    
5284
    if (!linux_boot && initrd_filename != NULL) {
5285
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5286
        exit(1);
5287
    }
5288

    
5289
    /* boot to floppy or the default cd if no hard disk defined yet */
5290
    if (!boot_devices[0]) {
5291
        boot_devices = "cad";
5292
    }
5293
    setvbuf(stdout, NULL, _IOLBF, 0);
5294

    
5295
    init_timers();
5296
    if (init_timer_alarm() < 0) {
5297
        fprintf(stderr, "could not initialize alarm timer\n");
5298
        exit(1);
5299
    }
5300
    if (use_icount && icount_time_shift < 0) {
5301
        use_icount = 2;
5302
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5303
           It will be corrected fairly quickly anyway.  */
5304
        icount_time_shift = 3;
5305
        init_icount_adjust();
5306
    }
5307

    
5308
#ifdef _WIN32
5309
    socket_init();
5310
#endif
5311

    
5312
    /* init network clients */
5313
    if (nb_net_clients == 0) {
5314
        /* if no clients, we use a default config */
5315
        net_clients[nb_net_clients++] = "nic";
5316
#ifdef CONFIG_SLIRP
5317
        net_clients[nb_net_clients++] = "user";
5318
#endif
5319
    }
5320

    
5321
    for(i = 0;i < nb_net_clients; i++) {
5322
        if (net_client_parse(net_clients[i]) < 0)
5323
            exit(1);
5324
    }
5325
    net_client_check();
5326

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

    
5356
    /* init the bluetooth world */
5357
    for (i = 0; i < nb_bt_opts; i++)
5358
        if (bt_parse(bt_opts[i]))
5359
            exit(1);
5360

    
5361
    /* init the memory */
5362
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
5363

    
5364
    if (machine->ram_require & RAMSIZE_FIXED) {
5365
        if (ram_size > 0) {
5366
            if (ram_size < phys_ram_size) {
5367
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
5368
                                machine->name, (unsigned long long) phys_ram_size);
5369
                exit(-1);
5370
            }
5371

    
5372
            phys_ram_size = ram_size;
5373
        } else
5374
            ram_size = phys_ram_size;
5375
    } else {
5376
        if (ram_size == 0)
5377
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5378

    
5379
        phys_ram_size += ram_size;
5380
    }
5381

    
5382
    phys_ram_base = qemu_vmalloc(phys_ram_size);
5383
    if (!phys_ram_base) {
5384
        fprintf(stderr, "Could not allocate physical memory\n");
5385
        exit(1);
5386
    }
5387

    
5388
    /* init the dynamic translator */
5389
    cpu_exec_init_all(tb_size * 1024 * 1024);
5390

    
5391
    bdrv_init();
5392

    
5393
    /* we always create the cdrom drive, even if no disk is there */
5394

    
5395
    if (nb_drives_opt < MAX_DRIVES)
5396
        drive_add(NULL, CDROM_ALIAS);
5397

    
5398
    /* we always create at least one floppy */
5399

    
5400
    if (nb_drives_opt < MAX_DRIVES)
5401
        drive_add(NULL, FD_ALIAS, 0);
5402

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

    
5405
    if (nb_drives_opt < MAX_DRIVES)
5406
        drive_add(NULL, SD_ALIAS);
5407

    
5408
    /* open the virtual block devices */
5409

    
5410
    for(i = 0; i < nb_drives_opt; i++)
5411
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5412
            exit(1);
5413

    
5414
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5415
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5416

    
5417
    /* terminal init */
5418
    memset(&display_state, 0, sizeof(display_state));
5419
    ds->surface = qemu_create_displaysurface(640, 480, 32, 640 * 4);
5420
    if (nographic) {
5421
        if (curses) {
5422
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5423
            exit(1);
5424
        }
5425
        /* nearly nothing to do */
5426
        dumb_display_init(ds);
5427
    } else { 
5428
#if defined(CONFIG_CURSES)
5429
            if (curses) {
5430
                /* At the moment curses cannot be used with other displays */
5431
                curses_display_init(ds, full_screen);
5432
            } else
5433
#endif
5434
            {
5435
                if (vnc_display != NULL) {
5436
                    vnc_display_init(ds);
5437
                    if (vnc_display_open(ds, vnc_display) < 0)
5438
                        exit(1);
5439
                }
5440
                if (sdl || !vnc_display)
5441
#if defined(CONFIG_SDL)
5442
                    sdl_display_init(ds, full_screen, no_frame);
5443
#elif defined(CONFIG_COCOA)
5444
                    cocoa_display_init(ds, full_screen);
5445
#else
5446
                    dumb_display_init(ds);
5447
#endif
5448
            }
5449
    }
5450
    dpy_resize(ds);
5451
#ifndef _WIN32
5452
    /* must be after terminal init, SDL library changes signal handlers */
5453
    termsig_setup();
5454
#endif
5455

    
5456
    /* Maintain compatibility with multiple stdio monitors */
5457
    if (!strcmp(monitor_device,"stdio")) {
5458
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5459
            const char *devname = serial_devices[i];
5460
            if (devname && !strcmp(devname,"mon:stdio")) {
5461
                monitor_device = NULL;
5462
                break;
5463
            } else if (devname && !strcmp(devname,"stdio")) {
5464
                monitor_device = NULL;
5465
                serial_devices[i] = "mon:stdio";
5466
                break;
5467
            }
5468
        }
5469
    }
5470
    if (monitor_device) {
5471
        monitor_hd = qemu_chr_open("monitor", monitor_device);
5472
        if (!monitor_hd) {
5473
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5474
            exit(1);
5475
        }
5476
        monitor_init(monitor_hd, !nographic);
5477
    }
5478

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

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

    
5511
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5512
        const char *devname = virtio_consoles[i];
5513
        if (devname && strcmp(devname, "none")) {
5514
            char label[32];
5515
            snprintf(label, sizeof(label), "virtcon%d", i);
5516
            virtcon_hds[i] = qemu_chr_open(label, devname);
5517
            if (!virtcon_hds[i]) {
5518
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5519
                        devname);
5520
                exit(1);
5521
            }
5522
            if (strstart(devname, "vc", 0))
5523
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5524
        }
5525
    }
5526

    
5527
    if (kvm_enabled()) {
5528
        int ret;
5529

    
5530
        ret = kvm_init(smp_cpus);
5531
        if (ret < 0) {
5532
            fprintf(stderr, "failed to initialize KVM\n");
5533
            exit(1);
5534
        }
5535
    }
5536

    
5537
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
5538
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5539

    
5540
    /* Set KVM's vcpu state to qemu's initial CPUState. */
5541
    if (kvm_enabled()) {
5542
        int ret;
5543

    
5544
        ret = kvm_sync_vcpus();
5545
        if (ret < 0) {
5546
            fprintf(stderr, "failed to initialize vcpus\n");
5547
            exit(1);
5548
        }
5549
    }
5550

    
5551
    /* init USB devices */
5552
    if (usb_enabled) {
5553
        for(i = 0; i < usb_devices_index; i++) {
5554
            if (usb_device_add(usb_devices[i]) < 0) {
5555
                fprintf(stderr, "Warning: could not add USB device %s\n",
5556
                        usb_devices[i]);
5557
            }
5558
        }
5559
    }
5560

    
5561
    dcl = ds->listeners;
5562
    while (dcl != NULL) {
5563
        if (dcl->dpy_refresh != NULL) {
5564
            display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
5565
            qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
5566
        }
5567
        dcl = dcl->next;
5568
    }
5569
#ifdef CONFIG_GDBSTUB
5570
    if (use_gdbstub) {
5571
        /* XXX: use standard host:port notation and modify options
5572
           accordingly. */
5573
        if (gdbserver_start(gdbstub_port) < 0) {
5574
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
5575
                    gdbstub_port);
5576
            exit(1);
5577
        }
5578
    }
5579
#endif
5580

    
5581
    if (loadvm)
5582
        do_loadvm(loadvm);
5583

    
5584
    if (incoming) {
5585
        autostart = 0; /* fixme how to deal with -daemonize */
5586
        qemu_start_incoming_migration(incoming);
5587
    }
5588

    
5589
    {
5590
        /* XXX: simplify init */
5591
        read_passwords();
5592
        if (autostart) {
5593
            vm_start();
5594
        }
5595
    }
5596

    
5597
    if (daemonize) {
5598
        uint8_t status = 0;
5599
        ssize_t len;
5600
        int fd;
5601

    
5602
    again1:
5603
        len = write(fds[1], &status, 1);
5604
        if (len == -1 && (errno == EINTR))
5605
            goto again1;
5606

    
5607
        if (len != 1)
5608
            exit(1);
5609

    
5610
        chdir("/");
5611
        TFR(fd = open("/dev/null", O_RDWR));
5612
        if (fd == -1)
5613
            exit(1);
5614

    
5615
        dup2(fd, 0);
5616
        dup2(fd, 1);
5617
        dup2(fd, 2);
5618

    
5619
        close(fd);
5620
    }
5621

    
5622
    main_loop();
5623
    quit_timers();
5624
    net_cleanup();
5625

    
5626
    return 0;
5627
}