Statistics
| Branch: | Revision:

root / vl.c @ 640f42e4

History | View | Annotate | Download (141.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 <unistd.h>
25
#include <fcntl.h>
26
#include <signal.h>
27
#include <time.h>
28
#include <errno.h>
29
#include <sys/time.h>
30
#include <zlib.h>
31

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

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

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

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

    
97
#if defined(__OpenBSD__)
98
#include <util.h>
99
#endif
100

    
101
#if defined(CONFIG_VDE)
102
#include <libvdeplug.h>
103
#endif
104

    
105
#ifdef _WIN32
106
#include <windows.h>
107
#include <malloc.h>
108
#include <sys/timeb.h>
109
#include <mmsystem.h>
110
#define getopt_long_only getopt_long
111
#define memalign(align, size) malloc(size)
112
#endif
113

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

    
127
#ifdef CONFIG_COCOA
128
#undef main
129
#define main qemu_main
130
#endif /* CONFIG_COCOA */
131

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

    
158
#include "disas.h"
159

    
160
#include "exec-all.h"
161

    
162
#include "qemu_socket.h"
163

    
164
#if defined(CONFIG_SLIRP)
165
#include "libslirp.h"
166
#endif
167

    
168
//#define DEBUG_UNUSED_IOPORT
169
//#define DEBUG_IOPORT
170
//#define DEBUG_NET
171
//#define DEBUG_SLIRP
172

    
173

    
174
#ifdef DEBUG_IOPORT
175
#  define LOG_IOPORT(...) qemu_log_mask(CPU_LOG_IOPORT, ## __VA_ARGS__)
176
#else
177
#  define LOG_IOPORT(...) do { } while (0)
178
#endif
179

    
180
#define DEFAULT_RAM_SIZE 128
181

    
182
/* Max number of USB devices that can be specified on the commandline.  */
183
#define MAX_USB_CMDLINE 8
184

    
185
/* Max number of bluetooth switches on the commandline.  */
186
#define MAX_BT_CMDLINE 10
187

    
188
/* XXX: use a two level table to limit memory usage */
189
#define MAX_IOPORTS 65536
190

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

    
268
static CPUState *cur_cpu;
269
static CPUState *next_cpu;
270
static int event_pending = 1;
271
/* Conversion factor from emulated instructions to virtual clock ticks.  */
272
static int icount_time_shift;
273
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
274
#define MAX_ICOUNT_SHIFT 10
275
/* Compensate for varying guest execution speed.  */
276
static int64_t qemu_icount_bias;
277
static QEMUTimer *icount_rt_timer;
278
static QEMUTimer *icount_vm_timer;
279
static QEMUTimer *nographic_timer;
280

    
281
uint8_t qemu_uuid[16];
282

    
283
/***********************************************************/
284
/* x86 ISA bus support */
285

    
286
target_phys_addr_t isa_mem_base = 0;
287
PicState2 *isa_pic;
288

    
289
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
290
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
291

    
292
static uint32_t ioport_read(int index, uint32_t address)
293
{
294
    static IOPortReadFunc *default_func[3] = {
295
        default_ioport_readb,
296
        default_ioport_readw,
297
        default_ioport_readl
298
    };
299
    IOPortReadFunc *func = ioport_read_table[index][address];
300
    if (!func)
301
        func = default_func[index];
302
    return func(ioport_opaque[address], address);
303
}
304

    
305
static void ioport_write(int index, uint32_t address, uint32_t data)
306
{
307
    static IOPortWriteFunc *default_func[3] = {
308
        default_ioport_writeb,
309
        default_ioport_writew,
310
        default_ioport_writel
311
    };
312
    IOPortWriteFunc *func = ioport_write_table[index][address];
313
    if (!func)
314
        func = default_func[index];
315
    func(ioport_opaque[address], address, data);
316
}
317

    
318
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
319
{
320
#ifdef DEBUG_UNUSED_IOPORT
321
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
322
#endif
323
    return 0xff;
324
}
325

    
326
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
327
{
328
#ifdef DEBUG_UNUSED_IOPORT
329
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
330
#endif
331
}
332

    
333
/* default is to make two byte accesses */
334
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
335
{
336
    uint32_t data;
337
    data = ioport_read(0, address);
338
    address = (address + 1) & (MAX_IOPORTS - 1);
339
    data |= ioport_read(0, address) << 8;
340
    return data;
341
}
342

    
343
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
344
{
345
    ioport_write(0, address, data & 0xff);
346
    address = (address + 1) & (MAX_IOPORTS - 1);
347
    ioport_write(0, address, (data >> 8) & 0xff);
348
}
349

    
350
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
351
{
352
#ifdef DEBUG_UNUSED_IOPORT
353
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
354
#endif
355
    return 0xffffffff;
356
}
357

    
358
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
359
{
360
#ifdef DEBUG_UNUSED_IOPORT
361
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
362
#endif
363
}
364

    
365
/* size is the word size in byte */
366
int register_ioport_read(int start, int length, int size,
367
                         IOPortReadFunc *func, void *opaque)
368
{
369
    int i, bsize;
370

    
371
    if (size == 1) {
372
        bsize = 0;
373
    } else if (size == 2) {
374
        bsize = 1;
375
    } else if (size == 4) {
376
        bsize = 2;
377
    } else {
378
        hw_error("register_ioport_read: invalid size");
379
        return -1;
380
    }
381
    for(i = start; i < start + length; i += size) {
382
        ioport_read_table[bsize][i] = func;
383
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
384
            hw_error("register_ioport_read: invalid opaque");
385
        ioport_opaque[i] = opaque;
386
    }
387
    return 0;
388
}
389

    
390
/* size is the word size in byte */
391
int register_ioport_write(int start, int length, int size,
392
                          IOPortWriteFunc *func, void *opaque)
393
{
394
    int i, bsize;
395

    
396
    if (size == 1) {
397
        bsize = 0;
398
    } else if (size == 2) {
399
        bsize = 1;
400
    } else if (size == 4) {
401
        bsize = 2;
402
    } else {
403
        hw_error("register_ioport_write: invalid size");
404
        return -1;
405
    }
406
    for(i = start; i < start + length; i += size) {
407
        ioport_write_table[bsize][i] = func;
408
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
409
            hw_error("register_ioport_write: invalid opaque");
410
        ioport_opaque[i] = opaque;
411
    }
412
    return 0;
413
}
414

    
415
void isa_unassign_ioport(int start, int length)
416
{
417
    int i;
418

    
419
    for(i = start; i < start + length; i++) {
420
        ioport_read_table[0][i] = default_ioport_readb;
421
        ioport_read_table[1][i] = default_ioport_readw;
422
        ioport_read_table[2][i] = default_ioport_readl;
423

    
424
        ioport_write_table[0][i] = default_ioport_writeb;
425
        ioport_write_table[1][i] = default_ioport_writew;
426
        ioport_write_table[2][i] = default_ioport_writel;
427

    
428
        ioport_opaque[i] = NULL;
429
    }
430
}
431

    
432
/***********************************************************/
433

    
434
void cpu_outb(CPUState *env, int addr, int val)
435
{
436
    LOG_IOPORT("outb: %04x %02x\n", addr, val);
437
    ioport_write(0, addr, val);
438
#ifdef CONFIG_KQEMU
439
    if (env)
440
        env->last_io_time = cpu_get_time_fast();
441
#endif
442
}
443

    
444
void cpu_outw(CPUState *env, int addr, int val)
445
{
446
    LOG_IOPORT("outw: %04x %04x\n", addr, val);
447
    ioport_write(1, addr, val);
448
#ifdef CONFIG_KQEMU
449
    if (env)
450
        env->last_io_time = cpu_get_time_fast();
451
#endif
452
}
453

    
454
void cpu_outl(CPUState *env, int addr, int val)
455
{
456
    LOG_IOPORT("outl: %04x %08x\n", addr, val);
457
    ioport_write(2, addr, val);
458
#ifdef CONFIG_KQEMU
459
    if (env)
460
        env->last_io_time = cpu_get_time_fast();
461
#endif
462
}
463

    
464
int cpu_inb(CPUState *env, int addr)
465
{
466
    int val;
467
    val = ioport_read(0, addr);
468
    LOG_IOPORT("inb : %04x %02x\n", addr, val);
469
#ifdef CONFIG_KQEMU
470
    if (env)
471
        env->last_io_time = cpu_get_time_fast();
472
#endif
473
    return val;
474
}
475

    
476
int cpu_inw(CPUState *env, int addr)
477
{
478
    int val;
479
    val = ioport_read(1, addr);
480
    LOG_IOPORT("inw : %04x %04x\n", addr, val);
481
#ifdef CONFIG_KQEMU
482
    if (env)
483
        env->last_io_time = cpu_get_time_fast();
484
#endif
485
    return val;
486
}
487

    
488
int cpu_inl(CPUState *env, int addr)
489
{
490
    int val;
491
    val = ioport_read(2, addr);
492
    LOG_IOPORT("inl : %04x %08x\n", addr, val);
493
#ifdef CONFIG_KQEMU
494
    if (env)
495
        env->last_io_time = cpu_get_time_fast();
496
#endif
497
    return val;
498
}
499

    
500
/***********************************************************/
501
void hw_error(const char *fmt, ...)
502
{
503
    va_list ap;
504
    CPUState *env;
505

    
506
    va_start(ap, fmt);
507
    fprintf(stderr, "qemu: hardware error: ");
508
    vfprintf(stderr, fmt, ap);
509
    fprintf(stderr, "\n");
510
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
511
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
512
#ifdef TARGET_I386
513
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
514
#else
515
        cpu_dump_state(env, stderr, fprintf, 0);
516
#endif
517
    }
518
    va_end(ap);
519
    abort();
520
}
521
 
522
/***************/
523
/* ballooning */
524

    
525
static QEMUBalloonEvent *qemu_balloon_event;
526
void *qemu_balloon_event_opaque;
527

    
528
void qemu_add_balloon_handler(QEMUBalloonEvent *func, void *opaque)
529
{
530
    qemu_balloon_event = func;
531
    qemu_balloon_event_opaque = opaque;
532
}
533

    
534
void qemu_balloon(ram_addr_t target)
535
{
536
    if (qemu_balloon_event)
537
        qemu_balloon_event(qemu_balloon_event_opaque, target);
538
}
539

    
540
ram_addr_t qemu_balloon_status(void)
541
{
542
    if (qemu_balloon_event)
543
        return qemu_balloon_event(qemu_balloon_event_opaque, 0);
544
    return 0;
545
}
546

    
547
/***********************************************************/
548
/* keyboard/mouse */
549

    
550
static QEMUPutKBDEvent *qemu_put_kbd_event;
551
static void *qemu_put_kbd_event_opaque;
552
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
553
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
554

    
555
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
556
{
557
    qemu_put_kbd_event_opaque = opaque;
558
    qemu_put_kbd_event = func;
559
}
560

    
561
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
562
                                                void *opaque, int absolute,
563
                                                const char *name)
564
{
565
    QEMUPutMouseEntry *s, *cursor;
566

    
567
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
568

    
569
    s->qemu_put_mouse_event = func;
570
    s->qemu_put_mouse_event_opaque = opaque;
571
    s->qemu_put_mouse_event_absolute = absolute;
572
    s->qemu_put_mouse_event_name = qemu_strdup(name);
573
    s->next = NULL;
574

    
575
    if (!qemu_put_mouse_event_head) {
576
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
577
        return s;
578
    }
579

    
580
    cursor = qemu_put_mouse_event_head;
581
    while (cursor->next != NULL)
582
        cursor = cursor->next;
583

    
584
    cursor->next = s;
585
    qemu_put_mouse_event_current = s;
586

    
587
    return s;
588
}
589

    
590
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
591
{
592
    QEMUPutMouseEntry *prev = NULL, *cursor;
593

    
594
    if (!qemu_put_mouse_event_head || entry == NULL)
595
        return;
596

    
597
    cursor = qemu_put_mouse_event_head;
598
    while (cursor != NULL && cursor != entry) {
599
        prev = cursor;
600
        cursor = cursor->next;
601
    }
602

    
603
    if (cursor == NULL) // does not exist or list empty
604
        return;
605
    else if (prev == NULL) { // entry is head
606
        qemu_put_mouse_event_head = cursor->next;
607
        if (qemu_put_mouse_event_current == entry)
608
            qemu_put_mouse_event_current = cursor->next;
609
        qemu_free(entry->qemu_put_mouse_event_name);
610
        qemu_free(entry);
611
        return;
612
    }
613

    
614
    prev->next = entry->next;
615

    
616
    if (qemu_put_mouse_event_current == entry)
617
        qemu_put_mouse_event_current = prev;
618

    
619
    qemu_free(entry->qemu_put_mouse_event_name);
620
    qemu_free(entry);
621
}
622

    
623
void kbd_put_keycode(int keycode)
624
{
625
    if (qemu_put_kbd_event) {
626
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
627
    }
628
}
629

    
630
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
631
{
632
    QEMUPutMouseEvent *mouse_event;
633
    void *mouse_event_opaque;
634
    int width;
635

    
636
    if (!qemu_put_mouse_event_current) {
637
        return;
638
    }
639

    
640
    mouse_event =
641
        qemu_put_mouse_event_current->qemu_put_mouse_event;
642
    mouse_event_opaque =
643
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
644

    
645
    if (mouse_event) {
646
        if (graphic_rotate) {
647
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
648
                width = 0x7fff;
649
            else
650
                width = graphic_width - 1;
651
            mouse_event(mouse_event_opaque,
652
                                 width - dy, dx, dz, buttons_state);
653
        } else
654
            mouse_event(mouse_event_opaque,
655
                                 dx, dy, dz, buttons_state);
656
    }
657
}
658

    
659
int kbd_mouse_is_absolute(void)
660
{
661
    if (!qemu_put_mouse_event_current)
662
        return 0;
663

    
664
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
665
}
666

    
667
void do_info_mice(Monitor *mon)
668
{
669
    QEMUPutMouseEntry *cursor;
670
    int index = 0;
671

    
672
    if (!qemu_put_mouse_event_head) {
673
        monitor_printf(mon, "No mouse devices connected\n");
674
        return;
675
    }
676

    
677
    monitor_printf(mon, "Mouse devices available:\n");
678
    cursor = qemu_put_mouse_event_head;
679
    while (cursor != NULL) {
680
        monitor_printf(mon, "%c Mouse #%d: %s\n",
681
                       (cursor == qemu_put_mouse_event_current ? '*' : ' '),
682
                       index, cursor->qemu_put_mouse_event_name);
683
        index++;
684
        cursor = cursor->next;
685
    }
686
}
687

    
688
void do_mouse_set(Monitor *mon, int index)
689
{
690
    QEMUPutMouseEntry *cursor;
691
    int i = 0;
692

    
693
    if (!qemu_put_mouse_event_head) {
694
        monitor_printf(mon, "No mouse devices connected\n");
695
        return;
696
    }
697

    
698
    cursor = qemu_put_mouse_event_head;
699
    while (cursor != NULL && index != i) {
700
        i++;
701
        cursor = cursor->next;
702
    }
703

    
704
    if (cursor != NULL)
705
        qemu_put_mouse_event_current = cursor;
706
    else
707
        monitor_printf(mon, "Mouse at given index not found\n");
708
}
709

    
710
/* compute with 96 bit intermediate result: (a*b)/c */
711
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
712
{
713
    union {
714
        uint64_t ll;
715
        struct {
716
#ifdef WORDS_BIGENDIAN
717
            uint32_t high, low;
718
#else
719
            uint32_t low, high;
720
#endif
721
        } l;
722
    } u, res;
723
    uint64_t rl, rh;
724

    
725
    u.ll = a;
726
    rl = (uint64_t)u.l.low * (uint64_t)b;
727
    rh = (uint64_t)u.l.high * (uint64_t)b;
728
    rh += (rl >> 32);
729
    res.l.high = rh / c;
730
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
731
    return res.ll;
732
}
733

    
734
/***********************************************************/
735
/* real time host monotonic timer */
736

    
737
#define QEMU_TIMER_BASE 1000000000LL
738

    
739
#ifdef WIN32
740

    
741
static int64_t clock_freq;
742

    
743
static void init_get_clock(void)
744
{
745
    LARGE_INTEGER freq;
746
    int ret;
747
    ret = QueryPerformanceFrequency(&freq);
748
    if (ret == 0) {
749
        fprintf(stderr, "Could not calibrate ticks\n");
750
        exit(1);
751
    }
752
    clock_freq = freq.QuadPart;
753
}
754

    
755
static int64_t get_clock(void)
756
{
757
    LARGE_INTEGER ti;
758
    QueryPerformanceCounter(&ti);
759
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
760
}
761

    
762
#else
763

    
764
static int use_rt_clock;
765

    
766
static void init_get_clock(void)
767
{
768
    use_rt_clock = 0;
769
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
770
    || defined(__DragonFly__)
771
    {
772
        struct timespec ts;
773
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
774
            use_rt_clock = 1;
775
        }
776
    }
777
#endif
778
}
779

    
780
static int64_t get_clock(void)
781
{
782
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000) \
783
        || defined(__DragonFly__)
784
    if (use_rt_clock) {
785
        struct timespec ts;
786
        clock_gettime(CLOCK_MONOTONIC, &ts);
787
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
788
    } else
789
#endif
790
    {
791
        /* XXX: using gettimeofday leads to problems if the date
792
           changes, so it should be avoided. */
793
        struct timeval tv;
794
        gettimeofday(&tv, NULL);
795
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
796
    }
797
}
798
#endif
799

    
800
/* Return the virtual CPU time, based on the instruction counter.  */
801
static int64_t cpu_get_icount(void)
802
{
803
    int64_t icount;
804
    CPUState *env = cpu_single_env;;
805
    icount = qemu_icount;
806
    if (env) {
807
        if (!can_do_io(env))
808
            fprintf(stderr, "Bad clock read\n");
809
        icount -= (env->icount_decr.u16.low + env->icount_extra);
810
    }
811
    return qemu_icount_bias + (icount << icount_time_shift);
812
}
813

    
814
/***********************************************************/
815
/* guest cycle counter */
816

    
817
static int64_t cpu_ticks_prev;
818
static int64_t cpu_ticks_offset;
819
static int64_t cpu_clock_offset;
820
static int cpu_ticks_enabled;
821

    
822
/* return the host CPU cycle counter and handle stop/restart */
823
int64_t cpu_get_ticks(void)
824
{
825
    if (use_icount) {
826
        return cpu_get_icount();
827
    }
828
    if (!cpu_ticks_enabled) {
829
        return cpu_ticks_offset;
830
    } else {
831
        int64_t ticks;
832
        ticks = cpu_get_real_ticks();
833
        if (cpu_ticks_prev > ticks) {
834
            /* Note: non increasing ticks may happen if the host uses
835
               software suspend */
836
            cpu_ticks_offset += cpu_ticks_prev - ticks;
837
        }
838
        cpu_ticks_prev = ticks;
839
        return ticks + cpu_ticks_offset;
840
    }
841
}
842

    
843
/* return the host CPU monotonic timer and handle stop/restart */
844
static int64_t cpu_get_clock(void)
845
{
846
    int64_t ti;
847
    if (!cpu_ticks_enabled) {
848
        return cpu_clock_offset;
849
    } else {
850
        ti = get_clock();
851
        return ti + cpu_clock_offset;
852
    }
853
}
854

    
855
/* enable cpu_get_ticks() */
856
void cpu_enable_ticks(void)
857
{
858
    if (!cpu_ticks_enabled) {
859
        cpu_ticks_offset -= cpu_get_real_ticks();
860
        cpu_clock_offset -= get_clock();
861
        cpu_ticks_enabled = 1;
862
    }
863
}
864

    
865
/* disable cpu_get_ticks() : the clock is stopped. You must not call
866
   cpu_get_ticks() after that.  */
867
void cpu_disable_ticks(void)
868
{
869
    if (cpu_ticks_enabled) {
870
        cpu_ticks_offset = cpu_get_ticks();
871
        cpu_clock_offset = cpu_get_clock();
872
        cpu_ticks_enabled = 0;
873
    }
874
}
875

    
876
/***********************************************************/
877
/* timers */
878

    
879
#define QEMU_TIMER_REALTIME 0
880
#define QEMU_TIMER_VIRTUAL  1
881

    
882
struct QEMUClock {
883
    int type;
884
    /* XXX: add frequency */
885
};
886

    
887
struct QEMUTimer {
888
    QEMUClock *clock;
889
    int64_t expire_time;
890
    QEMUTimerCB *cb;
891
    void *opaque;
892
    struct QEMUTimer *next;
893
};
894

    
895
struct qemu_alarm_timer {
896
    char const *name;
897
    unsigned int flags;
898

    
899
    int (*start)(struct qemu_alarm_timer *t);
900
    void (*stop)(struct qemu_alarm_timer *t);
901
    void (*rearm)(struct qemu_alarm_timer *t);
902
    void *priv;
903
};
904

    
905
#define ALARM_FLAG_DYNTICKS  0x1
906
#define ALARM_FLAG_EXPIRED   0x2
907

    
908
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
909
{
910
    return t->flags & ALARM_FLAG_DYNTICKS;
911
}
912

    
913
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
914
{
915
    if (!alarm_has_dynticks(t))
916
        return;
917

    
918
    t->rearm(t);
919
}
920

    
921
/* TODO: MIN_TIMER_REARM_US should be optimized */
922
#define MIN_TIMER_REARM_US 250
923

    
924
static struct qemu_alarm_timer *alarm_timer;
925
#ifndef _WIN32
926
static int alarm_timer_rfd, alarm_timer_wfd;
927
#endif
928

    
929
#ifdef _WIN32
930

    
931
struct qemu_alarm_win32 {
932
    MMRESULT timerId;
933
    HANDLE host_alarm;
934
    unsigned int period;
935
} alarm_win32_data = {0, NULL, -1};
936

    
937
static int win32_start_timer(struct qemu_alarm_timer *t);
938
static void win32_stop_timer(struct qemu_alarm_timer *t);
939
static void win32_rearm_timer(struct qemu_alarm_timer *t);
940

    
941
#else
942

    
943
static int unix_start_timer(struct qemu_alarm_timer *t);
944
static void unix_stop_timer(struct qemu_alarm_timer *t);
945

    
946
#ifdef __linux__
947

    
948
static int dynticks_start_timer(struct qemu_alarm_timer *t);
949
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
950
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
951

    
952
static int hpet_start_timer(struct qemu_alarm_timer *t);
953
static void hpet_stop_timer(struct qemu_alarm_timer *t);
954

    
955
static int rtc_start_timer(struct qemu_alarm_timer *t);
956
static void rtc_stop_timer(struct qemu_alarm_timer *t);
957

    
958
#endif /* __linux__ */
959

    
960
#endif /* _WIN32 */
961

    
962
/* Correlation between real and virtual time is always going to be
963
   fairly approximate, so ignore small variation.
964
   When the guest is idle real and virtual time will be aligned in
965
   the IO wait loop.  */
966
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
967

    
968
static void icount_adjust(void)
969
{
970
    int64_t cur_time;
971
    int64_t cur_icount;
972
    int64_t delta;
973
    static int64_t last_delta;
974
    /* If the VM is not running, then do nothing.  */
975
    if (!vm_running)
976
        return;
977

    
978
    cur_time = cpu_get_clock();
979
    cur_icount = qemu_get_clock(vm_clock);
980
    delta = cur_icount - cur_time;
981
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
982
    if (delta > 0
983
        && last_delta + ICOUNT_WOBBLE < delta * 2
984
        && icount_time_shift > 0) {
985
        /* The guest is getting too far ahead.  Slow time down.  */
986
        icount_time_shift--;
987
    }
988
    if (delta < 0
989
        && last_delta - ICOUNT_WOBBLE > delta * 2
990
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
991
        /* The guest is getting too far behind.  Speed time up.  */
992
        icount_time_shift++;
993
    }
994
    last_delta = delta;
995
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
996
}
997

    
998
static void icount_adjust_rt(void * opaque)
999
{
1000
    qemu_mod_timer(icount_rt_timer,
1001
                   qemu_get_clock(rt_clock) + 1000);
1002
    icount_adjust();
1003
}
1004

    
1005
static void icount_adjust_vm(void * opaque)
1006
{
1007
    qemu_mod_timer(icount_vm_timer,
1008
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1009
    icount_adjust();
1010
}
1011

    
1012
static void init_icount_adjust(void)
1013
{
1014
    /* Have both realtime and virtual time triggers for speed adjustment.
1015
       The realtime trigger catches emulated time passing too slowly,
1016
       the virtual time trigger catches emulated time passing too fast.
1017
       Realtime triggers occur even when idle, so use them less frequently
1018
       than VM triggers.  */
1019
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
1020
    qemu_mod_timer(icount_rt_timer,
1021
                   qemu_get_clock(rt_clock) + 1000);
1022
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
1023
    qemu_mod_timer(icount_vm_timer,
1024
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
1025
}
1026

    
1027
static struct qemu_alarm_timer alarm_timers[] = {
1028
#ifndef _WIN32
1029
#ifdef __linux__
1030
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
1031
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
1032
    /* HPET - if available - is preferred */
1033
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
1034
    /* ...otherwise try RTC */
1035
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
1036
#endif
1037
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
1038
#else
1039
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
1040
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1041
    {"win32", 0, win32_start_timer,
1042
     win32_stop_timer, NULL, &alarm_win32_data},
1043
#endif
1044
    {NULL, }
1045
};
1046

    
1047
static void show_available_alarms(void)
1048
{
1049
    int i;
1050

    
1051
    printf("Available alarm timers, in order of precedence:\n");
1052
    for (i = 0; alarm_timers[i].name; i++)
1053
        printf("%s\n", alarm_timers[i].name);
1054
}
1055

    
1056
static void configure_alarms(char const *opt)
1057
{
1058
    int i;
1059
    int cur = 0;
1060
    int count = ARRAY_SIZE(alarm_timers) - 1;
1061
    char *arg;
1062
    char *name;
1063
    struct qemu_alarm_timer tmp;
1064

    
1065
    if (!strcmp(opt, "?")) {
1066
        show_available_alarms();
1067
        exit(0);
1068
    }
1069

    
1070
    arg = strdup(opt);
1071

    
1072
    /* Reorder the array */
1073
    name = strtok(arg, ",");
1074
    while (name) {
1075
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1076
            if (!strcmp(alarm_timers[i].name, name))
1077
                break;
1078
        }
1079

    
1080
        if (i == count) {
1081
            fprintf(stderr, "Unknown clock %s\n", name);
1082
            goto next;
1083
        }
1084

    
1085
        if (i < cur)
1086
            /* Ignore */
1087
            goto next;
1088

    
1089
        /* Swap */
1090
        tmp = alarm_timers[i];
1091
        alarm_timers[i] = alarm_timers[cur];
1092
        alarm_timers[cur] = tmp;
1093

    
1094
        cur++;
1095
next:
1096
        name = strtok(NULL, ",");
1097
    }
1098

    
1099
    free(arg);
1100

    
1101
    if (cur) {
1102
        /* Disable remaining timers */
1103
        for (i = cur; i < count; i++)
1104
            alarm_timers[i].name = NULL;
1105
    } else {
1106
        show_available_alarms();
1107
        exit(1);
1108
    }
1109
}
1110

    
1111
QEMUClock *rt_clock;
1112
QEMUClock *vm_clock;
1113

    
1114
static QEMUTimer *active_timers[2];
1115

    
1116
static QEMUClock *qemu_new_clock(int type)
1117
{
1118
    QEMUClock *clock;
1119
    clock = qemu_mallocz(sizeof(QEMUClock));
1120
    clock->type = type;
1121
    return clock;
1122
}
1123

    
1124
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1125
{
1126
    QEMUTimer *ts;
1127

    
1128
    ts = qemu_mallocz(sizeof(QEMUTimer));
1129
    ts->clock = clock;
1130
    ts->cb = cb;
1131
    ts->opaque = opaque;
1132
    return ts;
1133
}
1134

    
1135
void qemu_free_timer(QEMUTimer *ts)
1136
{
1137
    qemu_free(ts);
1138
}
1139

    
1140
/* stop a timer, but do not dealloc it */
1141
void qemu_del_timer(QEMUTimer *ts)
1142
{
1143
    QEMUTimer **pt, *t;
1144

    
1145
    /* NOTE: this code must be signal safe because
1146
       qemu_timer_expired() can be called from a signal. */
1147
    pt = &active_timers[ts->clock->type];
1148
    for(;;) {
1149
        t = *pt;
1150
        if (!t)
1151
            break;
1152
        if (t == ts) {
1153
            *pt = t->next;
1154
            break;
1155
        }
1156
        pt = &t->next;
1157
    }
1158
}
1159

    
1160
/* modify the current timer so that it will be fired when current_time
1161
   >= expire_time. The corresponding callback will be called. */
1162
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1163
{
1164
    QEMUTimer **pt, *t;
1165

    
1166
    qemu_del_timer(ts);
1167

    
1168
    /* add the timer in the sorted list */
1169
    /* NOTE: this code must be signal safe because
1170
       qemu_timer_expired() can be called from a signal. */
1171
    pt = &active_timers[ts->clock->type];
1172
    for(;;) {
1173
        t = *pt;
1174
        if (!t)
1175
            break;
1176
        if (t->expire_time > expire_time)
1177
            break;
1178
        pt = &t->next;
1179
    }
1180
    ts->expire_time = expire_time;
1181
    ts->next = *pt;
1182
    *pt = ts;
1183

    
1184
    /* Rearm if necessary  */
1185
    if (pt == &active_timers[ts->clock->type]) {
1186
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1187
            qemu_rearm_alarm_timer(alarm_timer);
1188
        }
1189
        /* Interrupt execution to force deadline recalculation.  */
1190
        if (use_icount && cpu_single_env) {
1191
            cpu_exit(cpu_single_env);
1192
        }
1193
    }
1194
}
1195

    
1196
int qemu_timer_pending(QEMUTimer *ts)
1197
{
1198
    QEMUTimer *t;
1199
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1200
        if (t == ts)
1201
            return 1;
1202
    }
1203
    return 0;
1204
}
1205

    
1206
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1207
{
1208
    if (!timer_head)
1209
        return 0;
1210
    return (timer_head->expire_time <= current_time);
1211
}
1212

    
1213
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1214
{
1215
    QEMUTimer *ts;
1216

    
1217
    for(;;) {
1218
        ts = *ptimer_head;
1219
        if (!ts || ts->expire_time > current_time)
1220
            break;
1221
        /* remove timer from the list before calling the callback */
1222
        *ptimer_head = ts->next;
1223
        ts->next = NULL;
1224

    
1225
        /* run the callback (the timer list can be modified) */
1226
        ts->cb(ts->opaque);
1227
    }
1228
}
1229

    
1230
int64_t qemu_get_clock(QEMUClock *clock)
1231
{
1232
    switch(clock->type) {
1233
    case QEMU_TIMER_REALTIME:
1234
        return get_clock() / 1000000;
1235
    default:
1236
    case QEMU_TIMER_VIRTUAL:
1237
        if (use_icount) {
1238
            return cpu_get_icount();
1239
        } else {
1240
            return cpu_get_clock();
1241
        }
1242
    }
1243
}
1244

    
1245
static void init_timers(void)
1246
{
1247
    init_get_clock();
1248
    ticks_per_sec = QEMU_TIMER_BASE;
1249
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1250
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1251
}
1252

    
1253
/* save a timer */
1254
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1255
{
1256
    uint64_t expire_time;
1257

    
1258
    if (qemu_timer_pending(ts)) {
1259
        expire_time = ts->expire_time;
1260
    } else {
1261
        expire_time = -1;
1262
    }
1263
    qemu_put_be64(f, expire_time);
1264
}
1265

    
1266
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1267
{
1268
    uint64_t expire_time;
1269

    
1270
    expire_time = qemu_get_be64(f);
1271
    if (expire_time != -1) {
1272
        qemu_mod_timer(ts, expire_time);
1273
    } else {
1274
        qemu_del_timer(ts);
1275
    }
1276
}
1277

    
1278
static void timer_save(QEMUFile *f, void *opaque)
1279
{
1280
    if (cpu_ticks_enabled) {
1281
        hw_error("cannot save state if virtual timers are running");
1282
    }
1283
    qemu_put_be64(f, cpu_ticks_offset);
1284
    qemu_put_be64(f, ticks_per_sec);
1285
    qemu_put_be64(f, cpu_clock_offset);
1286
}
1287

    
1288
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1289
{
1290
    if (version_id != 1 && version_id != 2)
1291
        return -EINVAL;
1292
    if (cpu_ticks_enabled) {
1293
        return -EINVAL;
1294
    }
1295
    cpu_ticks_offset=qemu_get_be64(f);
1296
    ticks_per_sec=qemu_get_be64(f);
1297
    if (version_id == 2) {
1298
        cpu_clock_offset=qemu_get_be64(f);
1299
    }
1300
    return 0;
1301
}
1302

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

    
1348
#ifdef _WIN32
1349
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1350
        SetEvent(data->host_alarm);
1351
#else
1352
        static const char byte = 0;
1353
        write(alarm_timer_wfd, &byte, sizeof(byte));
1354
#endif
1355
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1356

    
1357
        if (env) {
1358
            /* stop the currently executing cpu because a timer occured */
1359
            cpu_exit(env);
1360
#ifdef CONFIG_KQEMU
1361
            if (env->kqemu_enabled) {
1362
                kqemu_cpu_interrupt(env);
1363
            }
1364
#endif
1365
        }
1366
        event_pending = 1;
1367
    }
1368
}
1369

    
1370
static int64_t qemu_next_deadline(void)
1371
{
1372
    int64_t delta;
1373

    
1374
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1375
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1376
                     qemu_get_clock(vm_clock);
1377
    } else {
1378
        /* To avoid problems with overflow limit this to 2^32.  */
1379
        delta = INT32_MAX;
1380
    }
1381

    
1382
    if (delta < 0)
1383
        delta = 0;
1384

    
1385
    return delta;
1386
}
1387

    
1388
#if defined(__linux__) || defined(_WIN32)
1389
static uint64_t qemu_next_deadline_dyntick(void)
1390
{
1391
    int64_t delta;
1392
    int64_t rtdelta;
1393

    
1394
    if (use_icount)
1395
        delta = INT32_MAX;
1396
    else
1397
        delta = (qemu_next_deadline() + 999) / 1000;
1398

    
1399
    if (active_timers[QEMU_TIMER_REALTIME]) {
1400
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1401
                 qemu_get_clock(rt_clock))*1000;
1402
        if (rtdelta < delta)
1403
            delta = rtdelta;
1404
    }
1405

    
1406
    if (delta < MIN_TIMER_REARM_US)
1407
        delta = MIN_TIMER_REARM_US;
1408

    
1409
    return delta;
1410
}
1411
#endif
1412

    
1413
#ifndef _WIN32
1414

    
1415
/* Sets a specific flag */
1416
static int fcntl_setfl(int fd, int flag)
1417
{
1418
    int flags;
1419

    
1420
    flags = fcntl(fd, F_GETFL);
1421
    if (flags == -1)
1422
        return -errno;
1423

    
1424
    if (fcntl(fd, F_SETFL, flags | flag) == -1)
1425
        return -errno;
1426

    
1427
    return 0;
1428
}
1429

    
1430
#if defined(__linux__)
1431

    
1432
#define RTC_FREQ 1024
1433

    
1434
static void enable_sigio_timer(int fd)
1435
{
1436
    struct sigaction act;
1437

    
1438
    /* timer signal */
1439
    sigfillset(&act.sa_mask);
1440
    act.sa_flags = 0;
1441
    act.sa_handler = host_alarm_handler;
1442

    
1443
    sigaction(SIGIO, &act, NULL);
1444
    fcntl_setfl(fd, O_ASYNC);
1445
    fcntl(fd, F_SETOWN, getpid());
1446
}
1447

    
1448
static int hpet_start_timer(struct qemu_alarm_timer *t)
1449
{
1450
    struct hpet_info info;
1451
    int r, fd;
1452

    
1453
    fd = open("/dev/hpet", O_RDONLY);
1454
    if (fd < 0)
1455
        return -1;
1456

    
1457
    /* Set frequency */
1458
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1459
    if (r < 0) {
1460
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1461
                "error, but for better emulation accuracy type:\n"
1462
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1463
        goto fail;
1464
    }
1465

    
1466
    /* Check capabilities */
1467
    r = ioctl(fd, HPET_INFO, &info);
1468
    if (r < 0)
1469
        goto fail;
1470

    
1471
    /* Enable periodic mode */
1472
    r = ioctl(fd, HPET_EPI, 0);
1473
    if (info.hi_flags && (r < 0))
1474
        goto fail;
1475

    
1476
    /* Enable interrupt */
1477
    r = ioctl(fd, HPET_IE_ON, 0);
1478
    if (r < 0)
1479
        goto fail;
1480

    
1481
    enable_sigio_timer(fd);
1482
    t->priv = (void *)(long)fd;
1483

    
1484
    return 0;
1485
fail:
1486
    close(fd);
1487
    return -1;
1488
}
1489

    
1490
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1491
{
1492
    int fd = (long)t->priv;
1493

    
1494
    close(fd);
1495
}
1496

    
1497
static int rtc_start_timer(struct qemu_alarm_timer *t)
1498
{
1499
    int rtc_fd;
1500
    unsigned long current_rtc_freq = 0;
1501

    
1502
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1503
    if (rtc_fd < 0)
1504
        return -1;
1505
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1506
    if (current_rtc_freq != RTC_FREQ &&
1507
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1508
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1509
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1510
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1511
        goto fail;
1512
    }
1513
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1514
    fail:
1515
        close(rtc_fd);
1516
        return -1;
1517
    }
1518

    
1519
    enable_sigio_timer(rtc_fd);
1520

    
1521
    t->priv = (void *)(long)rtc_fd;
1522

    
1523
    return 0;
1524
}
1525

    
1526
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1527
{
1528
    int rtc_fd = (long)t->priv;
1529

    
1530
    close(rtc_fd);
1531
}
1532

    
1533
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1534
{
1535
    struct sigevent ev;
1536
    timer_t host_timer;
1537
    struct sigaction act;
1538

    
1539
    sigfillset(&act.sa_mask);
1540
    act.sa_flags = 0;
1541
    act.sa_handler = host_alarm_handler;
1542

    
1543
    sigaction(SIGALRM, &act, NULL);
1544

    
1545
    ev.sigev_value.sival_int = 0;
1546
    ev.sigev_notify = SIGEV_SIGNAL;
1547
    ev.sigev_signo = SIGALRM;
1548

    
1549
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1550
        perror("timer_create");
1551

    
1552
        /* disable dynticks */
1553
        fprintf(stderr, "Dynamic Ticks disabled\n");
1554

    
1555
        return -1;
1556
    }
1557

    
1558
    t->priv = (void *)(long)host_timer;
1559

    
1560
    return 0;
1561
}
1562

    
1563
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1564
{
1565
    timer_t host_timer = (timer_t)(long)t->priv;
1566

    
1567
    timer_delete(host_timer);
1568
}
1569

    
1570
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1571
{
1572
    timer_t host_timer = (timer_t)(long)t->priv;
1573
    struct itimerspec timeout;
1574
    int64_t nearest_delta_us = INT64_MAX;
1575
    int64_t current_us;
1576

    
1577
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1578
                !active_timers[QEMU_TIMER_VIRTUAL])
1579
        return;
1580

    
1581
    nearest_delta_us = qemu_next_deadline_dyntick();
1582

    
1583
    /* check whether a timer is already running */
1584
    if (timer_gettime(host_timer, &timeout)) {
1585
        perror("gettime");
1586
        fprintf(stderr, "Internal timer error: aborting\n");
1587
        exit(1);
1588
    }
1589
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1590
    if (current_us && current_us <= nearest_delta_us)
1591
        return;
1592

    
1593
    timeout.it_interval.tv_sec = 0;
1594
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1595
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1596
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1597
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1598
        perror("settime");
1599
        fprintf(stderr, "Internal timer error: aborting\n");
1600
        exit(1);
1601
    }
1602
}
1603

    
1604
#endif /* defined(__linux__) */
1605

    
1606
static int unix_start_timer(struct qemu_alarm_timer *t)
1607
{
1608
    struct sigaction act;
1609
    struct itimerval itv;
1610
    int err;
1611

    
1612
    /* timer signal */
1613
    sigfillset(&act.sa_mask);
1614
    act.sa_flags = 0;
1615
    act.sa_handler = host_alarm_handler;
1616

    
1617
    sigaction(SIGALRM, &act, NULL);
1618

    
1619
    itv.it_interval.tv_sec = 0;
1620
    /* for i386 kernel 2.6 to get 1 ms */
1621
    itv.it_interval.tv_usec = 999;
1622
    itv.it_value.tv_sec = 0;
1623
    itv.it_value.tv_usec = 10 * 1000;
1624

    
1625
    err = setitimer(ITIMER_REAL, &itv, NULL);
1626
    if (err)
1627
        return -1;
1628

    
1629
    return 0;
1630
}
1631

    
1632
static void unix_stop_timer(struct qemu_alarm_timer *t)
1633
{
1634
    struct itimerval itv;
1635

    
1636
    memset(&itv, 0, sizeof(itv));
1637
    setitimer(ITIMER_REAL, &itv, NULL);
1638
}
1639

    
1640
#endif /* !defined(_WIN32) */
1641

    
1642
static void try_to_rearm_timer(void *opaque)
1643
{
1644
    struct qemu_alarm_timer *t = opaque;
1645
#ifndef _WIN32
1646
    ssize_t len;
1647

    
1648
    /* Drain the notify pipe */
1649
    do {
1650
        char buffer[512];
1651
        len = read(alarm_timer_rfd, buffer, sizeof(buffer));
1652
    } while ((len == -1 && errno == EINTR) || len > 0);
1653
#endif
1654

    
1655
    if (t->flags & ALARM_FLAG_EXPIRED) {
1656
        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;
1657
        qemu_rearm_alarm_timer(alarm_timer);
1658
    }
1659
}
1660

    
1661
#ifdef _WIN32
1662

    
1663
static int win32_start_timer(struct qemu_alarm_timer *t)
1664
{
1665
    TIMECAPS tc;
1666
    struct qemu_alarm_win32 *data = t->priv;
1667
    UINT flags;
1668

    
1669
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1670
    if (!data->host_alarm) {
1671
        perror("Failed CreateEvent");
1672
        return -1;
1673
    }
1674

    
1675
    memset(&tc, 0, sizeof(tc));
1676
    timeGetDevCaps(&tc, sizeof(tc));
1677

    
1678
    if (data->period < tc.wPeriodMin)
1679
        data->period = tc.wPeriodMin;
1680

    
1681
    timeBeginPeriod(data->period);
1682

    
1683
    flags = TIME_CALLBACK_FUNCTION;
1684
    if (alarm_has_dynticks(t))
1685
        flags |= TIME_ONESHOT;
1686
    else
1687
        flags |= TIME_PERIODIC;
1688

    
1689
    data->timerId = timeSetEvent(1,         // interval (ms)
1690
                        data->period,       // resolution
1691
                        host_alarm_handler, // function
1692
                        (DWORD)t,           // parameter
1693
                        flags);
1694

    
1695
    if (!data->timerId) {
1696
        perror("Failed to initialize win32 alarm timer");
1697

    
1698
        timeEndPeriod(data->period);
1699
        CloseHandle(data->host_alarm);
1700
        return -1;
1701
    }
1702

    
1703
    qemu_add_wait_object(data->host_alarm, try_to_rearm_timer, t);
1704

    
1705
    return 0;
1706
}
1707

    
1708
static void win32_stop_timer(struct qemu_alarm_timer *t)
1709
{
1710
    struct qemu_alarm_win32 *data = t->priv;
1711

    
1712
    timeKillEvent(data->timerId);
1713
    timeEndPeriod(data->period);
1714

    
1715
    CloseHandle(data->host_alarm);
1716
}
1717

    
1718
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1719
{
1720
    struct qemu_alarm_win32 *data = t->priv;
1721
    uint64_t nearest_delta_us;
1722

    
1723
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1724
                !active_timers[QEMU_TIMER_VIRTUAL])
1725
        return;
1726

    
1727
    nearest_delta_us = qemu_next_deadline_dyntick();
1728
    nearest_delta_us /= 1000;
1729

    
1730
    timeKillEvent(data->timerId);
1731

    
1732
    data->timerId = timeSetEvent(1,
1733
                        data->period,
1734
                        host_alarm_handler,
1735
                        (DWORD)t,
1736
                        TIME_ONESHOT | TIME_PERIODIC);
1737

    
1738
    if (!data->timerId) {
1739
        perror("Failed to re-arm win32 alarm timer");
1740

    
1741
        timeEndPeriod(data->period);
1742
        CloseHandle(data->host_alarm);
1743
        exit(1);
1744
    }
1745
}
1746

    
1747
#endif /* _WIN32 */
1748

    
1749
static int init_timer_alarm(void)
1750
{
1751
    struct qemu_alarm_timer *t = NULL;
1752
    int i, err = -1;
1753

    
1754
#ifndef _WIN32
1755
    int fds[2];
1756

    
1757
    err = pipe(fds);
1758
    if (err == -1)
1759
        return -errno;
1760

    
1761
    err = fcntl_setfl(fds[0], O_NONBLOCK);
1762
    if (err < 0)
1763
        goto fail;
1764

    
1765
    err = fcntl_setfl(fds[1], O_NONBLOCK);
1766
    if (err < 0)
1767
        goto fail;
1768

    
1769
    alarm_timer_rfd = fds[0];
1770
    alarm_timer_wfd = fds[1];
1771
#endif
1772

    
1773
    for (i = 0; alarm_timers[i].name; i++) {
1774
        t = &alarm_timers[i];
1775

    
1776
        err = t->start(t);
1777
        if (!err)
1778
            break;
1779
    }
1780

    
1781
    if (err) {
1782
        err = -ENOENT;
1783
        goto fail;
1784
    }
1785

    
1786
#ifndef _WIN32
1787
    qemu_set_fd_handler2(alarm_timer_rfd, NULL,
1788
                         try_to_rearm_timer, NULL, t);
1789
#endif
1790

    
1791
    alarm_timer = t;
1792

    
1793
    return 0;
1794

    
1795
fail:
1796
#ifndef _WIN32
1797
    close(fds[0]);
1798
    close(fds[1]);
1799
#endif
1800
    return err;
1801
}
1802

    
1803
static void quit_timers(void)
1804
{
1805
    alarm_timer->stop(alarm_timer);
1806
    alarm_timer = NULL;
1807
}
1808

    
1809
/***********************************************************/
1810
/* host time/date access */
1811
void qemu_get_timedate(struct tm *tm, int offset)
1812
{
1813
    time_t ti;
1814
    struct tm *ret;
1815

    
1816
    time(&ti);
1817
    ti += offset;
1818
    if (rtc_date_offset == -1) {
1819
        if (rtc_utc)
1820
            ret = gmtime(&ti);
1821
        else
1822
            ret = localtime(&ti);
1823
    } else {
1824
        ti -= rtc_date_offset;
1825
        ret = gmtime(&ti);
1826
    }
1827

    
1828
    memcpy(tm, ret, sizeof(struct tm));
1829
}
1830

    
1831
int qemu_timedate_diff(struct tm *tm)
1832
{
1833
    time_t seconds;
1834

    
1835
    if (rtc_date_offset == -1)
1836
        if (rtc_utc)
1837
            seconds = mktimegm(tm);
1838
        else
1839
            seconds = mktime(tm);
1840
    else
1841
        seconds = mktimegm(tm) + rtc_date_offset;
1842

    
1843
    return seconds - time(NULL);
1844
}
1845

    
1846
#ifdef _WIN32
1847
static void socket_cleanup(void)
1848
{
1849
    WSACleanup();
1850
}
1851

    
1852
static int socket_init(void)
1853
{
1854
    WSADATA Data;
1855
    int ret, err;
1856

    
1857
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1858
    if (ret != 0) {
1859
        err = WSAGetLastError();
1860
        fprintf(stderr, "WSAStartup: %d\n", err);
1861
        return -1;
1862
    }
1863
    atexit(socket_cleanup);
1864
    return 0;
1865
}
1866
#endif
1867

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

    
1872
    q = buf;
1873
    while (*p != '\0' && *p != '=') {
1874
        if (q && (q - buf) < buf_size - 1)
1875
            *q++ = *p;
1876
        p++;
1877
    }
1878
    if (q)
1879
        *q = '\0';
1880

    
1881
    return p;
1882
}
1883

    
1884
const char *get_opt_value(char *buf, int buf_size, const char *p)
1885
{
1886
    char *q;
1887

    
1888
    q = buf;
1889
    while (*p != '\0') {
1890
        if (*p == ',') {
1891
            if (*(p + 1) != ',')
1892
                break;
1893
            p++;
1894
        }
1895
        if (q && (q - buf) < buf_size - 1)
1896
            *q++ = *p;
1897
        p++;
1898
    }
1899
    if (q)
1900
        *q = '\0';
1901

    
1902
    return p;
1903
}
1904

    
1905
int get_param_value(char *buf, int buf_size,
1906
                    const char *tag, const char *str)
1907
{
1908
    const char *p;
1909
    char option[128];
1910

    
1911
    p = str;
1912
    for(;;) {
1913
        p = get_opt_name(option, sizeof(option), p);
1914
        if (*p != '=')
1915
            break;
1916
        p++;
1917
        if (!strcmp(tag, option)) {
1918
            (void)get_opt_value(buf, buf_size, p);
1919
            return strlen(buf);
1920
        } else {
1921
            p = get_opt_value(NULL, 0, p);
1922
        }
1923
        if (*p != ',')
1924
            break;
1925
        p++;
1926
    }
1927
    return 0;
1928
}
1929

    
1930
int check_params(char *buf, int buf_size,
1931
                 const char * const *params, const char *str)
1932
{
1933
    const char *p;
1934
    int i;
1935

    
1936
    p = str;
1937
    for(;;) {
1938
        p = get_opt_name(buf, buf_size, p);
1939
        if (*p != '=')
1940
            return -1;
1941
        p++;
1942
        for(i = 0; params[i] != NULL; i++)
1943
            if (!strcmp(params[i], buf))
1944
                break;
1945
        if (params[i] == NULL)
1946
            return -1;
1947
        p = get_opt_value(NULL, 0, p);
1948
        if (*p != ',')
1949
            break;
1950
        p++;
1951
    }
1952
    return 0;
1953
}
1954

    
1955
/***********************************************************/
1956
/* Bluetooth support */
1957
static int nb_hcis;
1958
static int cur_hci;
1959
static struct HCIInfo *hci_table[MAX_NICS];
1960

    
1961
static struct bt_vlan_s {
1962
    struct bt_scatternet_s net;
1963
    int id;
1964
    struct bt_vlan_s *next;
1965
} *first_bt_vlan;
1966

    
1967
/* find or alloc a new bluetooth "VLAN" */
1968
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1969
{
1970
    struct bt_vlan_s **pvlan, *vlan;
1971
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1972
        if (vlan->id == id)
1973
            return &vlan->net;
1974
    }
1975
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1976
    vlan->id = id;
1977
    pvlan = &first_bt_vlan;
1978
    while (*pvlan != NULL)
1979
        pvlan = &(*pvlan)->next;
1980
    *pvlan = vlan;
1981
    return &vlan->net;
1982
}
1983

    
1984
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1985
{
1986
}
1987

    
1988
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1989
{
1990
    return -ENOTSUP;
1991
}
1992

    
1993
static struct HCIInfo null_hci = {
1994
    .cmd_send = null_hci_send,
1995
    .sco_send = null_hci_send,
1996
    .acl_send = null_hci_send,
1997
    .bdaddr_set = null_hci_addr_set,
1998
};
1999

    
2000
struct HCIInfo *qemu_next_hci(void)
2001
{
2002
    if (cur_hci == nb_hcis)
2003
        return &null_hci;
2004

    
2005
    return hci_table[cur_hci++];
2006
}
2007

    
2008
static struct HCIInfo *hci_init(const char *str)
2009
{
2010
    char *endp;
2011
    struct bt_scatternet_s *vlan = 0;
2012

    
2013
    if (!strcmp(str, "null"))
2014
        /* null */
2015
        return &null_hci;
2016
    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))
2017
        /* host[:hciN] */
2018
        return bt_host_hci(str[4] ? str + 5 : "hci0");
2019
    else if (!strncmp(str, "hci", 3)) {
2020
        /* hci[,vlan=n] */
2021
        if (str[3]) {
2022
            if (!strncmp(str + 3, ",vlan=", 6)) {
2023
                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));
2024
                if (*endp)
2025
                    vlan = 0;
2026
            }
2027
        } else
2028
            vlan = qemu_find_bt_vlan(0);
2029
        if (vlan)
2030
           return bt_new_hci(vlan);
2031
    }
2032

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

    
2035
    return 0;
2036
}
2037

    
2038
static int bt_hci_parse(const char *str)
2039
{
2040
    struct HCIInfo *hci;
2041
    bdaddr_t bdaddr;
2042

    
2043
    if (nb_hcis >= MAX_NICS) {
2044
        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);
2045
        return -1;
2046
    }
2047

    
2048
    hci = hci_init(str);
2049
    if (!hci)
2050
        return -1;
2051

    
2052
    bdaddr.b[0] = 0x52;
2053
    bdaddr.b[1] = 0x54;
2054
    bdaddr.b[2] = 0x00;
2055
    bdaddr.b[3] = 0x12;
2056
    bdaddr.b[4] = 0x34;
2057
    bdaddr.b[5] = 0x56 + nb_hcis;
2058
    hci->bdaddr_set(hci, bdaddr.b);
2059

    
2060
    hci_table[nb_hcis++] = hci;
2061

    
2062
    return 0;
2063
}
2064

    
2065
static void bt_vhci_add(int vlan_id)
2066
{
2067
    struct bt_scatternet_s *vlan = qemu_find_bt_vlan(vlan_id);
2068

    
2069
    if (!vlan->slave)
2070
        fprintf(stderr, "qemu: warning: adding a VHCI to "
2071
                        "an empty scatternet %i\n", vlan_id);
2072

    
2073
    bt_vhci_init(bt_new_hci(vlan));
2074
}
2075

    
2076
static struct bt_device_s *bt_device_add(const char *opt)
2077
{
2078
    struct bt_scatternet_s *vlan;
2079
    int vlan_id = 0;
2080
    char *endp = strstr(opt, ",vlan=");
2081
    int len = (endp ? endp - opt : strlen(opt)) + 1;
2082
    char devname[10];
2083

    
2084
    pstrcpy(devname, MIN(sizeof(devname), len), opt);
2085

    
2086
    if (endp) {
2087
        vlan_id = strtol(endp + 6, &endp, 0);
2088
        if (*endp) {
2089
            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");
2090
            return 0;
2091
        }
2092
    }
2093

    
2094
    vlan = qemu_find_bt_vlan(vlan_id);
2095

    
2096
    if (!vlan->slave)
2097
        fprintf(stderr, "qemu: warning: adding a slave device to "
2098
                        "an empty scatternet %i\n", vlan_id);
2099

    
2100
    if (!strcmp(devname, "keyboard"))
2101
        return bt_keyboard_init(vlan);
2102

    
2103
    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);
2104
    return 0;
2105
}
2106

    
2107
static int bt_parse(const char *opt)
2108
{
2109
    const char *endp, *p;
2110
    int vlan;
2111

    
2112
    if (strstart(opt, "hci", &endp)) {
2113
        if (!*endp || *endp == ',') {
2114
            if (*endp)
2115
                if (!strstart(endp, ",vlan=", 0))
2116
                    opt = endp + 1;
2117

    
2118
            return bt_hci_parse(opt);
2119
       }
2120
    } else if (strstart(opt, "vhci", &endp)) {
2121
        if (!*endp || *endp == ',') {
2122
            if (*endp) {
2123
                if (strstart(endp, ",vlan=", &p)) {
2124
                    vlan = strtol(p, (char **) &endp, 0);
2125
                    if (*endp) {
2126
                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);
2127
                        return 1;
2128
                    }
2129
                } else {
2130
                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);
2131
                    return 1;
2132
                }
2133
            } else
2134
                vlan = 0;
2135

    
2136
            bt_vhci_add(vlan);
2137
            return 0;
2138
        }
2139
    } else if (strstart(opt, "device:", &endp))
2140
        return !bt_device_add(endp);
2141

    
2142
    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);
2143
    return 1;
2144
}
2145

    
2146
/***********************************************************/
2147
/* QEMU Block devices */
2148

    
2149
#define HD_ALIAS "index=%d,media=disk"
2150
#define CDROM_ALIAS "index=2,media=cdrom"
2151
#define FD_ALIAS "index=%d,if=floppy"
2152
#define PFLASH_ALIAS "if=pflash"
2153
#define MTD_ALIAS "if=mtd"
2154
#define SD_ALIAS "index=0,if=sd"
2155

    
2156
static int drive_opt_get_free_idx(void)
2157
{
2158
    int index;
2159

    
2160
    for (index = 0; index < MAX_DRIVES; index++)
2161
        if (!drives_opt[index].used) {
2162
            drives_opt[index].used = 1;
2163
            return index;
2164
        }
2165

    
2166
    return -1;
2167
}
2168

    
2169
static int drive_get_free_idx(void)
2170
{
2171
    int index;
2172

    
2173
    for (index = 0; index < MAX_DRIVES; index++)
2174
        if (!drives_table[index].used) {
2175
            drives_table[index].used = 1;
2176
            return index;
2177
        }
2178

    
2179
    return -1;
2180
}
2181

    
2182
int drive_add(const char *file, const char *fmt, ...)
2183
{
2184
    va_list ap;
2185
    int index = drive_opt_get_free_idx();
2186

    
2187
    if (nb_drives_opt >= MAX_DRIVES || index == -1) {
2188
        fprintf(stderr, "qemu: too many drives\n");
2189
        return -1;
2190
    }
2191

    
2192
    drives_opt[index].file = file;
2193
    va_start(ap, fmt);
2194
    vsnprintf(drives_opt[index].opt,
2195
              sizeof(drives_opt[0].opt), fmt, ap);
2196
    va_end(ap);
2197

    
2198
    nb_drives_opt++;
2199
    return index;
2200
}
2201

    
2202
void drive_remove(int index)
2203
{
2204
    drives_opt[index].used = 0;
2205
    nb_drives_opt--;
2206
}
2207

    
2208
int drive_get_index(BlockInterfaceType type, int bus, int unit)
2209
{
2210
    int index;
2211

    
2212
    /* seek interface, bus and unit */
2213

    
2214
    for (index = 0; index < MAX_DRIVES; index++)
2215
        if (drives_table[index].type == type &&
2216
            drives_table[index].bus == bus &&
2217
            drives_table[index].unit == unit &&
2218
            drives_table[index].used)
2219
        return index;
2220

    
2221
    return -1;
2222
}
2223

    
2224
int drive_get_max_bus(BlockInterfaceType type)
2225
{
2226
    int max_bus;
2227
    int index;
2228

    
2229
    max_bus = -1;
2230
    for (index = 0; index < nb_drives; index++) {
2231
        if(drives_table[index].type == type &&
2232
           drives_table[index].bus > max_bus)
2233
            max_bus = drives_table[index].bus;
2234
    }
2235
    return max_bus;
2236
}
2237

    
2238
const char *drive_get_serial(BlockDriverState *bdrv)
2239
{
2240
    int index;
2241

    
2242
    for (index = 0; index < nb_drives; index++)
2243
        if (drives_table[index].bdrv == bdrv)
2244
            return drives_table[index].serial;
2245

    
2246
    return "\0";
2247
}
2248

    
2249
BlockInterfaceErrorAction drive_get_onerror(BlockDriverState *bdrv)
2250
{
2251
    int index;
2252

    
2253
    for (index = 0; index < nb_drives; index++)
2254
        if (drives_table[index].bdrv == bdrv)
2255
            return drives_table[index].onerror;
2256

    
2257
    return BLOCK_ERR_STOP_ENOSPC;
2258
}
2259

    
2260
static void bdrv_format_print(void *opaque, const char *name)
2261
{
2262
    fprintf(stderr, " %s", name);
2263
}
2264

    
2265
void drive_uninit(BlockDriverState *bdrv)
2266
{
2267
    int i;
2268

    
2269
    for (i = 0; i < MAX_DRIVES; i++)
2270
        if (drives_table[i].bdrv == bdrv) {
2271
            drives_table[i].bdrv = NULL;
2272
            drives_table[i].used = 0;
2273
            drive_remove(drives_table[i].drive_opt_idx);
2274
            nb_drives--;
2275
            break;
2276
        }
2277
}
2278

    
2279
int drive_init(struct drive_opt *arg, int snapshot, void *opaque)
2280
{
2281
    char buf[128];
2282
    char file[1024];
2283
    char devname[128];
2284
    char serial[21];
2285
    const char *mediastr = "";
2286
    BlockInterfaceType type;
2287
    enum { MEDIA_DISK, MEDIA_CDROM } media;
2288
    int bus_id, unit_id;
2289
    int cyls, heads, secs, translation;
2290
    BlockDriverState *bdrv;
2291
    BlockDriver *drv = NULL;
2292
    QEMUMachine *machine = opaque;
2293
    int max_devs;
2294
    int index;
2295
    int cache;
2296
    int bdrv_flags, onerror;
2297
    int drives_table_idx;
2298
    char *str = arg->opt;
2299
    static const char * const params[] = { "bus", "unit", "if", "index",
2300
                                           "cyls", "heads", "secs", "trans",
2301
                                           "media", "snapshot", "file",
2302
                                           "cache", "format", "serial", "werror",
2303
                                           NULL };
2304

    
2305
    if (check_params(buf, sizeof(buf), params, str) < 0) {
2306
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
2307
                         buf, str);
2308
         return -1;
2309
    }
2310

    
2311
    file[0] = 0;
2312
    cyls = heads = secs = 0;
2313
    bus_id = 0;
2314
    unit_id = -1;
2315
    translation = BIOS_ATA_TRANSLATION_AUTO;
2316
    index = -1;
2317
    cache = 3;
2318

    
2319
    if (machine->use_scsi) {
2320
        type = IF_SCSI;
2321
        max_devs = MAX_SCSI_DEVS;
2322
        pstrcpy(devname, sizeof(devname), "scsi");
2323
    } else {
2324
        type = IF_IDE;
2325
        max_devs = MAX_IDE_DEVS;
2326
        pstrcpy(devname, sizeof(devname), "ide");
2327
    }
2328
    media = MEDIA_DISK;
2329

    
2330
    /* extract parameters */
2331

    
2332
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2333
        bus_id = strtol(buf, NULL, 0);
2334
        if (bus_id < 0) {
2335
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2336
            return -1;
2337
        }
2338
    }
2339

    
2340
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2341
        unit_id = strtol(buf, NULL, 0);
2342
        if (unit_id < 0) {
2343
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2344
            return -1;
2345
        }
2346
    }
2347

    
2348
    if (get_param_value(buf, sizeof(buf), "if", str)) {
2349
        pstrcpy(devname, sizeof(devname), buf);
2350
        if (!strcmp(buf, "ide")) {
2351
            type = IF_IDE;
2352
            max_devs = MAX_IDE_DEVS;
2353
        } else if (!strcmp(buf, "scsi")) {
2354
            type = IF_SCSI;
2355
            max_devs = MAX_SCSI_DEVS;
2356
        } else if (!strcmp(buf, "floppy")) {
2357
            type = IF_FLOPPY;
2358
            max_devs = 0;
2359
        } else if (!strcmp(buf, "pflash")) {
2360
            type = IF_PFLASH;
2361
            max_devs = 0;
2362
        } else if (!strcmp(buf, "mtd")) {
2363
            type = IF_MTD;
2364
            max_devs = 0;
2365
        } else if (!strcmp(buf, "sd")) {
2366
            type = IF_SD;
2367
            max_devs = 0;
2368
        } else if (!strcmp(buf, "virtio")) {
2369
            type = IF_VIRTIO;
2370
            max_devs = 0;
2371
        } else {
2372
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
2373
            return -1;
2374
        }
2375
    }
2376

    
2377
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2378
        index = strtol(buf, NULL, 0);
2379
        if (index < 0) {
2380
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2381
            return -1;
2382
        }
2383
    }
2384

    
2385
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2386
        cyls = strtol(buf, NULL, 0);
2387
    }
2388

    
2389
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2390
        heads = strtol(buf, NULL, 0);
2391
    }
2392

    
2393
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2394
        secs = strtol(buf, NULL, 0);
2395
    }
2396

    
2397
    if (cyls || heads || secs) {
2398
        if (cyls < 1 || cyls > 16383) {
2399
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2400
            return -1;
2401
        }
2402
        if (heads < 1 || heads > 16) {
2403
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2404
            return -1;
2405
        }
2406
        if (secs < 1 || secs > 63) {
2407
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2408
            return -1;
2409
        }
2410
    }
2411

    
2412
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2413
        if (!cyls) {
2414
            fprintf(stderr,
2415
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2416
                    str);
2417
            return -1;
2418
        }
2419
        if (!strcmp(buf, "none"))
2420
            translation = BIOS_ATA_TRANSLATION_NONE;
2421
        else if (!strcmp(buf, "lba"))
2422
            translation = BIOS_ATA_TRANSLATION_LBA;
2423
        else if (!strcmp(buf, "auto"))
2424
            translation = BIOS_ATA_TRANSLATION_AUTO;
2425
        else {
2426
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2427
            return -1;
2428
        }
2429
    }
2430

    
2431
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2432
        if (!strcmp(buf, "disk")) {
2433
            media = MEDIA_DISK;
2434
        } else if (!strcmp(buf, "cdrom")) {
2435
            if (cyls || secs || heads) {
2436
                fprintf(stderr,
2437
                        "qemu: '%s' invalid physical CHS format\n", str);
2438
                return -1;
2439
            }
2440
            media = MEDIA_CDROM;
2441
        } else {
2442
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2443
            return -1;
2444
        }
2445
    }
2446

    
2447
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2448
        if (!strcmp(buf, "on"))
2449
            snapshot = 1;
2450
        else if (!strcmp(buf, "off"))
2451
            snapshot = 0;
2452
        else {
2453
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2454
            return -1;
2455
        }
2456
    }
2457

    
2458
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2459
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2460
            cache = 0;
2461
        else if (!strcmp(buf, "writethrough"))
2462
            cache = 1;
2463
        else if (!strcmp(buf, "writeback"))
2464
            cache = 2;
2465
        else {
2466
           fprintf(stderr, "qemu: invalid cache option\n");
2467
           return -1;
2468
        }
2469
    }
2470

    
2471
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2472
       if (strcmp(buf, "?") == 0) {
2473
            fprintf(stderr, "qemu: Supported formats:");
2474
            bdrv_iterate_format(bdrv_format_print, NULL);
2475
            fprintf(stderr, "\n");
2476
            return -1;
2477
        }
2478
        drv = bdrv_find_format(buf);
2479
        if (!drv) {
2480
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2481
            return -1;
2482
        }
2483
    }
2484

    
2485
    if (arg->file == NULL)
2486
        get_param_value(file, sizeof(file), "file", str);
2487
    else
2488
        pstrcpy(file, sizeof(file), arg->file);
2489

    
2490
    if (!get_param_value(serial, sizeof(serial), "serial", str))
2491
            memset(serial, 0,  sizeof(serial));
2492

    
2493
    onerror = BLOCK_ERR_STOP_ENOSPC;
2494
    if (get_param_value(buf, sizeof(serial), "werror", str)) {
2495
        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO) {
2496
            fprintf(stderr, "werror is no supported by this format\n");
2497
            return -1;
2498
        }
2499
        if (!strcmp(buf, "ignore"))
2500
            onerror = BLOCK_ERR_IGNORE;
2501
        else if (!strcmp(buf, "enospc"))
2502
            onerror = BLOCK_ERR_STOP_ENOSPC;
2503
        else if (!strcmp(buf, "stop"))
2504
            onerror = BLOCK_ERR_STOP_ANY;
2505
        else if (!strcmp(buf, "report"))
2506
            onerror = BLOCK_ERR_REPORT;
2507
        else {
2508
            fprintf(stderr, "qemu: '%s' invalid write error action\n", buf);
2509
            return -1;
2510
        }
2511
    }
2512

    
2513
    /* compute bus and unit according index */
2514

    
2515
    if (index != -1) {
2516
        if (bus_id != 0 || unit_id != -1) {
2517
            fprintf(stderr,
2518
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2519
            return -1;
2520
        }
2521
        if (max_devs == 0)
2522
        {
2523
            unit_id = index;
2524
            bus_id = 0;
2525
        } else {
2526
            unit_id = index % max_devs;
2527
            bus_id = index / max_devs;
2528
        }
2529
    }
2530

    
2531
    /* if user doesn't specify a unit_id,
2532
     * try to find the first free
2533
     */
2534

    
2535
    if (unit_id == -1) {
2536
       unit_id = 0;
2537
       while (drive_get_index(type, bus_id, unit_id) != -1) {
2538
           unit_id++;
2539
           if (max_devs && unit_id >= max_devs) {
2540
               unit_id -= max_devs;
2541
               bus_id++;
2542
           }
2543
       }
2544
    }
2545

    
2546
    /* check unit id */
2547

    
2548
    if (max_devs && unit_id >= max_devs) {
2549
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2550
                        str, unit_id, max_devs - 1);
2551
        return -1;
2552
    }
2553

    
2554
    /*
2555
     * ignore multiple definitions
2556
     */
2557

    
2558
    if (drive_get_index(type, bus_id, unit_id) != -1)
2559
        return -2;
2560

    
2561
    /* init */
2562

    
2563
    if (type == IF_IDE || type == IF_SCSI)
2564
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2565
    if (max_devs)
2566
        snprintf(buf, sizeof(buf), "%s%i%s%i",
2567
                 devname, bus_id, mediastr, unit_id);
2568
    else
2569
        snprintf(buf, sizeof(buf), "%s%s%i",
2570
                 devname, mediastr, unit_id);
2571
    bdrv = bdrv_new(buf);
2572
    drives_table_idx = drive_get_free_idx();
2573
    drives_table[drives_table_idx].bdrv = bdrv;
2574
    drives_table[drives_table_idx].type = type;
2575
    drives_table[drives_table_idx].bus = bus_id;
2576
    drives_table[drives_table_idx].unit = unit_id;
2577
    drives_table[drives_table_idx].onerror = onerror;
2578
    drives_table[drives_table_idx].drive_opt_idx = arg - drives_opt;
2579
    strncpy(drives_table[nb_drives].serial, serial, sizeof(serial));
2580
    nb_drives++;
2581

    
2582
    switch(type) {
2583
    case IF_IDE:
2584
    case IF_SCSI:
2585
        switch(media) {
2586
        case MEDIA_DISK:
2587
            if (cyls != 0) {
2588
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2589
                bdrv_set_translation_hint(bdrv, translation);
2590
            }
2591
            break;
2592
        case MEDIA_CDROM:
2593
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2594
            break;
2595
        }
2596
        break;
2597
    case IF_SD:
2598
        /* FIXME: This isn't really a floppy, but it's a reasonable
2599
           approximation.  */
2600
    case IF_FLOPPY:
2601
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2602
        break;
2603
    case IF_PFLASH:
2604
    case IF_MTD:
2605
    case IF_VIRTIO:
2606
        break;
2607
    }
2608
    if (!file[0])
2609
        return -2;
2610
    bdrv_flags = 0;
2611
    if (snapshot) {
2612
        bdrv_flags |= BDRV_O_SNAPSHOT;
2613
        cache = 2; /* always use write-back with snapshot */
2614
    }
2615
    if (cache == 0) /* no caching */
2616
        bdrv_flags |= BDRV_O_NOCACHE;
2617
    else if (cache == 2) /* write-back */
2618
        bdrv_flags |= BDRV_O_CACHE_WB;
2619
    else if (cache == 3) /* not specified */
2620
        bdrv_flags |= BDRV_O_CACHE_DEF;
2621
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0) {
2622
        fprintf(stderr, "qemu: could not open disk image %s\n",
2623
                        file);
2624
        return -1;
2625
    }
2626
    if (bdrv_key_required(bdrv))
2627
        autostart = 0;
2628
    return drives_table_idx;
2629
}
2630

    
2631
/***********************************************************/
2632
/* USB devices */
2633

    
2634
static USBPort *used_usb_ports;
2635
static USBPort *free_usb_ports;
2636

    
2637
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2638
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2639
                            usb_attachfn attach)
2640
{
2641
    port->opaque = opaque;
2642
    port->index = index;
2643
    port->attach = attach;
2644
    port->next = free_usb_ports;
2645
    free_usb_ports = port;
2646
}
2647

    
2648
int usb_device_add_dev(USBDevice *dev)
2649
{
2650
    USBPort *port;
2651

    
2652
    /* Find a USB port to add the device to.  */
2653
    port = free_usb_ports;
2654
    if (!port->next) {
2655
        USBDevice *hub;
2656

    
2657
        /* Create a new hub and chain it on.  */
2658
        free_usb_ports = NULL;
2659
        port->next = used_usb_ports;
2660
        used_usb_ports = port;
2661

    
2662
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2663
        usb_attach(port, hub);
2664
        port = free_usb_ports;
2665
    }
2666

    
2667
    free_usb_ports = port->next;
2668
    port->next = used_usb_ports;
2669
    used_usb_ports = port;
2670
    usb_attach(port, dev);
2671
    return 0;
2672
}
2673

    
2674
static void usb_msd_password_cb(void *opaque, int err)
2675
{
2676
    USBDevice *dev = opaque;
2677

    
2678
    if (!err)
2679
        usb_device_add_dev(dev);
2680
    else
2681
        dev->handle_destroy(dev);
2682
}
2683

    
2684
static int usb_device_add(const char *devname, int is_hotplug)
2685
{
2686
    const char *p;
2687
    USBDevice *dev;
2688

    
2689
    if (!free_usb_ports)
2690
        return -1;
2691

    
2692
    if (strstart(devname, "host:", &p)) {
2693
        dev = usb_host_device_open(p);
2694
    } else if (!strcmp(devname, "mouse")) {
2695
        dev = usb_mouse_init();
2696
    } else if (!strcmp(devname, "tablet")) {
2697
        dev = usb_tablet_init();
2698
    } else if (!strcmp(devname, "keyboard")) {
2699
        dev = usb_keyboard_init();
2700
    } else if (strstart(devname, "disk:", &p)) {
2701
        BlockDriverState *bs;
2702

    
2703
        dev = usb_msd_init(p);
2704
        if (!dev)
2705
            return -1;
2706
        bs = usb_msd_get_bdrv(dev);
2707
        if (bdrv_key_required(bs)) {
2708
            autostart = 0;
2709
            if (is_hotplug) {
2710
                monitor_read_bdrv_key_start(cur_mon, bs, usb_msd_password_cb,
2711
                                            dev);
2712
                return 0;
2713
            }
2714
        }
2715
    } else if (!strcmp(devname, "wacom-tablet")) {
2716
        dev = usb_wacom_init();
2717
    } else if (strstart(devname, "serial:", &p)) {
2718
        dev = usb_serial_init(p);
2719
#ifdef CONFIG_BRLAPI
2720
    } else if (!strcmp(devname, "braille")) {
2721
        dev = usb_baum_init();
2722
#endif
2723
    } else if (strstart(devname, "net:", &p)) {
2724
        int nic = nb_nics;
2725

    
2726
        if (net_client_init("nic", p) < 0)
2727
            return -1;
2728
        nd_table[nic].model = "usb";
2729
        dev = usb_net_init(&nd_table[nic]);
2730
    } else if (!strcmp(devname, "bt") || strstart(devname, "bt:", &p)) {
2731
        dev = usb_bt_init(devname[2] ? hci_init(p) :
2732
                        bt_new_hci(qemu_find_bt_vlan(0)));
2733
    } else {
2734
        return -1;
2735
    }
2736
    if (!dev)
2737
        return -1;
2738

    
2739
    return usb_device_add_dev(dev);
2740
}
2741

    
2742
int usb_device_del_addr(int bus_num, int addr)
2743
{
2744
    USBPort *port;
2745
    USBPort **lastp;
2746
    USBDevice *dev;
2747

    
2748
    if (!used_usb_ports)
2749
        return -1;
2750

    
2751
    if (bus_num != 0)
2752
        return -1;
2753

    
2754
    lastp = &used_usb_ports;
2755
    port = used_usb_ports;
2756
    while (port && port->dev->addr != addr) {
2757
        lastp = &port->next;
2758
        port = port->next;
2759
    }
2760

    
2761
    if (!port)
2762
        return -1;
2763

    
2764
    dev = port->dev;
2765
    *lastp = port->next;
2766
    usb_attach(port, NULL);
2767
    dev->handle_destroy(dev);
2768
    port->next = free_usb_ports;
2769
    free_usb_ports = port;
2770
    return 0;
2771
}
2772

    
2773
static int usb_device_del(const char *devname)
2774
{
2775
    int bus_num, addr;
2776
    const char *p;
2777

    
2778
    if (strstart(devname, "host:", &p))
2779
        return usb_host_device_close(p);
2780

    
2781
    if (!used_usb_ports)
2782
        return -1;
2783

    
2784
    p = strchr(devname, '.');
2785
    if (!p)
2786
        return -1;
2787
    bus_num = strtoul(devname, NULL, 0);
2788
    addr = strtoul(p + 1, NULL, 0);
2789

    
2790
    return usb_device_del_addr(bus_num, addr);
2791
}
2792

    
2793
void do_usb_add(Monitor *mon, const char *devname)
2794
{
2795
    usb_device_add(devname, 1);
2796
}
2797

    
2798
void do_usb_del(Monitor *mon, const char *devname)
2799
{
2800
    usb_device_del(devname);
2801
}
2802

    
2803
void usb_info(Monitor *mon)
2804
{
2805
    USBDevice *dev;
2806
    USBPort *port;
2807
    const char *speed_str;
2808

    
2809
    if (!usb_enabled) {
2810
        monitor_printf(mon, "USB support not enabled\n");
2811
        return;
2812
    }
2813

    
2814
    for (port = used_usb_ports; port; port = port->next) {
2815
        dev = port->dev;
2816
        if (!dev)
2817
            continue;
2818
        switch(dev->speed) {
2819
        case USB_SPEED_LOW:
2820
            speed_str = "1.5";
2821
            break;
2822
        case USB_SPEED_FULL:
2823
            speed_str = "12";
2824
            break;
2825
        case USB_SPEED_HIGH:
2826
            speed_str = "480";
2827
            break;
2828
        default:
2829
            speed_str = "?";
2830
            break;
2831
        }
2832
        monitor_printf(mon, "  Device %d.%d, Speed %s Mb/s, Product %s\n",
2833
                       0, dev->addr, speed_str, dev->devname);
2834
    }
2835
}
2836

    
2837
/***********************************************************/
2838
/* PCMCIA/Cardbus */
2839

    
2840
static struct pcmcia_socket_entry_s {
2841
    struct pcmcia_socket_s *socket;
2842
    struct pcmcia_socket_entry_s *next;
2843
} *pcmcia_sockets = 0;
2844

    
2845
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2846
{
2847
    struct pcmcia_socket_entry_s *entry;
2848

    
2849
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2850
    entry->socket = socket;
2851
    entry->next = pcmcia_sockets;
2852
    pcmcia_sockets = entry;
2853
}
2854

    
2855
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2856
{
2857
    struct pcmcia_socket_entry_s *entry, **ptr;
2858

    
2859
    ptr = &pcmcia_sockets;
2860
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2861
        if (entry->socket == socket) {
2862
            *ptr = entry->next;
2863
            qemu_free(entry);
2864
        }
2865
}
2866

    
2867
void pcmcia_info(Monitor *mon)
2868
{
2869
    struct pcmcia_socket_entry_s *iter;
2870

    
2871
    if (!pcmcia_sockets)
2872
        monitor_printf(mon, "No PCMCIA sockets\n");
2873

    
2874
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2875
        monitor_printf(mon, "%s: %s\n", iter->socket->slot_string,
2876
                       iter->socket->attached ? iter->socket->card_string :
2877
                       "Empty");
2878
}
2879

    
2880
/***********************************************************/
2881
/* register display */
2882

    
2883
struct DisplayAllocator default_allocator = {
2884
    defaultallocator_create_displaysurface,
2885
    defaultallocator_resize_displaysurface,
2886
    defaultallocator_free_displaysurface
2887
};
2888

    
2889
void register_displaystate(DisplayState *ds)
2890
{
2891
    DisplayState **s;
2892
    s = &display_state;
2893
    while (*s != NULL)
2894
        s = &(*s)->next;
2895
    ds->next = NULL;
2896
    *s = ds;
2897
}
2898

    
2899
DisplayState *get_displaystate(void)
2900
{
2901
    return display_state;
2902
}
2903

    
2904
DisplayAllocator *register_displayallocator(DisplayState *ds, DisplayAllocator *da)
2905
{
2906
    if(ds->allocator ==  &default_allocator) ds->allocator = da;
2907
    return ds->allocator;
2908
}
2909

    
2910
/* dumb display */
2911

    
2912
static void dumb_display_init(void)
2913
{
2914
    DisplayState *ds = qemu_mallocz(sizeof(DisplayState));
2915
    ds->allocator = &default_allocator;
2916
    ds->surface = qemu_create_displaysurface(ds, 640, 480);
2917
    register_displaystate(ds);
2918
}
2919

    
2920
/***********************************************************/
2921
/* I/O handling */
2922

    
2923
typedef struct IOHandlerRecord {
2924
    int fd;
2925
    IOCanRWHandler *fd_read_poll;
2926
    IOHandler *fd_read;
2927
    IOHandler *fd_write;
2928
    int deleted;
2929
    void *opaque;
2930
    /* temporary data */
2931
    struct pollfd *ufd;
2932
    struct IOHandlerRecord *next;
2933
} IOHandlerRecord;
2934

    
2935
static IOHandlerRecord *first_io_handler;
2936

    
2937
/* XXX: fd_read_poll should be suppressed, but an API change is
2938
   necessary in the character devices to suppress fd_can_read(). */
2939
int qemu_set_fd_handler2(int fd,
2940
                         IOCanRWHandler *fd_read_poll,
2941
                         IOHandler *fd_read,
2942
                         IOHandler *fd_write,
2943
                         void *opaque)
2944
{
2945
    IOHandlerRecord **pioh, *ioh;
2946

    
2947
    if (!fd_read && !fd_write) {
2948
        pioh = &first_io_handler;
2949
        for(;;) {
2950
            ioh = *pioh;
2951
            if (ioh == NULL)
2952
                break;
2953
            if (ioh->fd == fd) {
2954
                ioh->deleted = 1;
2955
                break;
2956
            }
2957
            pioh = &ioh->next;
2958
        }
2959
    } else {
2960
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2961
            if (ioh->fd == fd)
2962
                goto found;
2963
        }
2964
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2965
        ioh->next = first_io_handler;
2966
        first_io_handler = ioh;
2967
    found:
2968
        ioh->fd = fd;
2969
        ioh->fd_read_poll = fd_read_poll;
2970
        ioh->fd_read = fd_read;
2971
        ioh->fd_write = fd_write;
2972
        ioh->opaque = opaque;
2973
        ioh->deleted = 0;
2974
    }
2975
    return 0;
2976
}
2977

    
2978
int qemu_set_fd_handler(int fd,
2979
                        IOHandler *fd_read,
2980
                        IOHandler *fd_write,
2981
                        void *opaque)
2982
{
2983
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2984
}
2985

    
2986
#ifdef _WIN32
2987
/***********************************************************/
2988
/* Polling handling */
2989

    
2990
typedef struct PollingEntry {
2991
    PollingFunc *func;
2992
    void *opaque;
2993
    struct PollingEntry *next;
2994
} PollingEntry;
2995

    
2996
static PollingEntry *first_polling_entry;
2997

    
2998
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2999
{
3000
    PollingEntry **ppe, *pe;
3001
    pe = qemu_mallocz(sizeof(PollingEntry));
3002
    pe->func = func;
3003
    pe->opaque = opaque;
3004
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3005
    *ppe = pe;
3006
    return 0;
3007
}
3008

    
3009
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3010
{
3011
    PollingEntry **ppe, *pe;
3012
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3013
        pe = *ppe;
3014
        if (pe->func == func && pe->opaque == opaque) {
3015
            *ppe = pe->next;
3016
            qemu_free(pe);
3017
            break;
3018
        }
3019
    }
3020
}
3021

    
3022
/***********************************************************/
3023
/* Wait objects support */
3024
typedef struct WaitObjects {
3025
    int num;
3026
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
3027
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
3028
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
3029
} WaitObjects;
3030

    
3031
static WaitObjects wait_objects = {0};
3032

    
3033
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3034
{
3035
    WaitObjects *w = &wait_objects;
3036

    
3037
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
3038
        return -1;
3039
    w->events[w->num] = handle;
3040
    w->func[w->num] = func;
3041
    w->opaque[w->num] = opaque;
3042
    w->num++;
3043
    return 0;
3044
}
3045

    
3046
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
3047
{
3048
    int i, found;
3049
    WaitObjects *w = &wait_objects;
3050

    
3051
    found = 0;
3052
    for (i = 0; i < w->num; i++) {
3053
        if (w->events[i] == handle)
3054
            found = 1;
3055
        if (found) {
3056
            w->events[i] = w->events[i + 1];
3057
            w->func[i] = w->func[i + 1];
3058
            w->opaque[i] = w->opaque[i + 1];
3059
        }
3060
    }
3061
    if (found)
3062
        w->num--;
3063
}
3064
#endif
3065

    
3066
/***********************************************************/
3067
/* ram save/restore */
3068

    
3069
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3070
{
3071
    int v;
3072

    
3073
    v = qemu_get_byte(f);
3074
    switch(v) {
3075
    case 0:
3076
        if (qemu_get_buffer(f, buf, len) != len)
3077
            return -EIO;
3078
        break;
3079
    case 1:
3080
        v = qemu_get_byte(f);
3081
        memset(buf, v, len);
3082
        break;
3083
    default:
3084
        return -EINVAL;
3085
    }
3086

    
3087
    if (qemu_file_has_error(f))
3088
        return -EIO;
3089

    
3090
    return 0;
3091
}
3092

    
3093
static int ram_load_v1(QEMUFile *f, void *opaque)
3094
{
3095
    int ret;
3096
    ram_addr_t i;
3097

    
3098
    if (qemu_get_be32(f) != last_ram_offset)
3099
        return -EINVAL;
3100
    for(i = 0; i < last_ram_offset; i+= TARGET_PAGE_SIZE) {
3101
        ret = ram_get_page(f, qemu_get_ram_ptr(i), TARGET_PAGE_SIZE);
3102
        if (ret)
3103
            return ret;
3104
    }
3105
    return 0;
3106
}
3107

    
3108
#define BDRV_HASH_BLOCK_SIZE 1024
3109
#define IOBUF_SIZE 4096
3110
#define RAM_CBLOCK_MAGIC 0xfabe
3111

    
3112
typedef struct RamDecompressState {
3113
    z_stream zstream;
3114
    QEMUFile *f;
3115
    uint8_t buf[IOBUF_SIZE];
3116
} RamDecompressState;
3117

    
3118
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3119
{
3120
    int ret;
3121
    memset(s, 0, sizeof(*s));
3122
    s->f = f;
3123
    ret = inflateInit(&s->zstream);
3124
    if (ret != Z_OK)
3125
        return -1;
3126
    return 0;
3127
}
3128

    
3129
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3130
{
3131
    int ret, clen;
3132

    
3133
    s->zstream.avail_out = len;
3134
    s->zstream.next_out = buf;
3135
    while (s->zstream.avail_out > 0) {
3136
        if (s->zstream.avail_in == 0) {
3137
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3138
                return -1;
3139
            clen = qemu_get_be16(s->f);
3140
            if (clen > IOBUF_SIZE)
3141
                return -1;
3142
            qemu_get_buffer(s->f, s->buf, clen);
3143
            s->zstream.avail_in = clen;
3144
            s->zstream.next_in = s->buf;
3145
        }
3146
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3147
        if (ret != Z_OK && ret != Z_STREAM_END) {
3148
            return -1;
3149
        }
3150
    }
3151
    return 0;
3152
}
3153

    
3154
static void ram_decompress_close(RamDecompressState *s)
3155
{
3156
    inflateEnd(&s->zstream);
3157
}
3158

    
3159
#define RAM_SAVE_FLAG_FULL        0x01
3160
#define RAM_SAVE_FLAG_COMPRESS        0x02
3161
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
3162
#define RAM_SAVE_FLAG_PAGE        0x08
3163
#define RAM_SAVE_FLAG_EOS        0x10
3164

    
3165
static int is_dup_page(uint8_t *page, uint8_t ch)
3166
{
3167
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3168
    uint32_t *array = (uint32_t *)page;
3169
    int i;
3170

    
3171
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3172
        if (array[i] != val)
3173
            return 0;
3174
    }
3175

    
3176
    return 1;
3177
}
3178

    
3179
static int ram_save_block(QEMUFile *f)
3180
{
3181
    static ram_addr_t current_addr = 0;
3182
    ram_addr_t saved_addr = current_addr;
3183
    ram_addr_t addr = 0;
3184
    int found = 0;
3185

    
3186
    while (addr < last_ram_offset) {
3187
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3188
            uint8_t *p;
3189

    
3190
            cpu_physical_memory_reset_dirty(current_addr,
3191
                                            current_addr + TARGET_PAGE_SIZE,
3192
                                            MIGRATION_DIRTY_FLAG);
3193

    
3194
            p = qemu_get_ram_ptr(current_addr);
3195

    
3196
            if (is_dup_page(p, *p)) {
3197
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3198
                qemu_put_byte(f, *p);
3199
            } else {
3200
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3201
                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);
3202
            }
3203

    
3204
            found = 1;
3205
            break;
3206
        }
3207
        addr += TARGET_PAGE_SIZE;
3208
        current_addr = (saved_addr + addr) % last_ram_offset;
3209
    }
3210

    
3211
    return found;
3212
}
3213

    
3214
static ram_addr_t ram_save_threshold = 10;
3215

    
3216
static ram_addr_t ram_save_remaining(void)
3217
{
3218
    ram_addr_t addr;
3219
    ram_addr_t count = 0;
3220

    
3221
    for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3222
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3223
            count++;
3224
    }
3225

    
3226
    return count;
3227
}
3228

    
3229
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3230
{
3231
    ram_addr_t addr;
3232

    
3233
    if (stage == 1) {
3234
        /* Make sure all dirty bits are set */
3235
        for (addr = 0; addr < last_ram_offset; addr += TARGET_PAGE_SIZE) {
3236
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3237
                cpu_physical_memory_set_dirty(addr);
3238
        }
3239
        
3240
        /* Enable dirty memory tracking */
3241
        cpu_physical_memory_set_dirty_tracking(1);
3242

    
3243
        qemu_put_be64(f, last_ram_offset | RAM_SAVE_FLAG_MEM_SIZE);
3244
    }
3245

    
3246
    while (!qemu_file_rate_limit(f)) {
3247
        int ret;
3248

    
3249
        ret = ram_save_block(f);
3250
        if (ret == 0) /* no more blocks */
3251
            break;
3252
    }
3253

    
3254
    /* try transferring iterative blocks of memory */
3255

    
3256
    if (stage == 3) {
3257

    
3258
        /* flush all remaining blocks regardless of rate limiting */
3259
        while (ram_save_block(f) != 0);
3260
        cpu_physical_memory_set_dirty_tracking(0);
3261
    }
3262

    
3263
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3264

    
3265
    return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3266
}
3267

    
3268
static int ram_load_dead(QEMUFile *f, void *opaque)
3269
{
3270
    RamDecompressState s1, *s = &s1;
3271
    uint8_t buf[10];
3272
    ram_addr_t i;
3273

    
3274
    if (ram_decompress_open(s, f) < 0)
3275
        return -EINVAL;
3276
    for(i = 0; i < last_ram_offset; i+= BDRV_HASH_BLOCK_SIZE) {
3277
        if (ram_decompress_buf(s, buf, 1) < 0) {
3278
            fprintf(stderr, "Error while reading ram block header\n");
3279
            goto error;
3280
        }
3281
        if (buf[0] == 0) {
3282
            if (ram_decompress_buf(s, qemu_get_ram_ptr(i),
3283
                                   BDRV_HASH_BLOCK_SIZE) < 0) {
3284
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3285
                goto error;
3286
            }
3287
        } else {
3288
        error:
3289
            printf("Error block header\n");
3290
            return -EINVAL;
3291
        }
3292
    }
3293
    ram_decompress_close(s);
3294

    
3295
    return 0;
3296
}
3297

    
3298
static int ram_load(QEMUFile *f, void *opaque, int version_id)
3299
{
3300
    ram_addr_t addr;
3301
    int flags;
3302

    
3303
    if (version_id == 1)
3304
        return ram_load_v1(f, opaque);
3305

    
3306
    if (version_id == 2) {
3307
        if (qemu_get_be32(f) != last_ram_offset)
3308
            return -EINVAL;
3309
        return ram_load_dead(f, opaque);
3310
    }
3311

    
3312
    if (version_id != 3)
3313
        return -EINVAL;
3314

    
3315
    do {
3316
        addr = qemu_get_be64(f);
3317

    
3318
        flags = addr & ~TARGET_PAGE_MASK;
3319
        addr &= TARGET_PAGE_MASK;
3320

    
3321
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
3322
            if (addr != last_ram_offset)
3323
                return -EINVAL;
3324
        }
3325

    
3326
        if (flags & RAM_SAVE_FLAG_FULL) {
3327
            if (ram_load_dead(f, opaque) < 0)
3328
                return -EINVAL;
3329
        }
3330
        
3331
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
3332
            uint8_t ch = qemu_get_byte(f);
3333
            memset(qemu_get_ram_ptr(addr), ch, TARGET_PAGE_SIZE);
3334
        } else if (flags & RAM_SAVE_FLAG_PAGE)
3335
            qemu_get_buffer(f, qemu_get_ram_ptr(addr), TARGET_PAGE_SIZE);
3336
    } while (!(flags & RAM_SAVE_FLAG_EOS));
3337

    
3338
    return 0;
3339
}
3340

    
3341
void qemu_service_io(void)
3342
{
3343
    CPUState *env = cpu_single_env;
3344
    if (env) {
3345
        cpu_exit(env);
3346
#ifdef CONFIG_KQEMU
3347
        if (env->kqemu_enabled) {
3348
            kqemu_cpu_interrupt(env);
3349
        }
3350
#endif
3351
    }
3352
}
3353

    
3354
/***********************************************************/
3355
/* bottom halves (can be seen as timers which expire ASAP) */
3356

    
3357
struct QEMUBH {
3358
    QEMUBHFunc *cb;
3359
    void *opaque;
3360
    int scheduled;
3361
    int idle;
3362
    int deleted;
3363
    QEMUBH *next;
3364
};
3365

    
3366
static QEMUBH *first_bh = NULL;
3367

    
3368
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
3369
{
3370
    QEMUBH *bh;
3371
    bh = qemu_mallocz(sizeof(QEMUBH));
3372
    bh->cb = cb;
3373
    bh->opaque = opaque;
3374
    bh->next = first_bh;
3375
    first_bh = bh;
3376
    return bh;
3377
}
3378

    
3379
int qemu_bh_poll(void)
3380
{
3381
    QEMUBH *bh, **bhp;
3382
    int ret;
3383

    
3384
    ret = 0;
3385
    for (bh = first_bh; bh; bh = bh->next) {
3386
        if (!bh->deleted && bh->scheduled) {
3387
            bh->scheduled = 0;
3388
            if (!bh->idle)
3389
                ret = 1;
3390
            bh->idle = 0;
3391
            bh->cb(bh->opaque);
3392
        }
3393
    }
3394

    
3395
    /* remove deleted bhs */
3396
    bhp = &first_bh;
3397
    while (*bhp) {
3398
        bh = *bhp;
3399
        if (bh->deleted) {
3400
            *bhp = bh->next;
3401
            qemu_free(bh);
3402
        } else
3403
            bhp = &bh->next;
3404
    }
3405

    
3406
    return ret;
3407
}
3408

    
3409
void qemu_bh_schedule_idle(QEMUBH *bh)
3410
{
3411
    if (bh->scheduled)
3412
        return;
3413
    bh->scheduled = 1;
3414
    bh->idle = 1;
3415
}
3416

    
3417
void qemu_bh_schedule(QEMUBH *bh)
3418
{
3419
    CPUState *env = cpu_single_env;
3420
    if (bh->scheduled)
3421
        return;
3422
    bh->scheduled = 1;
3423
    bh->idle = 0;
3424
    /* stop the currently executing CPU to execute the BH ASAP */
3425
    if (env) {
3426
        cpu_exit(env);
3427
    }
3428
}
3429

    
3430
void qemu_bh_cancel(QEMUBH *bh)
3431
{
3432
    bh->scheduled = 0;
3433
}
3434

    
3435
void qemu_bh_delete(QEMUBH *bh)
3436
{
3437
    bh->scheduled = 0;
3438
    bh->deleted = 1;
3439
}
3440

    
3441
static void qemu_bh_update_timeout(int *timeout)
3442
{
3443
    QEMUBH *bh;
3444

    
3445
    for (bh = first_bh; bh; bh = bh->next) {
3446
        if (!bh->deleted && bh->scheduled) {
3447
            if (bh->idle) {
3448
                /* idle bottom halves will be polled at least
3449
                 * every 10ms */
3450
                *timeout = MIN(10, *timeout);
3451
            } else {
3452
                /* non-idle bottom halves will be executed
3453
                 * immediately */
3454
                *timeout = 0;
3455
                break;
3456
            }
3457
        }
3458
    }
3459
}
3460

    
3461
/***********************************************************/
3462
/* machine registration */
3463

    
3464
static QEMUMachine *first_machine = NULL;
3465
QEMUMachine *current_machine = NULL;
3466

    
3467
int qemu_register_machine(QEMUMachine *m)
3468
{
3469
    QEMUMachine **pm;
3470
    pm = &first_machine;
3471
    while (*pm != NULL)
3472
        pm = &(*pm)->next;
3473
    m->next = NULL;
3474
    *pm = m;
3475
    return 0;
3476
}
3477

    
3478
static QEMUMachine *find_machine(const char *name)
3479
{
3480
    QEMUMachine *m;
3481

    
3482
    for(m = first_machine; m != NULL; m = m->next) {
3483
        if (!strcmp(m->name, name))
3484
            return m;
3485
    }
3486
    return NULL;
3487
}
3488

    
3489
/***********************************************************/
3490
/* main execution loop */
3491

    
3492
static void gui_update(void *opaque)
3493
{
3494
    uint64_t interval = GUI_REFRESH_INTERVAL;
3495
    DisplayState *ds = opaque;
3496
    DisplayChangeListener *dcl = ds->listeners;
3497

    
3498
    dpy_refresh(ds);
3499

    
3500
    while (dcl != NULL) {
3501
        if (dcl->gui_timer_interval &&
3502
            dcl->gui_timer_interval < interval)
3503
            interval = dcl->gui_timer_interval;
3504
        dcl = dcl->next;
3505
    }
3506
    qemu_mod_timer(ds->gui_timer, interval + qemu_get_clock(rt_clock));
3507
}
3508

    
3509
static void nographic_update(void *opaque)
3510
{
3511
    uint64_t interval = GUI_REFRESH_INTERVAL;
3512

    
3513
    qemu_mod_timer(nographic_timer, interval + qemu_get_clock(rt_clock));
3514
}
3515

    
3516
struct vm_change_state_entry {
3517
    VMChangeStateHandler *cb;
3518
    void *opaque;
3519
    LIST_ENTRY (vm_change_state_entry) entries;
3520
};
3521

    
3522
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
3523

    
3524
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
3525
                                                     void *opaque)
3526
{
3527
    VMChangeStateEntry *e;
3528

    
3529
    e = qemu_mallocz(sizeof (*e));
3530

    
3531
    e->cb = cb;
3532
    e->opaque = opaque;
3533
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
3534
    return e;
3535
}
3536

    
3537
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
3538
{
3539
    LIST_REMOVE (e, entries);
3540
    qemu_free (e);
3541
}
3542

    
3543
static void vm_state_notify(int running, int reason)
3544
{
3545
    VMChangeStateEntry *e;
3546

    
3547
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
3548
        e->cb(e->opaque, running, reason);
3549
    }
3550
}
3551

    
3552
void vm_start(void)
3553
{
3554
    if (!vm_running) {
3555
        cpu_enable_ticks();
3556
        vm_running = 1;
3557
        vm_state_notify(1, 0);
3558
        qemu_rearm_alarm_timer(alarm_timer);
3559
    }
3560
}
3561

    
3562
void vm_stop(int reason)
3563
{
3564
    if (vm_running) {
3565
        cpu_disable_ticks();
3566
        vm_running = 0;
3567
        vm_state_notify(0, reason);
3568
    }
3569
}
3570

    
3571
/* reset/shutdown handler */
3572

    
3573
typedef struct QEMUResetEntry {
3574
    QEMUResetHandler *func;
3575
    void *opaque;
3576
    struct QEMUResetEntry *next;
3577
} QEMUResetEntry;
3578

    
3579
static QEMUResetEntry *first_reset_entry;
3580
static int reset_requested;
3581
static int shutdown_requested;
3582
static int powerdown_requested;
3583

    
3584
int qemu_shutdown_requested(void)
3585
{
3586
    int r = shutdown_requested;
3587
    shutdown_requested = 0;
3588
    return r;
3589
}
3590

    
3591
int qemu_reset_requested(void)
3592
{
3593
    int r = reset_requested;
3594
    reset_requested = 0;
3595
    return r;
3596
}
3597

    
3598
int qemu_powerdown_requested(void)
3599
{
3600
    int r = powerdown_requested;
3601
    powerdown_requested = 0;
3602
    return r;
3603
}
3604

    
3605
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
3606
{
3607
    QEMUResetEntry **pre, *re;
3608

    
3609
    pre = &first_reset_entry;
3610
    while (*pre != NULL)
3611
        pre = &(*pre)->next;
3612
    re = qemu_mallocz(sizeof(QEMUResetEntry));
3613
    re->func = func;
3614
    re->opaque = opaque;
3615
    re->next = NULL;
3616
    *pre = re;
3617
}
3618

    
3619
void qemu_system_reset(void)
3620
{
3621
    QEMUResetEntry *re;
3622

    
3623
    /* reset all devices */
3624
    for(re = first_reset_entry; re != NULL; re = re->next) {
3625
        re->func(re->opaque);
3626
    }
3627
    if (kvm_enabled())
3628
        kvm_sync_vcpus();
3629
}
3630

    
3631
void qemu_system_reset_request(void)
3632
{
3633
    if (no_reboot) {
3634
        shutdown_requested = 1;
3635
    } else {
3636
        reset_requested = 1;
3637
    }
3638
    if (cpu_single_env)
3639
        cpu_exit(cpu_single_env);
3640
}
3641

    
3642
void qemu_system_shutdown_request(void)
3643
{
3644
    shutdown_requested = 1;
3645
    if (cpu_single_env)
3646
        cpu_exit(cpu_single_env);
3647
}
3648

    
3649
void qemu_system_powerdown_request(void)
3650
{
3651
    powerdown_requested = 1;
3652
    if (cpu_single_env)
3653
        cpu_exit(cpu_single_env);
3654
}
3655

    
3656
#ifdef _WIN32
3657
static void host_main_loop_wait(int *timeout)
3658
{
3659
    int ret, ret2, i;
3660
    PollingEntry *pe;
3661

    
3662

    
3663
    /* XXX: need to suppress polling by better using win32 events */
3664
    ret = 0;
3665
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
3666
        ret |= pe->func(pe->opaque);
3667
    }
3668
    if (ret == 0) {
3669
        int err;
3670
        WaitObjects *w = &wait_objects;
3671

    
3672
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
3673
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
3674
            if (w->func[ret - WAIT_OBJECT_0])
3675
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
3676

    
3677
            /* Check for additional signaled events */
3678
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
3679

    
3680
                /* Check if event is signaled */
3681
                ret2 = WaitForSingleObject(w->events[i], 0);
3682
                if(ret2 == WAIT_OBJECT_0) {
3683
                    if (w->func[i])
3684
                        w->func[i](w->opaque[i]);
3685
                } else if (ret2 == WAIT_TIMEOUT) {
3686
                } else {
3687
                    err = GetLastError();
3688
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
3689
                }
3690
            }
3691
        } else if (ret == WAIT_TIMEOUT) {
3692
        } else {
3693
            err = GetLastError();
3694
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
3695
        }
3696
    }
3697

    
3698
    *timeout = 0;
3699
}
3700
#else
3701
static void host_main_loop_wait(int *timeout)
3702
{
3703
}
3704
#endif
3705

    
3706
void main_loop_wait(int timeout)
3707
{
3708
    IOHandlerRecord *ioh;
3709
    fd_set rfds, wfds, xfds;
3710
    int ret, nfds;
3711
    struct timeval tv;
3712

    
3713
    qemu_bh_update_timeout(&timeout);
3714

    
3715
    host_main_loop_wait(&timeout);
3716

    
3717
    /* poll any events */
3718
    /* XXX: separate device handlers from system ones */
3719
    nfds = -1;
3720
    FD_ZERO(&rfds);
3721
    FD_ZERO(&wfds);
3722
    FD_ZERO(&xfds);
3723
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3724
        if (ioh->deleted)
3725
            continue;
3726
        if (ioh->fd_read &&
3727
            (!ioh->fd_read_poll ||
3728
             ioh->fd_read_poll(ioh->opaque) != 0)) {
3729
            FD_SET(ioh->fd, &rfds);
3730
            if (ioh->fd > nfds)
3731
                nfds = ioh->fd;
3732
        }
3733
        if (ioh->fd_write) {
3734
            FD_SET(ioh->fd, &wfds);
3735
            if (ioh->fd > nfds)
3736
                nfds = ioh->fd;
3737
        }
3738
    }
3739

    
3740
    tv.tv_sec = timeout / 1000;
3741
    tv.tv_usec = (timeout % 1000) * 1000;
3742

    
3743
#if defined(CONFIG_SLIRP)
3744
    if (slirp_is_inited()) {
3745
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
3746
    }
3747
#endif
3748
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
3749
    if (ret > 0) {
3750
        IOHandlerRecord **pioh;
3751

    
3752
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3753
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
3754
                ioh->fd_read(ioh->opaque);
3755
            }
3756
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
3757
                ioh->fd_write(ioh->opaque);
3758
            }
3759
        }
3760

    
3761
        /* remove deleted IO handlers */
3762
        pioh = &first_io_handler;
3763
        while (*pioh) {
3764
            ioh = *pioh;
3765
            if (ioh->deleted) {
3766
                *pioh = ioh->next;
3767
                qemu_free(ioh);
3768
            } else
3769
                pioh = &ioh->next;
3770
        }
3771
    }
3772
#if defined(CONFIG_SLIRP)
3773
    if (slirp_is_inited()) {
3774
        if (ret < 0) {
3775
            FD_ZERO(&rfds);
3776
            FD_ZERO(&wfds);
3777
            FD_ZERO(&xfds);
3778
        }
3779
        slirp_select_poll(&rfds, &wfds, &xfds);
3780
    }
3781
#endif
3782

    
3783
    /* vm time timers */
3784
    if (vm_running && likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
3785
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
3786
                        qemu_get_clock(vm_clock));
3787

    
3788
    /* real time timers */
3789
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
3790
                    qemu_get_clock(rt_clock));
3791

    
3792
    /* Check bottom-halves last in case any of the earlier events triggered
3793
       them.  */
3794
    qemu_bh_poll();
3795

    
3796
}
3797

    
3798
static int main_loop(void)
3799
{
3800
    int ret, timeout;
3801
#ifdef CONFIG_PROFILER
3802
    int64_t ti;
3803
#endif
3804
    CPUState *env;
3805

    
3806
    cur_cpu = first_cpu;
3807
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
3808
    for(;;) {
3809
        if (vm_running) {
3810

    
3811
            for(;;) {
3812
                /* get next cpu */
3813
                env = next_cpu;
3814
#ifdef CONFIG_PROFILER
3815
                ti = profile_getclock();
3816
#endif
3817
                if (use_icount) {
3818
                    int64_t count;
3819
                    int decr;
3820
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
3821
                    env->icount_decr.u16.low = 0;
3822
                    env->icount_extra = 0;
3823
                    count = qemu_next_deadline();
3824
                    count = (count + (1 << icount_time_shift) - 1)
3825
                            >> icount_time_shift;
3826
                    qemu_icount += count;
3827
                    decr = (count > 0xffff) ? 0xffff : count;
3828
                    count -= decr;
3829
                    env->icount_decr.u16.low = decr;
3830
                    env->icount_extra = count;
3831
                }
3832
                ret = cpu_exec(env);
3833
#ifdef CONFIG_PROFILER
3834
                qemu_time += profile_getclock() - ti;
3835
#endif
3836
                if (use_icount) {
3837
                    /* Fold pending instructions back into the
3838
                       instruction counter, and clear the interrupt flag.  */
3839
                    qemu_icount -= (env->icount_decr.u16.low
3840
                                    + env->icount_extra);
3841
                    env->icount_decr.u32 = 0;
3842
                    env->icount_extra = 0;
3843
                }
3844
                next_cpu = env->next_cpu ?: first_cpu;
3845
                if (event_pending && likely(ret != EXCP_DEBUG)) {
3846
                    ret = EXCP_INTERRUPT;
3847
                    event_pending = 0;
3848
                    break;
3849
                }
3850
                if (ret == EXCP_HLT) {
3851
                    /* Give the next CPU a chance to run.  */
3852
                    cur_cpu = env;
3853
                    continue;
3854
                }
3855
                if (ret != EXCP_HALTED)
3856
                    break;
3857
                /* all CPUs are halted ? */
3858
                if (env == cur_cpu)
3859
                    break;
3860
            }
3861
            cur_cpu = env;
3862

    
3863
            if (shutdown_requested) {
3864
                ret = EXCP_INTERRUPT;
3865
                if (no_shutdown) {
3866
                    vm_stop(0);
3867
                    no_shutdown = 0;
3868
                }
3869
                else
3870
                    break;
3871
            }
3872
            if (reset_requested) {
3873
                reset_requested = 0;
3874
                qemu_system_reset();
3875
                ret = EXCP_INTERRUPT;
3876
            }
3877
            if (powerdown_requested) {
3878
                powerdown_requested = 0;
3879
                qemu_system_powerdown();
3880
                ret = EXCP_INTERRUPT;
3881
            }
3882
            if (unlikely(ret == EXCP_DEBUG)) {
3883
                gdb_set_stop_cpu(cur_cpu);
3884
                vm_stop(EXCP_DEBUG);
3885
            }
3886
            /* If all cpus are halted then wait until the next IRQ */
3887
            /* XXX: use timeout computed from timers */
3888
            if (ret == EXCP_HALTED) {
3889
                if (use_icount) {
3890
                    int64_t add;
3891
                    int64_t delta;
3892
                    /* Advance virtual time to the next event.  */
3893
                    if (use_icount == 1) {
3894
                        /* When not using an adaptive execution frequency
3895
                           we tend to get badly out of sync with real time,
3896
                           so just delay for a reasonable amount of time.  */
3897
                        delta = 0;
3898
                    } else {
3899
                        delta = cpu_get_icount() - cpu_get_clock();
3900
                    }
3901
                    if (delta > 0) {
3902
                        /* If virtual time is ahead of real time then just
3903
                           wait for IO.  */
3904
                        timeout = (delta / 1000000) + 1;
3905
                    } else {
3906
                        /* Wait for either IO to occur or the next
3907
                           timer event.  */
3908
                        add = qemu_next_deadline();
3909
                        /* We advance the timer before checking for IO.
3910
                           Limit the amount we advance so that early IO
3911
                           activity won't get the guest too far ahead.  */
3912
                        if (add > 10000000)
3913
                            add = 10000000;
3914
                        delta += add;
3915
                        add = (add + (1 << icount_time_shift) - 1)
3916
                              >> icount_time_shift;
3917
                        qemu_icount += add;
3918
                        timeout = delta / 1000000;
3919
                        if (timeout < 0)
3920
                            timeout = 0;
3921
                    }
3922
                } else {
3923
                    timeout = 5000;
3924
                }
3925
            } else {
3926
                timeout = 0;
3927
            }
3928
        } else {
3929
            if (shutdown_requested) {
3930
                ret = EXCP_INTERRUPT;
3931
                break;
3932
            }
3933
            timeout = 5000;
3934
        }
3935
#ifdef CONFIG_PROFILER
3936
        ti = profile_getclock();
3937
#endif
3938
        main_loop_wait(timeout);
3939
#ifdef CONFIG_PROFILER
3940
        dev_time += profile_getclock() - ti;
3941
#endif
3942
    }
3943
    cpu_disable_ticks();
3944
    return ret;
3945
}
3946

    
3947
static void version(void)
3948
{
3949
    printf("QEMU PC emulator version " QEMU_VERSION QEMU_PKGVERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n");
3950
}
3951

    
3952
static void help(int exitcode)
3953
{
3954
    version();
3955
    printf("usage: %s [options] [disk_image]\n"
3956
           "\n"
3957
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3958
           "\n"
3959
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3960
           opt_help
3961
#define DEFHEADING(text) stringify(text) "\n"
3962
#include "qemu-options.h"
3963
#undef DEF
3964
#undef DEFHEADING
3965
#undef GEN_DOCS
3966
           "\n"
3967
           "During emulation, the following keys are useful:\n"
3968
           "ctrl-alt-f      toggle full screen\n"
3969
           "ctrl-alt-n      switch to virtual console 'n'\n"
3970
           "ctrl-alt        toggle mouse and keyboard grab\n"
3971
           "\n"
3972
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
3973
           ,
3974
           "qemu",
3975
           DEFAULT_RAM_SIZE,
3976
#ifndef _WIN32
3977
           DEFAULT_NETWORK_SCRIPT,
3978
           DEFAULT_NETWORK_DOWN_SCRIPT,
3979
#endif
3980
           DEFAULT_GDBSTUB_PORT,
3981
           "/tmp/qemu.log");
3982
    exit(exitcode);
3983
}
3984

    
3985
#define HAS_ARG 0x0001
3986

    
3987
enum {
3988
#define DEF(option, opt_arg, opt_enum, opt_help)        \
3989
    opt_enum,
3990
#define DEFHEADING(text)
3991
#include "qemu-options.h"
3992
#undef DEF
3993
#undef DEFHEADING
3994
#undef GEN_DOCS
3995
};
3996

    
3997
typedef struct QEMUOption {
3998
    const char *name;
3999
    int flags;
4000
    int index;
4001
} QEMUOption;
4002

    
4003
static const QEMUOption qemu_options[] = {
4004
    { "h", 0, QEMU_OPTION_h },
4005
#define DEF(option, opt_arg, opt_enum, opt_help)        \
4006
    { option, opt_arg, opt_enum },
4007
#define DEFHEADING(text)
4008
#include "qemu-options.h"
4009
#undef DEF
4010
#undef DEFHEADING
4011
#undef GEN_DOCS
4012
    { NULL },
4013
};
4014

    
4015
#ifdef HAS_AUDIO
4016
struct soundhw soundhw[] = {
4017
#ifdef HAS_AUDIO_CHOICE
4018
#if defined(TARGET_I386) || defined(TARGET_MIPS)
4019
    {
4020
        "pcspk",
4021
        "PC speaker",
4022
        0,
4023
        1,
4024
        { .init_isa = pcspk_audio_init }
4025
    },
4026
#endif
4027

    
4028
#ifdef CONFIG_SB16
4029
    {
4030
        "sb16",
4031
        "Creative Sound Blaster 16",
4032
        0,
4033
        1,
4034
        { .init_isa = SB16_init }
4035
    },
4036
#endif
4037

    
4038
#ifdef CONFIG_CS4231A
4039
    {
4040
        "cs4231a",
4041
        "CS4231A",
4042
        0,
4043
        1,
4044
        { .init_isa = cs4231a_init }
4045
    },
4046
#endif
4047

    
4048
#ifdef CONFIG_ADLIB
4049
    {
4050
        "adlib",
4051
#ifdef HAS_YMF262
4052
        "Yamaha YMF262 (OPL3)",
4053
#else
4054
        "Yamaha YM3812 (OPL2)",
4055
#endif
4056
        0,
4057
        1,
4058
        { .init_isa = Adlib_init }
4059
    },
4060
#endif
4061

    
4062
#ifdef CONFIG_GUS
4063
    {
4064
        "gus",
4065
        "Gravis Ultrasound GF1",
4066
        0,
4067
        1,
4068
        { .init_isa = GUS_init }
4069
    },
4070
#endif
4071

    
4072
#ifdef CONFIG_AC97
4073
    {
4074
        "ac97",
4075
        "Intel 82801AA AC97 Audio",
4076
        0,
4077
        0,
4078
        { .init_pci = ac97_init }
4079
    },
4080
#endif
4081

    
4082
#ifdef CONFIG_ES1370
4083
    {
4084
        "es1370",
4085
        "ENSONIQ AudioPCI ES1370",
4086
        0,
4087
        0,
4088
        { .init_pci = es1370_init }
4089
    },
4090
#endif
4091

    
4092
#endif /* HAS_AUDIO_CHOICE */
4093

    
4094
    { NULL, NULL, 0, 0, { NULL } }
4095
};
4096

    
4097
static void select_soundhw (const char *optarg)
4098
{
4099
    struct soundhw *c;
4100

    
4101
    if (*optarg == '?') {
4102
    show_valid_cards:
4103

    
4104
        printf ("Valid sound card names (comma separated):\n");
4105
        for (c = soundhw; c->name; ++c) {
4106
            printf ("%-11s %s\n", c->name, c->descr);
4107
        }
4108
        printf ("\n-soundhw all will enable all of the above\n");
4109
        exit (*optarg != '?');
4110
    }
4111
    else {
4112
        size_t l;
4113
        const char *p;
4114
        char *e;
4115
        int bad_card = 0;
4116

    
4117
        if (!strcmp (optarg, "all")) {
4118
            for (c = soundhw; c->name; ++c) {
4119
                c->enabled = 1;
4120
            }
4121
            return;
4122
        }
4123

    
4124
        p = optarg;
4125
        while (*p) {
4126
            e = strchr (p, ',');
4127
            l = !e ? strlen (p) : (size_t) (e - p);
4128

    
4129
            for (c = soundhw; c->name; ++c) {
4130
                if (!strncmp (c->name, p, l)) {
4131
                    c->enabled = 1;
4132
                    break;
4133
                }
4134
            }
4135

    
4136
            if (!c->name) {
4137
                if (l > 80) {
4138
                    fprintf (stderr,
4139
                             "Unknown sound card name (too big to show)\n");
4140
                }
4141
                else {
4142
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
4143
                             (int) l, p);
4144
                }
4145
                bad_card = 1;
4146
            }
4147
            p += l + (e != NULL);
4148
        }
4149

    
4150
        if (bad_card)
4151
            goto show_valid_cards;
4152
    }
4153
}
4154
#endif
4155

    
4156
static void select_vgahw (const char *p)
4157
{
4158
    const char *opts;
4159

    
4160
    if (strstart(p, "std", &opts)) {
4161
        std_vga_enabled = 1;
4162
        cirrus_vga_enabled = 0;
4163
        vmsvga_enabled = 0;
4164
    } else if (strstart(p, "cirrus", &opts)) {
4165
        cirrus_vga_enabled = 1;
4166
        std_vga_enabled = 0;
4167
        vmsvga_enabled = 0;
4168
    } else if (strstart(p, "vmware", &opts)) {
4169
        cirrus_vga_enabled = 0;
4170
        std_vga_enabled = 0;
4171
        vmsvga_enabled = 1;
4172
    } else if (strstart(p, "none", &opts)) {
4173
        cirrus_vga_enabled = 0;
4174
        std_vga_enabled = 0;
4175
        vmsvga_enabled = 0;
4176
    } else {
4177
    invalid_vga:
4178
        fprintf(stderr, "Unknown vga type: %s\n", p);
4179
        exit(1);
4180
    }
4181
    while (*opts) {
4182
        const char *nextopt;
4183

    
4184
        if (strstart(opts, ",retrace=", &nextopt)) {
4185
            opts = nextopt;
4186
            if (strstart(opts, "dumb", &nextopt))
4187
                vga_retrace_method = VGA_RETRACE_DUMB;
4188
            else if (strstart(opts, "precise", &nextopt))
4189
                vga_retrace_method = VGA_RETRACE_PRECISE;
4190
            else goto invalid_vga;
4191
        } else goto invalid_vga;
4192
        opts = nextopt;
4193
    }
4194
}
4195

    
4196
#ifdef _WIN32
4197
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
4198
{
4199
    exit(STATUS_CONTROL_C_EXIT);
4200
    return TRUE;
4201
}
4202
#endif
4203

    
4204
int qemu_uuid_parse(const char *str, uint8_t *uuid)
4205
{
4206
    int ret;
4207

    
4208
    if(strlen(str) != 36)
4209
        return -1;
4210

    
4211
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
4212
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
4213
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
4214

    
4215
    if(ret != 16)
4216
        return -1;
4217

    
4218
#ifdef TARGET_I386
4219
    smbios_add_field(1, offsetof(struct smbios_type_1, uuid), 16, uuid);
4220
#endif
4221

    
4222
    return 0;
4223
}
4224

    
4225
#define MAX_NET_CLIENTS 32
4226

    
4227
#ifndef _WIN32
4228

    
4229
static void termsig_handler(int signal)
4230
{
4231
    qemu_system_shutdown_request();
4232
}
4233

    
4234
static void termsig_setup(void)
4235
{
4236
    struct sigaction act;
4237

    
4238
    memset(&act, 0, sizeof(act));
4239
    act.sa_handler = termsig_handler;
4240
    sigaction(SIGINT,  &act, NULL);
4241
    sigaction(SIGHUP,  &act, NULL);
4242
    sigaction(SIGTERM, &act, NULL);
4243
}
4244

    
4245
#endif
4246

    
4247
int main(int argc, char **argv, char **envp)
4248
{
4249
#ifdef CONFIG_GDBSTUB
4250
    const char *gdbstub_dev = NULL;
4251
#endif
4252
    uint32_t boot_devices_bitmap = 0;
4253
    int i;
4254
    int snapshot, linux_boot, net_boot;
4255
    const char *initrd_filename;
4256
    const char *kernel_filename, *kernel_cmdline;
4257
    const char *boot_devices = "";
4258
    DisplayState *ds;
4259
    DisplayChangeListener *dcl;
4260
    int cyls, heads, secs, translation;
4261
    const char *net_clients[MAX_NET_CLIENTS];
4262
    int nb_net_clients;
4263
    const char *bt_opts[MAX_BT_CMDLINE];
4264
    int nb_bt_opts;
4265
    int hda_index;
4266
    int optind;
4267
    const char *r, *optarg;
4268
    CharDriverState *monitor_hd = NULL;
4269
    const char *monitor_device;
4270
    const char *serial_devices[MAX_SERIAL_PORTS];
4271
    int serial_device_index;
4272
    const char *parallel_devices[MAX_PARALLEL_PORTS];
4273
    int parallel_device_index;
4274
    const char *virtio_consoles[MAX_VIRTIO_CONSOLES];
4275
    int virtio_console_index;
4276
    const char *loadvm = NULL;
4277
    QEMUMachine *machine;
4278
    const char *cpu_model;
4279
    const char *usb_devices[MAX_USB_CMDLINE];
4280
    int usb_devices_index;
4281
#ifndef _WIN32
4282
    int fds[2];
4283
#endif
4284
    int tb_size;
4285
    const char *pid_file = NULL;
4286
    const char *incoming = NULL;
4287
#ifndef _WIN32
4288
    int fd = 0;
4289
    struct passwd *pwd = NULL;
4290
    const char *chroot_dir = NULL;
4291
    const char *run_as = NULL;
4292
#endif
4293

    
4294
    qemu_cache_utils_init(envp);
4295

    
4296
    LIST_INIT (&vm_change_state_head);
4297
#ifndef _WIN32
4298
    {
4299
        struct sigaction act;
4300
        sigfillset(&act.sa_mask);
4301
        act.sa_flags = 0;
4302
        act.sa_handler = SIG_IGN;
4303
        sigaction(SIGPIPE, &act, NULL);
4304
    }
4305
#else
4306
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
4307
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
4308
       QEMU to run on a single CPU */
4309
    {
4310
        HANDLE h;
4311
        DWORD mask, smask;
4312
        int i;
4313
        h = GetCurrentProcess();
4314
        if (GetProcessAffinityMask(h, &mask, &smask)) {
4315
            for(i = 0; i < 32; i++) {
4316
                if (mask & (1 << i))
4317
                    break;
4318
            }
4319
            if (i != 32) {
4320
                mask = 1 << i;
4321
                SetProcessAffinityMask(h, mask);
4322
            }
4323
        }
4324
    }
4325
#endif
4326

    
4327
    register_machines();
4328
    machine = first_machine;
4329
    cpu_model = NULL;
4330
    initrd_filename = NULL;
4331
    ram_size = 0;
4332
    vga_ram_size = VGA_RAM_SIZE;
4333
    snapshot = 0;
4334
    nographic = 0;
4335
    curses = 0;
4336
    kernel_filename = NULL;
4337
    kernel_cmdline = "";
4338
    cyls = heads = secs = 0;
4339
    translation = BIOS_ATA_TRANSLATION_AUTO;
4340
    monitor_device = "vc:80Cx24C";
4341

    
4342
    serial_devices[0] = "vc:80Cx24C";
4343
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
4344
        serial_devices[i] = NULL;
4345
    serial_device_index = 0;
4346

    
4347
    parallel_devices[0] = "vc:80Cx24C";
4348
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
4349
        parallel_devices[i] = NULL;
4350
    parallel_device_index = 0;
4351

    
4352
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++)
4353
        virtio_consoles[i] = NULL;
4354
    virtio_console_index = 0;
4355

    
4356
    usb_devices_index = 0;
4357

    
4358
    nb_net_clients = 0;
4359
    nb_bt_opts = 0;
4360
    nb_drives = 0;
4361
    nb_drives_opt = 0;
4362
    hda_index = -1;
4363

    
4364
    nb_nics = 0;
4365

    
4366
    tb_size = 0;
4367
    autostart= 1;
4368

    
4369
    optind = 1;
4370
    for(;;) {
4371
        if (optind >= argc)
4372
            break;
4373
        r = argv[optind];
4374
        if (r[0] != '-') {
4375
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
4376
        } else {
4377
            const QEMUOption *popt;
4378

    
4379
            optind++;
4380
            /* Treat --foo the same as -foo.  */
4381
            if (r[1] == '-')
4382
                r++;
4383
            popt = qemu_options;
4384
            for(;;) {
4385
                if (!popt->name) {
4386
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
4387
                            argv[0], r);
4388
                    exit(1);
4389
                }
4390
                if (!strcmp(popt->name, r + 1))
4391
                    break;
4392
                popt++;
4393
            }
4394
            if (popt->flags & HAS_ARG) {
4395
                if (optind >= argc) {
4396
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
4397
                            argv[0], r);
4398
                    exit(1);
4399
                }
4400
                optarg = argv[optind++];
4401
            } else {
4402
                optarg = NULL;
4403
            }
4404

    
4405
            switch(popt->index) {
4406
            case QEMU_OPTION_M:
4407
                machine = find_machine(optarg);
4408
                if (!machine) {
4409
                    QEMUMachine *m;
4410
                    printf("Supported machines are:\n");
4411
                    for(m = first_machine; m != NULL; m = m->next) {
4412
                        printf("%-10s %s%s\n",
4413
                               m->name, m->desc,
4414
                               m == first_machine ? " (default)" : "");
4415
                    }
4416
                    exit(*optarg != '?');
4417
                }
4418
                break;
4419
            case QEMU_OPTION_cpu:
4420
                /* hw initialization will check this */
4421
                if (*optarg == '?') {
4422
/* XXX: implement xxx_cpu_list for targets that still miss it */
4423
#if defined(cpu_list)
4424
                    cpu_list(stdout, &fprintf);
4425
#endif
4426
                    exit(0);
4427
                } else {
4428
                    cpu_model = optarg;
4429
                }
4430
                break;
4431
            case QEMU_OPTION_initrd:
4432
                initrd_filename = optarg;
4433
                break;
4434
            case QEMU_OPTION_hda:
4435
                if (cyls == 0)
4436
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
4437
                else
4438
                    hda_index = drive_add(optarg, HD_ALIAS
4439
                             ",cyls=%d,heads=%d,secs=%d%s",
4440
                             0, cyls, heads, secs,
4441
                             translation == BIOS_ATA_TRANSLATION_LBA ?
4442
                                 ",trans=lba" :
4443
                             translation == BIOS_ATA_TRANSLATION_NONE ?
4444
                                 ",trans=none" : "");
4445
                 break;
4446
            case QEMU_OPTION_hdb:
4447
            case QEMU_OPTION_hdc:
4448
            case QEMU_OPTION_hdd:
4449
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
4450
                break;
4451
            case QEMU_OPTION_drive:
4452
                drive_add(NULL, "%s", optarg);
4453
                break;
4454
            case QEMU_OPTION_mtdblock:
4455
                drive_add(optarg, MTD_ALIAS);
4456
                break;
4457
            case QEMU_OPTION_sd:
4458
                drive_add(optarg, SD_ALIAS);
4459
                break;
4460
            case QEMU_OPTION_pflash:
4461
                drive_add(optarg, PFLASH_ALIAS);
4462
                break;
4463
            case QEMU_OPTION_snapshot:
4464
                snapshot = 1;
4465
                break;
4466
            case QEMU_OPTION_hdachs:
4467
                {
4468
                    const char *p;
4469
                    p = optarg;
4470
                    cyls = strtol(p, (char **)&p, 0);
4471
                    if (cyls < 1 || cyls > 16383)
4472
                        goto chs_fail;
4473
                    if (*p != ',')
4474
                        goto chs_fail;
4475
                    p++;
4476
                    heads = strtol(p, (char **)&p, 0);
4477
                    if (heads < 1 || heads > 16)
4478
                        goto chs_fail;
4479
                    if (*p != ',')
4480
                        goto chs_fail;
4481
                    p++;
4482
                    secs = strtol(p, (char **)&p, 0);
4483
                    if (secs < 1 || secs > 63)
4484
                        goto chs_fail;
4485
                    if (*p == ',') {
4486
                        p++;
4487
                        if (!strcmp(p, "none"))
4488
                            translation = BIOS_ATA_TRANSLATION_NONE;
4489
                        else if (!strcmp(p, "lba"))
4490
                            translation = BIOS_ATA_TRANSLATION_LBA;
4491
                        else if (!strcmp(p, "auto"))
4492
                            translation = BIOS_ATA_TRANSLATION_AUTO;
4493
                        else
4494
                            goto chs_fail;
4495
                    } else if (*p != '\0') {
4496
                    chs_fail:
4497
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
4498
                        exit(1);
4499
                    }
4500
                    if (hda_index != -1)
4501
                        snprintf(drives_opt[hda_index].opt,
4502
                                 sizeof(drives_opt[hda_index].opt),
4503
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
4504
                                 0, cyls, heads, secs,
4505
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
4506
                                         ",trans=lba" :
4507
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
4508
                                     ",trans=none" : "");
4509
                }
4510
                break;
4511
            case QEMU_OPTION_nographic:
4512
                nographic = 1;
4513
                break;
4514
#ifdef CONFIG_CURSES
4515
            case QEMU_OPTION_curses:
4516
                curses = 1;
4517
                break;
4518
#endif
4519
            case QEMU_OPTION_portrait:
4520
                graphic_rotate = 1;
4521
                break;
4522
            case QEMU_OPTION_kernel:
4523
                kernel_filename = optarg;
4524
                break;
4525
            case QEMU_OPTION_append:
4526
                kernel_cmdline = optarg;
4527
                break;
4528
            case QEMU_OPTION_cdrom:
4529
                drive_add(optarg, CDROM_ALIAS);
4530
                break;
4531
            case QEMU_OPTION_boot:
4532
                boot_devices = optarg;
4533
                /* We just do some generic consistency checks */
4534
                {
4535
                    /* Could easily be extended to 64 devices if needed */
4536
                    const char *p;
4537
                    
4538
                    boot_devices_bitmap = 0;
4539
                    for (p = boot_devices; *p != '\0'; p++) {
4540
                        /* Allowed boot devices are:
4541
                         * a b     : floppy disk drives
4542
                         * c ... f : IDE disk drives
4543
                         * g ... m : machine implementation dependant drives
4544
                         * n ... p : network devices
4545
                         * It's up to each machine implementation to check
4546
                         * if the given boot devices match the actual hardware
4547
                         * implementation and firmware features.
4548
                         */
4549
                        if (*p < 'a' || *p > 'q') {
4550
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
4551
                            exit(1);
4552
                        }
4553
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
4554
                            fprintf(stderr,
4555
                                    "Boot device '%c' was given twice\n",*p);
4556
                            exit(1);
4557
                        }
4558
                        boot_devices_bitmap |= 1 << (*p - 'a');
4559
                    }
4560
                }
4561
                break;
4562
            case QEMU_OPTION_fda:
4563
            case QEMU_OPTION_fdb:
4564
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
4565
                break;
4566
#ifdef TARGET_I386
4567
            case QEMU_OPTION_no_fd_bootchk:
4568
                fd_bootchk = 0;
4569
                break;
4570
#endif
4571
            case QEMU_OPTION_net:
4572
                if (nb_net_clients >= MAX_NET_CLIENTS) {
4573
                    fprintf(stderr, "qemu: too many network clients\n");
4574
                    exit(1);
4575
                }
4576
                net_clients[nb_net_clients] = optarg;
4577
                nb_net_clients++;
4578
                break;
4579
#ifdef CONFIG_SLIRP
4580
            case QEMU_OPTION_tftp:
4581
                tftp_prefix = optarg;
4582
                break;
4583
            case QEMU_OPTION_bootp:
4584
                bootp_filename = optarg;
4585
                break;
4586
#ifndef _WIN32
4587
            case QEMU_OPTION_smb:
4588
                net_slirp_smb(optarg);
4589
                break;
4590
#endif
4591
            case QEMU_OPTION_redir:
4592
                net_slirp_redir(optarg);
4593
                break;
4594
#endif
4595
            case QEMU_OPTION_bt:
4596
                if (nb_bt_opts >= MAX_BT_CMDLINE) {
4597
                    fprintf(stderr, "qemu: too many bluetooth options\n");
4598
                    exit(1);
4599
                }
4600
                bt_opts[nb_bt_opts++] = optarg;
4601
                break;
4602
#ifdef HAS_AUDIO
4603
            case QEMU_OPTION_audio_help:
4604
                AUD_help ();
4605
                exit (0);
4606
                break;
4607
            case QEMU_OPTION_soundhw:
4608
                select_soundhw (optarg);
4609
                break;
4610
#endif
4611
            case QEMU_OPTION_h:
4612
                help(0);
4613
                break;
4614
            case QEMU_OPTION_version:
4615
                version();
4616
                exit(0);
4617
                break;
4618
            case QEMU_OPTION_m: {
4619
                uint64_t value;
4620
                char *ptr;
4621

    
4622
                value = strtoul(optarg, &ptr, 10);
4623
                switch (*ptr) {
4624
                case 0: case 'M': case 'm':
4625
                    value <<= 20;
4626
                    break;
4627
                case 'G': case 'g':
4628
                    value <<= 30;
4629
                    break;
4630
                default:
4631
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
4632
                    exit(1);
4633
                }
4634

    
4635
                /* On 32-bit hosts, QEMU is limited by virtual address space */
4636
                if (value > (2047 << 20)
4637
#ifndef CONFIG_KQEMU
4638
                    && HOST_LONG_BITS == 32
4639
#endif
4640
                    ) {
4641
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
4642
                    exit(1);
4643
                }
4644
                if (value != (uint64_t)(ram_addr_t)value) {
4645
                    fprintf(stderr, "qemu: ram size too large\n");
4646
                    exit(1);
4647
                }
4648
                ram_size = value;
4649
                break;
4650
            }
4651
            case QEMU_OPTION_d:
4652
                {
4653
                    int mask;
4654
                    const CPULogItem *item;
4655

    
4656
                    mask = cpu_str_to_log_mask(optarg);
4657
                    if (!mask) {
4658
                        printf("Log items (comma separated):\n");
4659
                    for(item = cpu_log_items; item->mask != 0; item++) {
4660
                        printf("%-10s %s\n", item->name, item->help);
4661
                    }
4662
                    exit(1);
4663
                    }
4664
                    cpu_set_log(mask);
4665
                }
4666
                break;
4667
#ifdef CONFIG_GDBSTUB
4668
            case QEMU_OPTION_s:
4669
                gdbstub_dev = "tcp::" DEFAULT_GDBSTUB_PORT;
4670
                break;
4671
            case QEMU_OPTION_gdb:
4672
                gdbstub_dev = optarg;
4673
                break;
4674
#endif
4675
            case QEMU_OPTION_L:
4676
                bios_dir = optarg;
4677
                break;
4678
            case QEMU_OPTION_bios:
4679
                bios_name = optarg;
4680
                break;
4681
            case QEMU_OPTION_singlestep:
4682
                singlestep = 1;
4683
                break;
4684
            case QEMU_OPTION_S:
4685
                autostart = 0;
4686
                break;
4687
#ifndef _WIN32
4688
            case QEMU_OPTION_k:
4689
                keyboard_layout = optarg;
4690
                break;
4691
#endif
4692
            case QEMU_OPTION_localtime:
4693
                rtc_utc = 0;
4694
                break;
4695
            case QEMU_OPTION_vga:
4696
                select_vgahw (optarg);
4697
                break;
4698
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4699
            case QEMU_OPTION_g:
4700
                {
4701
                    const char *p;
4702
                    int w, h, depth;
4703
                    p = optarg;
4704
                    w = strtol(p, (char **)&p, 10);
4705
                    if (w <= 0) {
4706
                    graphic_error:
4707
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
4708
                        exit(1);
4709
                    }
4710
                    if (*p != 'x')
4711
                        goto graphic_error;
4712
                    p++;
4713
                    h = strtol(p, (char **)&p, 10);
4714
                    if (h <= 0)
4715
                        goto graphic_error;
4716
                    if (*p == 'x') {
4717
                        p++;
4718
                        depth = strtol(p, (char **)&p, 10);
4719
                        if (depth != 8 && depth != 15 && depth != 16 &&
4720
                            depth != 24 && depth != 32)
4721
                            goto graphic_error;
4722
                    } else if (*p == '\0') {
4723
                        depth = graphic_depth;
4724
                    } else {
4725
                        goto graphic_error;
4726
                    }
4727

    
4728
                    graphic_width = w;
4729
                    graphic_height = h;
4730
                    graphic_depth = depth;
4731
                }
4732
                break;
4733
#endif
4734
            case QEMU_OPTION_echr:
4735
                {
4736
                    char *r;
4737
                    term_escape_char = strtol(optarg, &r, 0);
4738
                    if (r == optarg)
4739
                        printf("Bad argument to echr\n");
4740
                    break;
4741
                }
4742
            case QEMU_OPTION_monitor:
4743
                monitor_device = optarg;
4744
                break;
4745
            case QEMU_OPTION_serial:
4746
                if (serial_device_index >= MAX_SERIAL_PORTS) {
4747
                    fprintf(stderr, "qemu: too many serial ports\n");
4748
                    exit(1);
4749
                }
4750
                serial_devices[serial_device_index] = optarg;
4751
                serial_device_index++;
4752
                break;
4753
            case QEMU_OPTION_virtiocon:
4754
                if (virtio_console_index >= MAX_VIRTIO_CONSOLES) {
4755
                    fprintf(stderr, "qemu: too many virtio consoles\n");
4756
                    exit(1);
4757
                }
4758
                virtio_consoles[virtio_console_index] = optarg;
4759
                virtio_console_index++;
4760
                break;
4761
            case QEMU_OPTION_parallel:
4762
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
4763
                    fprintf(stderr, "qemu: too many parallel ports\n");
4764
                    exit(1);
4765
                }
4766
                parallel_devices[parallel_device_index] = optarg;
4767
                parallel_device_index++;
4768
                break;
4769
            case QEMU_OPTION_loadvm:
4770
                loadvm = optarg;
4771
                break;
4772
            case QEMU_OPTION_full_screen:
4773
                full_screen = 1;
4774
                break;
4775
#ifdef CONFIG_SDL
4776
            case QEMU_OPTION_no_frame:
4777
                no_frame = 1;
4778
                break;
4779
            case QEMU_OPTION_alt_grab:
4780
                alt_grab = 1;
4781
                break;
4782
            case QEMU_OPTION_no_quit:
4783
                no_quit = 1;
4784
                break;
4785
            case QEMU_OPTION_sdl:
4786
                sdl = 1;
4787
                break;
4788
#endif
4789
            case QEMU_OPTION_pidfile:
4790
                pid_file = optarg;
4791
                break;
4792
#ifdef TARGET_I386
4793
            case QEMU_OPTION_win2k_hack:
4794
                win2k_install_hack = 1;
4795
                break;
4796
            case QEMU_OPTION_rtc_td_hack:
4797
                rtc_td_hack = 1;
4798
                break;
4799
            case QEMU_OPTION_acpitable:
4800
                if(acpi_table_add(optarg) < 0) {
4801
                    fprintf(stderr, "Wrong acpi table provided\n");
4802
                    exit(1);
4803
                }
4804
                break;
4805
            case QEMU_OPTION_smbios:
4806
                if(smbios_entry_add(optarg) < 0) {
4807
                    fprintf(stderr, "Wrong smbios provided\n");
4808
                    exit(1);
4809
                }
4810
                break;
4811
#endif
4812
#ifdef CONFIG_KQEMU
4813
            case QEMU_OPTION_no_kqemu:
4814
                kqemu_allowed = 0;
4815
                break;
4816
            case QEMU_OPTION_kernel_kqemu:
4817
                kqemu_allowed = 2;
4818
                break;
4819
#endif
4820
#ifdef CONFIG_KVM
4821
            case QEMU_OPTION_enable_kvm:
4822
                kvm_allowed = 1;
4823
#ifdef CONFIG_KQEMU
4824
                kqemu_allowed = 0;
4825
#endif
4826
                break;
4827
#endif
4828
            case QEMU_OPTION_usb:
4829
                usb_enabled = 1;
4830
                break;
4831
            case QEMU_OPTION_usbdevice:
4832
                usb_enabled = 1;
4833
                if (usb_devices_index >= MAX_USB_CMDLINE) {
4834
                    fprintf(stderr, "Too many USB devices\n");
4835
                    exit(1);
4836
                }
4837
                usb_devices[usb_devices_index] = optarg;
4838
                usb_devices_index++;
4839
                break;
4840
            case QEMU_OPTION_smp:
4841
                smp_cpus = atoi(optarg);
4842
                if (smp_cpus < 1) {
4843
                    fprintf(stderr, "Invalid number of CPUs\n");
4844
                    exit(1);
4845
                }
4846
                break;
4847
            case QEMU_OPTION_vnc:
4848
                vnc_display = optarg;
4849
                break;
4850
#ifdef TARGET_I386
4851
            case QEMU_OPTION_no_acpi:
4852
                acpi_enabled = 0;
4853
                break;
4854
            case QEMU_OPTION_no_hpet:
4855
                no_hpet = 1;
4856
                break;
4857
#endif
4858
            case QEMU_OPTION_no_reboot:
4859
                no_reboot = 1;
4860
                break;
4861
            case QEMU_OPTION_no_shutdown:
4862
                no_shutdown = 1;
4863
                break;
4864
            case QEMU_OPTION_show_cursor:
4865
                cursor_hide = 0;
4866
                break;
4867
            case QEMU_OPTION_uuid:
4868
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
4869
                    fprintf(stderr, "Fail to parse UUID string."
4870
                            " Wrong format.\n");
4871
                    exit(1);
4872
                }
4873
                break;
4874
#ifndef _WIN32
4875
            case QEMU_OPTION_daemonize:
4876
                daemonize = 1;
4877
                break;
4878
#endif
4879
            case QEMU_OPTION_option_rom:
4880
                if (nb_option_roms >= MAX_OPTION_ROMS) {
4881
                    fprintf(stderr, "Too many option ROMs\n");
4882
                    exit(1);
4883
                }
4884
                option_rom[nb_option_roms] = optarg;
4885
                nb_option_roms++;
4886
                break;
4887
#if defined(TARGET_ARM) || defined(TARGET_M68K)
4888
            case QEMU_OPTION_semihosting:
4889
                semihosting_enabled = 1;
4890
                break;
4891
#endif
4892
            case QEMU_OPTION_name:
4893
                qemu_name = optarg;
4894
                break;
4895
#if defined(TARGET_SPARC) || defined(TARGET_PPC)
4896
            case QEMU_OPTION_prom_env:
4897
                if (nb_prom_envs >= MAX_PROM_ENVS) {
4898
                    fprintf(stderr, "Too many prom variables\n");
4899
                    exit(1);
4900
                }
4901
                prom_envs[nb_prom_envs] = optarg;
4902
                nb_prom_envs++;
4903
                break;
4904
#endif
4905
#ifdef TARGET_ARM
4906
            case QEMU_OPTION_old_param:
4907
                old_param = 1;
4908
                break;
4909
#endif
4910
            case QEMU_OPTION_clock:
4911
                configure_alarms(optarg);
4912
                break;
4913
            case QEMU_OPTION_startdate:
4914
                {
4915
                    struct tm tm;
4916
                    time_t rtc_start_date;
4917
                    if (!strcmp(optarg, "now")) {
4918
                        rtc_date_offset = -1;
4919
                    } else {
4920
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
4921
                               &tm.tm_year,
4922
                               &tm.tm_mon,
4923
                               &tm.tm_mday,
4924
                               &tm.tm_hour,
4925
                               &tm.tm_min,
4926
                               &tm.tm_sec) == 6) {
4927
                            /* OK */
4928
                        } else if (sscanf(optarg, "%d-%d-%d",
4929
                                          &tm.tm_year,
4930
                                          &tm.tm_mon,
4931
                                          &tm.tm_mday) == 3) {
4932
                            tm.tm_hour = 0;
4933
                            tm.tm_min = 0;
4934
                            tm.tm_sec = 0;
4935
                        } else {
4936
                            goto date_fail;
4937
                        }
4938
                        tm.tm_year -= 1900;
4939
                        tm.tm_mon--;
4940
                        rtc_start_date = mktimegm(&tm);
4941
                        if (rtc_start_date == -1) {
4942
                        date_fail:
4943
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
4944
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
4945
                            exit(1);
4946
                        }
4947
                        rtc_date_offset = time(NULL) - rtc_start_date;
4948
                    }
4949
                }
4950
                break;
4951
            case QEMU_OPTION_tb_size:
4952
                tb_size = strtol(optarg, NULL, 0);
4953
                if (tb_size < 0)
4954
                    tb_size = 0;
4955
                break;
4956
            case QEMU_OPTION_icount:
4957
                use_icount = 1;
4958
                if (strcmp(optarg, "auto") == 0) {
4959
                    icount_time_shift = -1;
4960
                } else {
4961
                    icount_time_shift = strtol(optarg, NULL, 0);
4962
                }
4963
                break;
4964
            case QEMU_OPTION_incoming:
4965
                incoming = optarg;
4966
                break;
4967
#ifndef _WIN32
4968
            case QEMU_OPTION_chroot:
4969
                chroot_dir = optarg;
4970
                break;
4971
            case QEMU_OPTION_runas:
4972
                run_as = optarg;
4973
                break;
4974
#endif
4975
            }
4976
        }
4977
    }
4978

    
4979
#if defined(CONFIG_KVM) && defined(CONFIG_KQEMU)
4980
    if (kvm_allowed && kqemu_allowed) {
4981
        fprintf(stderr,
4982
                "You can not enable both KVM and kqemu at the same time\n");
4983
        exit(1);
4984
    }
4985
#endif
4986

    
4987
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
4988
    if (smp_cpus > machine->max_cpus) {
4989
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
4990
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
4991
                machine->max_cpus);
4992
        exit(1);
4993
    }
4994

    
4995
    if (nographic) {
4996
       if (serial_device_index == 0)
4997
           serial_devices[0] = "stdio";
4998
       if (parallel_device_index == 0)
4999
           parallel_devices[0] = "null";
5000
       if (strncmp(monitor_device, "vc", 2) == 0)
5001
           monitor_device = "stdio";
5002
    }
5003

    
5004
#ifndef _WIN32
5005
    if (daemonize) {
5006
        pid_t pid;
5007

    
5008
        if (pipe(fds) == -1)
5009
            exit(1);
5010

    
5011
        pid = fork();
5012
        if (pid > 0) {
5013
            uint8_t status;
5014
            ssize_t len;
5015

    
5016
            close(fds[1]);
5017

    
5018
        again:
5019
            len = read(fds[0], &status, 1);
5020
            if (len == -1 && (errno == EINTR))
5021
                goto again;
5022

    
5023
            if (len != 1)
5024
                exit(1);
5025
            else if (status == 1) {
5026
                fprintf(stderr, "Could not acquire pidfile\n");
5027
                exit(1);
5028
            } else
5029
                exit(0);
5030
        } else if (pid < 0)
5031
            exit(1);
5032

    
5033
        setsid();
5034

    
5035
        pid = fork();
5036
        if (pid > 0)
5037
            exit(0);
5038
        else if (pid < 0)
5039
            exit(1);
5040

    
5041
        umask(027);
5042

    
5043
        signal(SIGTSTP, SIG_IGN);
5044
        signal(SIGTTOU, SIG_IGN);
5045
        signal(SIGTTIN, SIG_IGN);
5046
    }
5047

    
5048
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
5049
        if (daemonize) {
5050
            uint8_t status = 1;
5051
            write(fds[1], &status, 1);
5052
        } else
5053
            fprintf(stderr, "Could not acquire pid file\n");
5054
        exit(1);
5055
    }
5056
#endif
5057

    
5058
#ifdef CONFIG_KQEMU
5059
    if (smp_cpus > 1)
5060
        kqemu_allowed = 0;
5061
#endif
5062
    linux_boot = (kernel_filename != NULL);
5063
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
5064

    
5065
    if (!linux_boot && *kernel_cmdline != '\0') {
5066
        fprintf(stderr, "-append only allowed with -kernel option\n");
5067
        exit(1);
5068
    }
5069

    
5070
    if (!linux_boot && initrd_filename != NULL) {
5071
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
5072
        exit(1);
5073
    }
5074

    
5075
    /* boot to floppy or the default cd if no hard disk defined yet */
5076
    if (!boot_devices[0]) {
5077
        boot_devices = "cad";
5078
    }
5079
    setvbuf(stdout, NULL, _IOLBF, 0);
5080

    
5081
    init_timers();
5082
    if (init_timer_alarm() < 0) {
5083
        fprintf(stderr, "could not initialize alarm timer\n");
5084
        exit(1);
5085
    }
5086
    if (use_icount && icount_time_shift < 0) {
5087
        use_icount = 2;
5088
        /* 125MIPS seems a reasonable initial guess at the guest speed.
5089
           It will be corrected fairly quickly anyway.  */
5090
        icount_time_shift = 3;
5091
        init_icount_adjust();
5092
    }
5093

    
5094
#ifdef _WIN32
5095
    socket_init();
5096
#endif
5097

    
5098
    /* init network clients */
5099
    if (nb_net_clients == 0) {
5100
        /* if no clients, we use a default config */
5101
        net_clients[nb_net_clients++] = "nic";
5102
#ifdef CONFIG_SLIRP
5103
        net_clients[nb_net_clients++] = "user";
5104
#endif
5105
    }
5106

    
5107
    for(i = 0;i < nb_net_clients; i++) {
5108
        if (net_client_parse(net_clients[i]) < 0)
5109
            exit(1);
5110
    }
5111
    net_client_check();
5112

    
5113
#ifdef TARGET_I386
5114
    /* XXX: this should be moved in the PC machine instantiation code */
5115
    if (net_boot != 0) {
5116
        int netroms = 0;
5117
        for (i = 0; i < nb_nics && i < 4; i++) {
5118
            const char *model = nd_table[i].model;
5119
            char buf[1024];
5120
            if (net_boot & (1 << i)) {
5121
                if (model == NULL)
5122
                    model = "ne2k_pci";
5123
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
5124
                if (get_image_size(buf) > 0) {
5125
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
5126
                        fprintf(stderr, "Too many option ROMs\n");
5127
                        exit(1);
5128
                    }
5129
                    option_rom[nb_option_roms] = strdup(buf);
5130
                    nb_option_roms++;
5131
                    netroms++;
5132
                }
5133
            }
5134
        }
5135
        if (netroms == 0) {
5136
            fprintf(stderr, "No valid PXE rom found for network device\n");
5137
            exit(1);
5138
        }
5139
    }
5140
#endif
5141

    
5142
    /* init the bluetooth world */
5143
    for (i = 0; i < nb_bt_opts; i++)
5144
        if (bt_parse(bt_opts[i]))
5145
            exit(1);
5146

    
5147
    /* init the memory */
5148
    if (ram_size == 0)
5149
        ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5150

    
5151
#ifdef CONFIG_KQEMU
5152
    /* FIXME: This is a nasty hack because kqemu can't cope with dynamic
5153
       guest ram allocation.  It needs to go away.  */
5154
    if (kqemu_allowed) {
5155
        kqemu_phys_ram_size = ram_size + VGA_RAM_SIZE + 4 * 1024 * 1024;
5156
        kqemu_phys_ram_base = qemu_vmalloc(kqemu_phys_ram_size);
5157
        if (!kqemu_phys_ram_base) {
5158
            fprintf(stderr, "Could not allocate physical memory\n");
5159
            exit(1);
5160
        }
5161
    }
5162
#endif
5163

    
5164
    /* init the dynamic translator */
5165
    cpu_exec_init_all(tb_size * 1024 * 1024);
5166

    
5167
    bdrv_init();
5168
    dma_helper_init();
5169

    
5170
    /* we always create the cdrom drive, even if no disk is there */
5171

    
5172
    if (nb_drives_opt < MAX_DRIVES)
5173
        drive_add(NULL, CDROM_ALIAS);
5174

    
5175
    /* we always create at least one floppy */
5176

    
5177
    if (nb_drives_opt < MAX_DRIVES)
5178
        drive_add(NULL, FD_ALIAS, 0);
5179

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

    
5182
    if (nb_drives_opt < MAX_DRIVES)
5183
        drive_add(NULL, SD_ALIAS);
5184

    
5185
    /* open the virtual block devices */
5186

    
5187
    for(i = 0; i < nb_drives_opt; i++)
5188
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
5189
            exit(1);
5190

    
5191
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
5192
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
5193

    
5194
#ifndef _WIN32
5195
    /* must be after terminal init, SDL library changes signal handlers */
5196
    termsig_setup();
5197
#endif
5198

    
5199
    /* Maintain compatibility with multiple stdio monitors */
5200
    if (!strcmp(monitor_device,"stdio")) {
5201
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
5202
            const char *devname = serial_devices[i];
5203
            if (devname && !strcmp(devname,"mon:stdio")) {
5204
                monitor_device = NULL;
5205
                break;
5206
            } else if (devname && !strcmp(devname,"stdio")) {
5207
                monitor_device = NULL;
5208
                serial_devices[i] = "mon:stdio";
5209
                break;
5210
            }
5211
        }
5212
    }
5213

    
5214
    if (kvm_enabled()) {
5215
        int ret;
5216

    
5217
        ret = kvm_init(smp_cpus);
5218
        if (ret < 0) {
5219
            fprintf(stderr, "failed to initialize KVM\n");
5220
            exit(1);
5221
        }
5222
    }
5223

    
5224
    if (monitor_device) {
5225
        monitor_hd = qemu_chr_open("monitor", monitor_device, NULL);
5226
        if (!monitor_hd) {
5227
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5228
            exit(1);
5229
        }
5230
    }
5231

    
5232
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5233
        const char *devname = serial_devices[i];
5234
        if (devname && strcmp(devname, "none")) {
5235
            char label[32];
5236
            snprintf(label, sizeof(label), "serial%d", i);
5237
            serial_hds[i] = qemu_chr_open(label, devname, NULL);
5238
            if (!serial_hds[i]) {
5239
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
5240
                        devname);
5241
                exit(1);
5242
            }
5243
        }
5244
    }
5245

    
5246
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5247
        const char *devname = parallel_devices[i];
5248
        if (devname && strcmp(devname, "none")) {
5249
            char label[32];
5250
            snprintf(label, sizeof(label), "parallel%d", i);
5251
            parallel_hds[i] = qemu_chr_open(label, devname, NULL);
5252
            if (!parallel_hds[i]) {
5253
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5254
                        devname);
5255
                exit(1);
5256
            }
5257
        }
5258
    }
5259

    
5260
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5261
        const char *devname = virtio_consoles[i];
5262
        if (devname && strcmp(devname, "none")) {
5263
            char label[32];
5264
            snprintf(label, sizeof(label), "virtcon%d", i);
5265
            virtcon_hds[i] = qemu_chr_open(label, devname, NULL);
5266
            if (!virtcon_hds[i]) {
5267
                fprintf(stderr, "qemu: could not open virtio console '%s'\n",
5268
                        devname);
5269
                exit(1);
5270
            }
5271
        }
5272
    }
5273

    
5274
    machine->init(ram_size, vga_ram_size, boot_devices,
5275
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
5276

    
5277
    current_machine = machine;
5278

    
5279
    /* Set KVM's vcpu state to qemu's initial CPUState. */
5280
    if (kvm_enabled()) {
5281
        int ret;
5282

    
5283
        ret = kvm_sync_vcpus();
5284
        if (ret < 0) {
5285
            fprintf(stderr, "failed to initialize vcpus\n");
5286
            exit(1);
5287
        }
5288
    }
5289

    
5290
    /* init USB devices */
5291
    if (usb_enabled) {
5292
        for(i = 0; i < usb_devices_index; i++) {
5293
            if (usb_device_add(usb_devices[i], 0) < 0) {
5294
                fprintf(stderr, "Warning: could not add USB device %s\n",
5295
                        usb_devices[i]);
5296
            }
5297
        }
5298
    }
5299

    
5300
    if (!display_state)
5301
        dumb_display_init();
5302
    /* just use the first displaystate for the moment */
5303
    ds = display_state;
5304
    /* terminal init */
5305
    if (nographic) {
5306
        if (curses) {
5307
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
5308
            exit(1);
5309
        }
5310
    } else { 
5311
#if defined(CONFIG_CURSES)
5312
            if (curses) {
5313
                /* At the moment curses cannot be used with other displays */
5314
                curses_display_init(ds, full_screen);
5315
            } else
5316
#endif
5317
            {
5318
                if (vnc_display != NULL) {
5319
                    vnc_display_init(ds);
5320
                    if (vnc_display_open(ds, vnc_display) < 0)
5321
                        exit(1);
5322
                }
5323
#if defined(CONFIG_SDL)
5324
                if (sdl || !vnc_display)
5325
                    sdl_display_init(ds, full_screen, no_frame);
5326
#elif defined(CONFIG_COCOA)
5327
                if (sdl || !vnc_display)
5328
                    cocoa_display_init(ds, full_screen);
5329
#endif
5330
            }
5331
    }
5332
    dpy_resize(ds);
5333

    
5334
    dcl = ds->listeners;
5335
    while (dcl != NULL) {
5336
        if (dcl->dpy_refresh != NULL) {
5337
            ds->gui_timer = qemu_new_timer(rt_clock, gui_update, ds);
5338
            qemu_mod_timer(ds->gui_timer, qemu_get_clock(rt_clock));
5339
        }
5340
        dcl = dcl->next;
5341
    }
5342

    
5343
    if (nographic || (vnc_display && !sdl)) {
5344
        nographic_timer = qemu_new_timer(rt_clock, nographic_update, NULL);
5345
        qemu_mod_timer(nographic_timer, qemu_get_clock(rt_clock));
5346
    }
5347

    
5348
    text_consoles_set_display(display_state);
5349
    qemu_chr_initial_reset();
5350

    
5351
    if (monitor_device && monitor_hd)
5352
        monitor_init(monitor_hd, MONITOR_USE_READLINE | MONITOR_IS_DEFAULT);
5353

    
5354
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5355
        const char *devname = serial_devices[i];
5356
        if (devname && strcmp(devname, "none")) {
5357
            char label[32];
5358
            snprintf(label, sizeof(label), "serial%d", i);
5359
            if (strstart(devname, "vc", 0))
5360
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
5361
        }
5362
    }
5363

    
5364
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5365
        const char *devname = parallel_devices[i];
5366
        if (devname && strcmp(devname, "none")) {
5367
            char label[32];
5368
            snprintf(label, sizeof(label), "parallel%d", i);
5369
            if (strstart(devname, "vc", 0))
5370
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
5371
        }
5372
    }
5373

    
5374
    for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
5375
        const char *devname = virtio_consoles[i];
5376
        if (virtcon_hds[i] && devname) {
5377
            char label[32];
5378
            snprintf(label, sizeof(label), "virtcon%d", i);
5379
            if (strstart(devname, "vc", 0))
5380
                qemu_chr_printf(virtcon_hds[i], "virtio console%d\r\n", i);
5381
        }
5382
    }
5383

    
5384
#ifdef CONFIG_GDBSTUB
5385
    if (gdbstub_dev && gdbserver_start(gdbstub_dev) < 0) {
5386
        fprintf(stderr, "qemu: could not open gdbserver on device '%s'\n",
5387
                gdbstub_dev);
5388
        exit(1);
5389
    }
5390
#endif
5391

    
5392
    if (loadvm)
5393
        do_loadvm(cur_mon, loadvm);
5394

    
5395
    if (incoming) {
5396
        autostart = 0; /* fixme how to deal with -daemonize */
5397
        qemu_start_incoming_migration(incoming);
5398
    }
5399

    
5400
    if (autostart)
5401
        vm_start();
5402

    
5403
#ifndef _WIN32
5404
    if (daemonize) {
5405
        uint8_t status = 0;
5406
        ssize_t len;
5407

    
5408
    again1:
5409
        len = write(fds[1], &status, 1);
5410
        if (len == -1 && (errno == EINTR))
5411
            goto again1;
5412

    
5413
        if (len != 1)
5414
            exit(1);
5415

    
5416
        chdir("/");
5417
        TFR(fd = open("/dev/null", O_RDWR));
5418
        if (fd == -1)
5419
            exit(1);
5420
    }
5421

    
5422
    if (run_as) {
5423
        pwd = getpwnam(run_as);
5424
        if (!pwd) {
5425
            fprintf(stderr, "User \"%s\" doesn't exist\n", run_as);
5426
            exit(1);
5427
        }
5428
    }
5429

    
5430
    if (chroot_dir) {
5431
        if (chroot(chroot_dir) < 0) {
5432
            fprintf(stderr, "chroot failed\n");
5433
            exit(1);
5434
        }
5435
        chdir("/");
5436
    }
5437

    
5438
    if (run_as) {
5439
        if (setgid(pwd->pw_gid) < 0) {
5440
            fprintf(stderr, "Failed to setgid(%d)\n", pwd->pw_gid);
5441
            exit(1);
5442
        }
5443
        if (setuid(pwd->pw_uid) < 0) {
5444
            fprintf(stderr, "Failed to setuid(%d)\n", pwd->pw_uid);
5445
            exit(1);
5446
        }
5447
        if (setuid(0) != -1) {
5448
            fprintf(stderr, "Dropping privileges failed\n");
5449
            exit(1);
5450
        }
5451
    }
5452

    
5453
    if (daemonize) {
5454
        dup2(fd, 0);
5455
        dup2(fd, 1);
5456
        dup2(fd, 2);
5457

    
5458
        close(fd);
5459
    }
5460
#endif
5461

    
5462
    main_loop();
5463
    quit_timers();
5464
    net_cleanup();
5465

    
5466
    return 0;
5467
}