Statistics
| Branch: | Revision:

root / vl.c @ 63a01ef8

History | View | Annotate | Download (165.4 kB)

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

    
43
#include <unistd.h>
44
#include <fcntl.h>
45
#include <signal.h>
46
#include <time.h>
47
#include <errno.h>
48
#include <sys/time.h>
49
#include <zlib.h>
50

    
51
#ifndef _WIN32
52
#include <sys/times.h>
53
#include <sys/wait.h>
54
#include <termios.h>
55
#include <sys/mman.h>
56
#include <sys/ioctl.h>
57
#include <sys/socket.h>
58
#include <netinet/in.h>
59
#include <dirent.h>
60
#include <netdb.h>
61
#include <sys/select.h>
62
#include <arpa/inet.h>
63
#ifdef _BSD
64
#include <sys/stat.h>
65
#if !defined(__APPLE__) && !defined(__OpenBSD__)
66
#include <libutil.h>
67
#endif
68
#ifdef __OpenBSD__
69
#include <net/if.h>
70
#endif
71
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72
#include <freebsd/stdlib.h>
73
#else
74
#ifdef __linux__
75
#include <linux/if.h>
76
#include <linux/if_tun.h>
77
#include <pty.h>
78
#include <malloc.h>
79
#include <linux/rtc.h>
80

    
81
/* For the benefit of older linux systems which don't supply it,
82
   we use a local copy of hpet.h. */
83
/* #include <linux/hpet.h> */
84
#include "hpet.h"
85

    
86
#include <linux/ppdev.h>
87
#include <linux/parport.h>
88
#endif
89
#ifdef __sun__
90
#include <sys/stat.h>
91
#include <sys/ethernet.h>
92
#include <sys/sockio.h>
93
#include <netinet/arp.h>
94
#include <netinet/in.h>
95
#include <netinet/in_systm.h>
96
#include <netinet/ip.h>
97
#include <netinet/ip_icmp.h> // must come after ip.h
98
#include <netinet/udp.h>
99
#include <netinet/tcp.h>
100
#include <net/if.h>
101
#include <syslog.h>
102
#include <stropts.h>
103
#endif
104
#endif
105
#endif
106

    
107
#include "qemu_socket.h"
108

    
109
#if defined(CONFIG_SLIRP)
110
#include "libslirp.h"
111
#endif
112

    
113
#if defined(__OpenBSD__)
114
#include <util.h>
115
#endif
116

    
117
#if defined(CONFIG_VDE)
118
#include <libvdeplug.h>
119
#endif
120

    
121
#ifdef _WIN32
122
#include <malloc.h>
123
#include <sys/timeb.h>
124
#include <mmsystem.h>
125
#define getopt_long_only getopt_long
126
#define memalign(align, size) malloc(size)
127
#endif
128

    
129
#ifdef CONFIG_SDL
130
#ifdef __APPLE__
131
#include <SDL/SDL.h>
132
#endif
133
#endif /* CONFIG_SDL */
134

    
135
#ifdef CONFIG_COCOA
136
#undef main
137
#define main qemu_main
138
#endif /* CONFIG_COCOA */
139

    
140
#include "disas.h"
141

    
142
#include "exec-all.h"
143

    
144
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
145
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
146
#ifdef __sun__
147
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
148
#else
149
#define SMBD_COMMAND "/usr/sbin/smbd"
150
#endif
151

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

    
157
#ifdef TARGET_PPC
158
#define DEFAULT_RAM_SIZE 144
159
#else
160
#define DEFAULT_RAM_SIZE 128
161
#endif
162

    
163
/* Max number of USB devices that can be specified on the commandline.  */
164
#define MAX_USB_CMDLINE 8
165

    
166
/* XXX: use a two level table to limit memory usage */
167
#define MAX_IOPORTS 65536
168

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

    
240
static CPUState *cur_cpu;
241
static CPUState *next_cpu;
242
static int event_pending = 1;
243
/* Conversion factor from emulated instructions to virtual clock ticks.  */
244
static int icount_time_shift;
245
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
246
#define MAX_ICOUNT_SHIFT 10
247
/* Compensate for varying guest execution speed.  */
248
static int64_t qemu_icount_bias;
249
static QEMUTimer *icount_rt_timer;
250
static QEMUTimer *icount_vm_timer;
251

    
252
uint8_t qemu_uuid[16];
253

    
254
/***********************************************************/
255
/* x86 ISA bus support */
256

    
257
target_phys_addr_t isa_mem_base = 0;
258
PicState2 *isa_pic;
259

    
260
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
261
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
262

    
263
static uint32_t ioport_read(int index, uint32_t address)
264
{
265
    static IOPortReadFunc *default_func[3] = {
266
        default_ioport_readb,
267
        default_ioport_readw,
268
        default_ioport_readl
269
    };
270
    IOPortReadFunc *func = ioport_read_table[index][address];
271
    if (!func)
272
        func = default_func[index];
273
    return func(ioport_opaque[address], address);
274
}
275

    
276
static void ioport_write(int index, uint32_t address, uint32_t data)
277
{
278
    static IOPortWriteFunc *default_func[3] = {
279
        default_ioport_writeb,
280
        default_ioport_writew,
281
        default_ioport_writel
282
    };
283
    IOPortWriteFunc *func = ioport_write_table[index][address];
284
    if (!func)
285
        func = default_func[index];
286
    func(ioport_opaque[address], address, data);
287
}
288

    
289
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
290
{
291
#ifdef DEBUG_UNUSED_IOPORT
292
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
293
#endif
294
    return 0xff;
295
}
296

    
297
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
298
{
299
#ifdef DEBUG_UNUSED_IOPORT
300
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
301
#endif
302
}
303

    
304
/* default is to make two byte accesses */
305
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
306
{
307
    uint32_t data;
308
    data = ioport_read(0, address);
309
    address = (address + 1) & (MAX_IOPORTS - 1);
310
    data |= ioport_read(0, address) << 8;
311
    return data;
312
}
313

    
314
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
315
{
316
    ioport_write(0, address, data & 0xff);
317
    address = (address + 1) & (MAX_IOPORTS - 1);
318
    ioport_write(0, address, (data >> 8) & 0xff);
319
}
320

    
321
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
322
{
323
#ifdef DEBUG_UNUSED_IOPORT
324
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
325
#endif
326
    return 0xffffffff;
327
}
328

    
329
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
330
{
331
#ifdef DEBUG_UNUSED_IOPORT
332
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
333
#endif
334
}
335

    
336
/* size is the word size in byte */
337
int register_ioport_read(int start, int length, int size,
338
                         IOPortReadFunc *func, void *opaque)
339
{
340
    int i, bsize;
341

    
342
    if (size == 1) {
343
        bsize = 0;
344
    } else if (size == 2) {
345
        bsize = 1;
346
    } else if (size == 4) {
347
        bsize = 2;
348
    } else {
349
        hw_error("register_ioport_read: invalid size");
350
        return -1;
351
    }
352
    for(i = start; i < start + length; i += size) {
353
        ioport_read_table[bsize][i] = func;
354
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
355
            hw_error("register_ioport_read: invalid opaque");
356
        ioport_opaque[i] = opaque;
357
    }
358
    return 0;
359
}
360

    
361
/* size is the word size in byte */
362
int register_ioport_write(int start, int length, int size,
363
                          IOPortWriteFunc *func, void *opaque)
364
{
365
    int i, bsize;
366

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

    
386
void isa_unassign_ioport(int start, int length)
387
{
388
    int i;
389

    
390
    for(i = start; i < start + length; i++) {
391
        ioport_read_table[0][i] = default_ioport_readb;
392
        ioport_read_table[1][i] = default_ioport_readw;
393
        ioport_read_table[2][i] = default_ioport_readl;
394

    
395
        ioport_write_table[0][i] = default_ioport_writeb;
396
        ioport_write_table[1][i] = default_ioport_writew;
397
        ioport_write_table[2][i] = default_ioport_writel;
398
    }
399
}
400

    
401
/***********************************************************/
402

    
403
void cpu_outb(CPUState *env, int addr, int val)
404
{
405
#ifdef DEBUG_IOPORT
406
    if (loglevel & CPU_LOG_IOPORT)
407
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
408
#endif
409
    ioport_write(0, addr, val);
410
#ifdef USE_KQEMU
411
    if (env)
412
        env->last_io_time = cpu_get_time_fast();
413
#endif
414
}
415

    
416
void cpu_outw(CPUState *env, int addr, int val)
417
{
418
#ifdef DEBUG_IOPORT
419
    if (loglevel & CPU_LOG_IOPORT)
420
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
421
#endif
422
    ioport_write(1, addr, val);
423
#ifdef USE_KQEMU
424
    if (env)
425
        env->last_io_time = cpu_get_time_fast();
426
#endif
427
}
428

    
429
void cpu_outl(CPUState *env, int addr, int val)
430
{
431
#ifdef DEBUG_IOPORT
432
    if (loglevel & CPU_LOG_IOPORT)
433
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
434
#endif
435
    ioport_write(2, addr, val);
436
#ifdef USE_KQEMU
437
    if (env)
438
        env->last_io_time = cpu_get_time_fast();
439
#endif
440
}
441

    
442
int cpu_inb(CPUState *env, int addr)
443
{
444
    int val;
445
    val = ioport_read(0, addr);
446
#ifdef DEBUG_IOPORT
447
    if (loglevel & CPU_LOG_IOPORT)
448
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
449
#endif
450
#ifdef USE_KQEMU
451
    if (env)
452
        env->last_io_time = cpu_get_time_fast();
453
#endif
454
    return val;
455
}
456

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

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

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

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

    
509
/***********************************************************/
510
/* keyboard/mouse */
511

    
512
static QEMUPutKBDEvent *qemu_put_kbd_event;
513
static void *qemu_put_kbd_event_opaque;
514
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
515
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
516

    
517
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
518
{
519
    qemu_put_kbd_event_opaque = opaque;
520
    qemu_put_kbd_event = func;
521
}
522

    
523
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
524
                                                void *opaque, int absolute,
525
                                                const char *name)
526
{
527
    QEMUPutMouseEntry *s, *cursor;
528

    
529
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
530
    if (!s)
531
        return NULL;
532

    
533
    s->qemu_put_mouse_event = func;
534
    s->qemu_put_mouse_event_opaque = opaque;
535
    s->qemu_put_mouse_event_absolute = absolute;
536
    s->qemu_put_mouse_event_name = qemu_strdup(name);
537
    s->next = NULL;
538

    
539
    if (!qemu_put_mouse_event_head) {
540
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
541
        return s;
542
    }
543

    
544
    cursor = qemu_put_mouse_event_head;
545
    while (cursor->next != NULL)
546
        cursor = cursor->next;
547

    
548
    cursor->next = s;
549
    qemu_put_mouse_event_current = s;
550

    
551
    return s;
552
}
553

    
554
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
555
{
556
    QEMUPutMouseEntry *prev = NULL, *cursor;
557

    
558
    if (!qemu_put_mouse_event_head || entry == NULL)
559
        return;
560

    
561
    cursor = qemu_put_mouse_event_head;
562
    while (cursor != NULL && cursor != entry) {
563
        prev = cursor;
564
        cursor = cursor->next;
565
    }
566

    
567
    if (cursor == NULL) // does not exist or list empty
568
        return;
569
    else if (prev == NULL) { // entry is head
570
        qemu_put_mouse_event_head = cursor->next;
571
        if (qemu_put_mouse_event_current == entry)
572
            qemu_put_mouse_event_current = cursor->next;
573
        qemu_free(entry->qemu_put_mouse_event_name);
574
        qemu_free(entry);
575
        return;
576
    }
577

    
578
    prev->next = entry->next;
579

    
580
    if (qemu_put_mouse_event_current == entry)
581
        qemu_put_mouse_event_current = prev;
582

    
583
    qemu_free(entry->qemu_put_mouse_event_name);
584
    qemu_free(entry);
585
}
586

    
587
void kbd_put_keycode(int keycode)
588
{
589
    if (qemu_put_kbd_event) {
590
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
591
    }
592
}
593

    
594
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
595
{
596
    QEMUPutMouseEvent *mouse_event;
597
    void *mouse_event_opaque;
598
    int width;
599

    
600
    if (!qemu_put_mouse_event_current) {
601
        return;
602
    }
603

    
604
    mouse_event =
605
        qemu_put_mouse_event_current->qemu_put_mouse_event;
606
    mouse_event_opaque =
607
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
608

    
609
    if (mouse_event) {
610
        if (graphic_rotate) {
611
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
612
                width = 0x7fff;
613
            else
614
                width = graphic_width - 1;
615
            mouse_event(mouse_event_opaque,
616
                                 width - dy, dx, dz, buttons_state);
617
        } else
618
            mouse_event(mouse_event_opaque,
619
                                 dx, dy, dz, buttons_state);
620
    }
621
}
622

    
623
int kbd_mouse_is_absolute(void)
624
{
625
    if (!qemu_put_mouse_event_current)
626
        return 0;
627

    
628
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
629
}
630

    
631
void do_info_mice(void)
632
{
633
    QEMUPutMouseEntry *cursor;
634
    int index = 0;
635

    
636
    if (!qemu_put_mouse_event_head) {
637
        term_printf("No mouse devices connected\n");
638
        return;
639
    }
640

    
641
    term_printf("Mouse devices available:\n");
642
    cursor = qemu_put_mouse_event_head;
643
    while (cursor != NULL) {
644
        term_printf("%c Mouse #%d: %s\n",
645
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
646
                    index, cursor->qemu_put_mouse_event_name);
647
        index++;
648
        cursor = cursor->next;
649
    }
650
}
651

    
652
void do_mouse_set(int index)
653
{
654
    QEMUPutMouseEntry *cursor;
655
    int i = 0;
656

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

    
662
    cursor = qemu_put_mouse_event_head;
663
    while (cursor != NULL && index != i) {
664
        i++;
665
        cursor = cursor->next;
666
    }
667

    
668
    if (cursor != NULL)
669
        qemu_put_mouse_event_current = cursor;
670
    else
671
        term_printf("Mouse at given index not found\n");
672
}
673

    
674
/* compute with 96 bit intermediate result: (a*b)/c */
675
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
676
{
677
    union {
678
        uint64_t ll;
679
        struct {
680
#ifdef WORDS_BIGENDIAN
681
            uint32_t high, low;
682
#else
683
            uint32_t low, high;
684
#endif
685
        } l;
686
    } u, res;
687
    uint64_t rl, rh;
688

    
689
    u.ll = a;
690
    rl = (uint64_t)u.l.low * (uint64_t)b;
691
    rh = (uint64_t)u.l.high * (uint64_t)b;
692
    rh += (rl >> 32);
693
    res.l.high = rh / c;
694
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
695
    return res.ll;
696
}
697

    
698
/***********************************************************/
699
/* real time host monotonic timer */
700

    
701
#define QEMU_TIMER_BASE 1000000000LL
702

    
703
#ifdef WIN32
704

    
705
static int64_t clock_freq;
706

    
707
static void init_get_clock(void)
708
{
709
    LARGE_INTEGER freq;
710
    int ret;
711
    ret = QueryPerformanceFrequency(&freq);
712
    if (ret == 0) {
713
        fprintf(stderr, "Could not calibrate ticks\n");
714
        exit(1);
715
    }
716
    clock_freq = freq.QuadPart;
717
}
718

    
719
static int64_t get_clock(void)
720
{
721
    LARGE_INTEGER ti;
722
    QueryPerformanceCounter(&ti);
723
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
724
}
725

    
726
#else
727

    
728
static int use_rt_clock;
729

    
730
static void init_get_clock(void)
731
{
732
    use_rt_clock = 0;
733
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
734
    {
735
        struct timespec ts;
736
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
737
            use_rt_clock = 1;
738
        }
739
    }
740
#endif
741
}
742

    
743
static int64_t get_clock(void)
744
{
745
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD_version >= 500000)
746
    if (use_rt_clock) {
747
        struct timespec ts;
748
        clock_gettime(CLOCK_MONOTONIC, &ts);
749
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
750
    } else
751
#endif
752
    {
753
        /* XXX: using gettimeofday leads to problems if the date
754
           changes, so it should be avoided. */
755
        struct timeval tv;
756
        gettimeofday(&tv, NULL);
757
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
758
    }
759
}
760
#endif
761

    
762
/* Return the virtual CPU time, based on the instruction counter.  */
763
static int64_t cpu_get_icount(void)
764
{
765
    int64_t icount;
766
    CPUState *env = cpu_single_env;;
767
    icount = qemu_icount;
768
    if (env) {
769
        if (!can_do_io(env))
770
            fprintf(stderr, "Bad clock read\n");
771
        icount -= (env->icount_decr.u16.low + env->icount_extra);
772
    }
773
    return qemu_icount_bias + (icount << icount_time_shift);
774
}
775

    
776
/***********************************************************/
777
/* guest cycle counter */
778

    
779
static int64_t cpu_ticks_prev;
780
static int64_t cpu_ticks_offset;
781
static int64_t cpu_clock_offset;
782
static int cpu_ticks_enabled;
783

    
784
/* return the host CPU cycle counter and handle stop/restart */
785
int64_t cpu_get_ticks(void)
786
{
787
    if (use_icount) {
788
        return cpu_get_icount();
789
    }
790
    if (!cpu_ticks_enabled) {
791
        return cpu_ticks_offset;
792
    } else {
793
        int64_t ticks;
794
        ticks = cpu_get_real_ticks();
795
        if (cpu_ticks_prev > ticks) {
796
            /* Note: non increasing ticks may happen if the host uses
797
               software suspend */
798
            cpu_ticks_offset += cpu_ticks_prev - ticks;
799
        }
800
        cpu_ticks_prev = ticks;
801
        return ticks + cpu_ticks_offset;
802
    }
803
}
804

    
805
/* return the host CPU monotonic timer and handle stop/restart */
806
static int64_t cpu_get_clock(void)
807
{
808
    int64_t ti;
809
    if (!cpu_ticks_enabled) {
810
        return cpu_clock_offset;
811
    } else {
812
        ti = get_clock();
813
        return ti + cpu_clock_offset;
814
    }
815
}
816

    
817
/* enable cpu_get_ticks() */
818
void cpu_enable_ticks(void)
819
{
820
    if (!cpu_ticks_enabled) {
821
        cpu_ticks_offset -= cpu_get_real_ticks();
822
        cpu_clock_offset -= get_clock();
823
        cpu_ticks_enabled = 1;
824
    }
825
}
826

    
827
/* disable cpu_get_ticks() : the clock is stopped. You must not call
828
   cpu_get_ticks() after that.  */
829
void cpu_disable_ticks(void)
830
{
831
    if (cpu_ticks_enabled) {
832
        cpu_ticks_offset = cpu_get_ticks();
833
        cpu_clock_offset = cpu_get_clock();
834
        cpu_ticks_enabled = 0;
835
    }
836
}
837

    
838
/***********************************************************/
839
/* timers */
840

    
841
#define QEMU_TIMER_REALTIME 0
842
#define QEMU_TIMER_VIRTUAL  1
843

    
844
struct QEMUClock {
845
    int type;
846
    /* XXX: add frequency */
847
};
848

    
849
struct QEMUTimer {
850
    QEMUClock *clock;
851
    int64_t expire_time;
852
    QEMUTimerCB *cb;
853
    void *opaque;
854
    struct QEMUTimer *next;
855
};
856

    
857
struct qemu_alarm_timer {
858
    char const *name;
859
    unsigned int flags;
860

    
861
    int (*start)(struct qemu_alarm_timer *t);
862
    void (*stop)(struct qemu_alarm_timer *t);
863
    void (*rearm)(struct qemu_alarm_timer *t);
864
    void *priv;
865
};
866

    
867
#define ALARM_FLAG_DYNTICKS  0x1
868
#define ALARM_FLAG_EXPIRED   0x2
869

    
870
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
871
{
872
    return t->flags & ALARM_FLAG_DYNTICKS;
873
}
874

    
875
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
876
{
877
    if (!alarm_has_dynticks(t))
878
        return;
879

    
880
    t->rearm(t);
881
}
882

    
883
/* TODO: MIN_TIMER_REARM_US should be optimized */
884
#define MIN_TIMER_REARM_US 250
885

    
886
static struct qemu_alarm_timer *alarm_timer;
887

    
888
#ifdef _WIN32
889

    
890
struct qemu_alarm_win32 {
891
    MMRESULT timerId;
892
    HANDLE host_alarm;
893
    unsigned int period;
894
} alarm_win32_data = {0, NULL, -1};
895

    
896
static int win32_start_timer(struct qemu_alarm_timer *t);
897
static void win32_stop_timer(struct qemu_alarm_timer *t);
898
static void win32_rearm_timer(struct qemu_alarm_timer *t);
899

    
900
#else
901

    
902
static int unix_start_timer(struct qemu_alarm_timer *t);
903
static void unix_stop_timer(struct qemu_alarm_timer *t);
904

    
905
#ifdef __linux__
906

    
907
static int dynticks_start_timer(struct qemu_alarm_timer *t);
908
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
909
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
910

    
911
static int hpet_start_timer(struct qemu_alarm_timer *t);
912
static void hpet_stop_timer(struct qemu_alarm_timer *t);
913

    
914
static int rtc_start_timer(struct qemu_alarm_timer *t);
915
static void rtc_stop_timer(struct qemu_alarm_timer *t);
916

    
917
#endif /* __linux__ */
918

    
919
#endif /* _WIN32 */
920

    
921
/* Correlation between real and virtual time is always going to be
922
   fairly approximate, so ignore small variation.
923
   When the guest is idle real and virtual time will be aligned in
924
   the IO wait loop.  */
925
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
926

    
927
static void icount_adjust(void)
928
{
929
    int64_t cur_time;
930
    int64_t cur_icount;
931
    int64_t delta;
932
    static int64_t last_delta;
933
    /* If the VM is not running, then do nothing.  */
934
    if (!vm_running)
935
        return;
936

    
937
    cur_time = cpu_get_clock();
938
    cur_icount = qemu_get_clock(vm_clock);
939
    delta = cur_icount - cur_time;
940
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
941
    if (delta > 0
942
        && last_delta + ICOUNT_WOBBLE < delta * 2
943
        && icount_time_shift > 0) {
944
        /* The guest is getting too far ahead.  Slow time down.  */
945
        icount_time_shift--;
946
    }
947
    if (delta < 0
948
        && last_delta - ICOUNT_WOBBLE > delta * 2
949
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
950
        /* The guest is getting too far behind.  Speed time up.  */
951
        icount_time_shift++;
952
    }
953
    last_delta = delta;
954
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
955
}
956

    
957
static void icount_adjust_rt(void * opaque)
958
{
959
    qemu_mod_timer(icount_rt_timer,
960
                   qemu_get_clock(rt_clock) + 1000);
961
    icount_adjust();
962
}
963

    
964
static void icount_adjust_vm(void * opaque)
965
{
966
    qemu_mod_timer(icount_vm_timer,
967
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
968
    icount_adjust();
969
}
970

    
971
static void init_icount_adjust(void)
972
{
973
    /* Have both realtime and virtual time triggers for speed adjustment.
974
       The realtime trigger catches emulated time passing too slowly,
975
       the virtual time trigger catches emulated time passing too fast.
976
       Realtime triggers occur even when idle, so use them less frequently
977
       than VM triggers.  */
978
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
979
    qemu_mod_timer(icount_rt_timer,
980
                   qemu_get_clock(rt_clock) + 1000);
981
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
982
    qemu_mod_timer(icount_vm_timer,
983
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
984
}
985

    
986
static struct qemu_alarm_timer alarm_timers[] = {
987
#ifndef _WIN32
988
#ifdef __linux__
989
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
990
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
991
    /* HPET - if available - is preferred */
992
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
993
    /* ...otherwise try RTC */
994
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
995
#endif
996
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
997
#else
998
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
999
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
1000
    {"win32", 0, win32_start_timer,
1001
     win32_stop_timer, NULL, &alarm_win32_data},
1002
#endif
1003
    {NULL, }
1004
};
1005

    
1006
static void show_available_alarms(void)
1007
{
1008
    int i;
1009

    
1010
    printf("Available alarm timers, in order of precedence:\n");
1011
    for (i = 0; alarm_timers[i].name; i++)
1012
        printf("%s\n", alarm_timers[i].name);
1013
}
1014

    
1015
static void configure_alarms(char const *opt)
1016
{
1017
    int i;
1018
    int cur = 0;
1019
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1020
    char *arg;
1021
    char *name;
1022
    struct qemu_alarm_timer tmp;
1023

    
1024
    if (!strcmp(opt, "?")) {
1025
        show_available_alarms();
1026
        exit(0);
1027
    }
1028

    
1029
    arg = strdup(opt);
1030

    
1031
    /* Reorder the array */
1032
    name = strtok(arg, ",");
1033
    while (name) {
1034
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1035
            if (!strcmp(alarm_timers[i].name, name))
1036
                break;
1037
        }
1038

    
1039
        if (i == count) {
1040
            fprintf(stderr, "Unknown clock %s\n", name);
1041
            goto next;
1042
        }
1043

    
1044
        if (i < cur)
1045
            /* Ignore */
1046
            goto next;
1047

    
1048
        /* Swap */
1049
        tmp = alarm_timers[i];
1050
        alarm_timers[i] = alarm_timers[cur];
1051
        alarm_timers[cur] = tmp;
1052

    
1053
        cur++;
1054
next:
1055
        name = strtok(NULL, ",");
1056
    }
1057

    
1058
    free(arg);
1059

    
1060
    if (cur) {
1061
        /* Disable remaining timers */
1062
        for (i = cur; i < count; i++)
1063
            alarm_timers[i].name = NULL;
1064
    } else {
1065
        show_available_alarms();
1066
        exit(1);
1067
    }
1068
}
1069

    
1070
QEMUClock *rt_clock;
1071
QEMUClock *vm_clock;
1072

    
1073
static QEMUTimer *active_timers[2];
1074

    
1075
static QEMUClock *qemu_new_clock(int type)
1076
{
1077
    QEMUClock *clock;
1078
    clock = qemu_mallocz(sizeof(QEMUClock));
1079
    if (!clock)
1080
        return NULL;
1081
    clock->type = type;
1082
    return clock;
1083
}
1084

    
1085
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1086
{
1087
    QEMUTimer *ts;
1088

    
1089
    ts = qemu_mallocz(sizeof(QEMUTimer));
1090
    ts->clock = clock;
1091
    ts->cb = cb;
1092
    ts->opaque = opaque;
1093
    return ts;
1094
}
1095

    
1096
void qemu_free_timer(QEMUTimer *ts)
1097
{
1098
    qemu_free(ts);
1099
}
1100

    
1101
/* stop a timer, but do not dealloc it */
1102
void qemu_del_timer(QEMUTimer *ts)
1103
{
1104
    QEMUTimer **pt, *t;
1105

    
1106
    /* NOTE: this code must be signal safe because
1107
       qemu_timer_expired() can be called from a signal. */
1108
    pt = &active_timers[ts->clock->type];
1109
    for(;;) {
1110
        t = *pt;
1111
        if (!t)
1112
            break;
1113
        if (t == ts) {
1114
            *pt = t->next;
1115
            break;
1116
        }
1117
        pt = &t->next;
1118
    }
1119
}
1120

    
1121
/* modify the current timer so that it will be fired when current_time
1122
   >= expire_time. The corresponding callback will be called. */
1123
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1124
{
1125
    QEMUTimer **pt, *t;
1126

    
1127
    qemu_del_timer(ts);
1128

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

    
1145
    /* Rearm if necessary  */
1146
    if (pt == &active_timers[ts->clock->type]) {
1147
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1148
            qemu_rearm_alarm_timer(alarm_timer);
1149
        }
1150
        /* Interrupt execution to force deadline recalculation.  */
1151
        if (use_icount && cpu_single_env) {
1152
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1153
        }
1154
    }
1155
}
1156

    
1157
int qemu_timer_pending(QEMUTimer *ts)
1158
{
1159
    QEMUTimer *t;
1160
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1161
        if (t == ts)
1162
            return 1;
1163
    }
1164
    return 0;
1165
}
1166

    
1167
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1168
{
1169
    if (!timer_head)
1170
        return 0;
1171
    return (timer_head->expire_time <= current_time);
1172
}
1173

    
1174
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1175
{
1176
    QEMUTimer *ts;
1177

    
1178
    for(;;) {
1179
        ts = *ptimer_head;
1180
        if (!ts || ts->expire_time > current_time)
1181
            break;
1182
        /* remove timer from the list before calling the callback */
1183
        *ptimer_head = ts->next;
1184
        ts->next = NULL;
1185

    
1186
        /* run the callback (the timer list can be modified) */
1187
        ts->cb(ts->opaque);
1188
    }
1189
}
1190

    
1191
int64_t qemu_get_clock(QEMUClock *clock)
1192
{
1193
    switch(clock->type) {
1194
    case QEMU_TIMER_REALTIME:
1195
        return get_clock() / 1000000;
1196
    default:
1197
    case QEMU_TIMER_VIRTUAL:
1198
        if (use_icount) {
1199
            return cpu_get_icount();
1200
        } else {
1201
            return cpu_get_clock();
1202
        }
1203
    }
1204
}
1205

    
1206
static void init_timers(void)
1207
{
1208
    init_get_clock();
1209
    ticks_per_sec = QEMU_TIMER_BASE;
1210
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1211
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1212
}
1213

    
1214
/* save a timer */
1215
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1216
{
1217
    uint64_t expire_time;
1218

    
1219
    if (qemu_timer_pending(ts)) {
1220
        expire_time = ts->expire_time;
1221
    } else {
1222
        expire_time = -1;
1223
    }
1224
    qemu_put_be64(f, expire_time);
1225
}
1226

    
1227
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1228
{
1229
    uint64_t expire_time;
1230

    
1231
    expire_time = qemu_get_be64(f);
1232
    if (expire_time != -1) {
1233
        qemu_mod_timer(ts, expire_time);
1234
    } else {
1235
        qemu_del_timer(ts);
1236
    }
1237
}
1238

    
1239
static void timer_save(QEMUFile *f, void *opaque)
1240
{
1241
    if (cpu_ticks_enabled) {
1242
        hw_error("cannot save state if virtual timers are running");
1243
    }
1244
    qemu_put_be64(f, cpu_ticks_offset);
1245
    qemu_put_be64(f, ticks_per_sec);
1246
    qemu_put_be64(f, cpu_clock_offset);
1247
}
1248

    
1249
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1250
{
1251
    if (version_id != 1 && version_id != 2)
1252
        return -EINVAL;
1253
    if (cpu_ticks_enabled) {
1254
        return -EINVAL;
1255
    }
1256
    cpu_ticks_offset=qemu_get_be64(f);
1257
    ticks_per_sec=qemu_get_be64(f);
1258
    if (version_id == 2) {
1259
        cpu_clock_offset=qemu_get_be64(f);
1260
    }
1261
    return 0;
1262
}
1263

    
1264
#ifdef _WIN32
1265
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1266
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1267
#else
1268
static void host_alarm_handler(int host_signum)
1269
#endif
1270
{
1271
#if 0
1272
#define DISP_FREQ 1000
1273
    {
1274
        static int64_t delta_min = INT64_MAX;
1275
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1276
        static int count;
1277
        ti = qemu_get_clock(vm_clock);
1278
        if (last_clock != 0) {
1279
            delta = ti - last_clock;
1280
            if (delta < delta_min)
1281
                delta_min = delta;
1282
            if (delta > delta_max)
1283
                delta_max = delta;
1284
            delta_cum += delta;
1285
            if (++count == DISP_FREQ) {
1286
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1287
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1288
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1289
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1290
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1291
                count = 0;
1292
                delta_min = INT64_MAX;
1293
                delta_max = 0;
1294
                delta_cum = 0;
1295
            }
1296
        }
1297
        last_clock = ti;
1298
    }
1299
#endif
1300
    if (alarm_has_dynticks(alarm_timer) ||
1301
        (!use_icount &&
1302
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1303
                               qemu_get_clock(vm_clock))) ||
1304
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1305
                           qemu_get_clock(rt_clock))) {
1306
#ifdef _WIN32
1307
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1308
        SetEvent(data->host_alarm);
1309
#endif
1310
        CPUState *env = next_cpu;
1311

    
1312
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1313

    
1314
        if (env) {
1315
            /* stop the currently executing cpu because a timer occured */
1316
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1317
#ifdef USE_KQEMU
1318
            if (env->kqemu_enabled) {
1319
                kqemu_cpu_interrupt(env);
1320
            }
1321
#endif
1322
        }
1323
        event_pending = 1;
1324
    }
1325
}
1326

    
1327
static int64_t qemu_next_deadline(void)
1328
{
1329
    int64_t delta;
1330

    
1331
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1332
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1333
                     qemu_get_clock(vm_clock);
1334
    } else {
1335
        /* To avoid problems with overflow limit this to 2^32.  */
1336
        delta = INT32_MAX;
1337
    }
1338

    
1339
    if (delta < 0)
1340
        delta = 0;
1341

    
1342
    return delta;
1343
}
1344

    
1345
#if defined(__linux__) || defined(_WIN32)
1346
static uint64_t qemu_next_deadline_dyntick(void)
1347
{
1348
    int64_t delta;
1349
    int64_t rtdelta;
1350

    
1351
    if (use_icount)
1352
        delta = INT32_MAX;
1353
    else
1354
        delta = (qemu_next_deadline() + 999) / 1000;
1355

    
1356
    if (active_timers[QEMU_TIMER_REALTIME]) {
1357
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1358
                 qemu_get_clock(rt_clock))*1000;
1359
        if (rtdelta < delta)
1360
            delta = rtdelta;
1361
    }
1362

    
1363
    if (delta < MIN_TIMER_REARM_US)
1364
        delta = MIN_TIMER_REARM_US;
1365

    
1366
    return delta;
1367
}
1368
#endif
1369

    
1370
#ifndef _WIN32
1371

    
1372
#if defined(__linux__)
1373

    
1374
#define RTC_FREQ 1024
1375

    
1376
static void enable_sigio_timer(int fd)
1377
{
1378
    struct sigaction act;
1379

    
1380
    /* timer signal */
1381
    sigfillset(&act.sa_mask);
1382
    act.sa_flags = 0;
1383
    act.sa_handler = host_alarm_handler;
1384

    
1385
    sigaction(SIGIO, &act, NULL);
1386
    fcntl(fd, F_SETFL, O_ASYNC);
1387
    fcntl(fd, F_SETOWN, getpid());
1388
}
1389

    
1390
static int hpet_start_timer(struct qemu_alarm_timer *t)
1391
{
1392
    struct hpet_info info;
1393
    int r, fd;
1394

    
1395
    fd = open("/dev/hpet", O_RDONLY);
1396
    if (fd < 0)
1397
        return -1;
1398

    
1399
    /* Set frequency */
1400
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1401
    if (r < 0) {
1402
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1403
                "error, but for better emulation accuracy type:\n"
1404
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1405
        goto fail;
1406
    }
1407

    
1408
    /* Check capabilities */
1409
    r = ioctl(fd, HPET_INFO, &info);
1410
    if (r < 0)
1411
        goto fail;
1412

    
1413
    /* Enable periodic mode */
1414
    r = ioctl(fd, HPET_EPI, 0);
1415
    if (info.hi_flags && (r < 0))
1416
        goto fail;
1417

    
1418
    /* Enable interrupt */
1419
    r = ioctl(fd, HPET_IE_ON, 0);
1420
    if (r < 0)
1421
        goto fail;
1422

    
1423
    enable_sigio_timer(fd);
1424
    t->priv = (void *)(long)fd;
1425

    
1426
    return 0;
1427
fail:
1428
    close(fd);
1429
    return -1;
1430
}
1431

    
1432
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1433
{
1434
    int fd = (long)t->priv;
1435

    
1436
    close(fd);
1437
}
1438

    
1439
static int rtc_start_timer(struct qemu_alarm_timer *t)
1440
{
1441
    int rtc_fd;
1442
    unsigned long current_rtc_freq = 0;
1443

    
1444
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1445
    if (rtc_fd < 0)
1446
        return -1;
1447
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1448
    if (current_rtc_freq != RTC_FREQ &&
1449
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1450
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1451
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1452
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1453
        goto fail;
1454
    }
1455
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1456
    fail:
1457
        close(rtc_fd);
1458
        return -1;
1459
    }
1460

    
1461
    enable_sigio_timer(rtc_fd);
1462

    
1463
    t->priv = (void *)(long)rtc_fd;
1464

    
1465
    return 0;
1466
}
1467

    
1468
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1469
{
1470
    int rtc_fd = (long)t->priv;
1471

    
1472
    close(rtc_fd);
1473
}
1474

    
1475
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1476
{
1477
    struct sigevent ev;
1478
    timer_t host_timer;
1479
    struct sigaction act;
1480

    
1481
    sigfillset(&act.sa_mask);
1482
    act.sa_flags = 0;
1483
    act.sa_handler = host_alarm_handler;
1484

    
1485
    sigaction(SIGALRM, &act, NULL);
1486

    
1487
    ev.sigev_value.sival_int = 0;
1488
    ev.sigev_notify = SIGEV_SIGNAL;
1489
    ev.sigev_signo = SIGALRM;
1490

    
1491
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1492
        perror("timer_create");
1493

    
1494
        /* disable dynticks */
1495
        fprintf(stderr, "Dynamic Ticks disabled\n");
1496

    
1497
        return -1;
1498
    }
1499

    
1500
    t->priv = (void *)host_timer;
1501

    
1502
    return 0;
1503
}
1504

    
1505
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1506
{
1507
    timer_t host_timer = (timer_t)t->priv;
1508

    
1509
    timer_delete(host_timer);
1510
}
1511

    
1512
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1513
{
1514
    timer_t host_timer = (timer_t)t->priv;
1515
    struct itimerspec timeout;
1516
    int64_t nearest_delta_us = INT64_MAX;
1517
    int64_t current_us;
1518

    
1519
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1520
                !active_timers[QEMU_TIMER_VIRTUAL])
1521
        return;
1522

    
1523
    nearest_delta_us = qemu_next_deadline_dyntick();
1524

    
1525
    /* check whether a timer is already running */
1526
    if (timer_gettime(host_timer, &timeout)) {
1527
        perror("gettime");
1528
        fprintf(stderr, "Internal timer error: aborting\n");
1529
        exit(1);
1530
    }
1531
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1532
    if (current_us && current_us <= nearest_delta_us)
1533
        return;
1534

    
1535
    timeout.it_interval.tv_sec = 0;
1536
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1537
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1538
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1539
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1540
        perror("settime");
1541
        fprintf(stderr, "Internal timer error: aborting\n");
1542
        exit(1);
1543
    }
1544
}
1545

    
1546
#endif /* defined(__linux__) */
1547

    
1548
static int unix_start_timer(struct qemu_alarm_timer *t)
1549
{
1550
    struct sigaction act;
1551
    struct itimerval itv;
1552
    int err;
1553

    
1554
    /* timer signal */
1555
    sigfillset(&act.sa_mask);
1556
    act.sa_flags = 0;
1557
    act.sa_handler = host_alarm_handler;
1558

    
1559
    sigaction(SIGALRM, &act, NULL);
1560

    
1561
    itv.it_interval.tv_sec = 0;
1562
    /* for i386 kernel 2.6 to get 1 ms */
1563
    itv.it_interval.tv_usec = 999;
1564
    itv.it_value.tv_sec = 0;
1565
    itv.it_value.tv_usec = 10 * 1000;
1566

    
1567
    err = setitimer(ITIMER_REAL, &itv, NULL);
1568
    if (err)
1569
        return -1;
1570

    
1571
    return 0;
1572
}
1573

    
1574
static void unix_stop_timer(struct qemu_alarm_timer *t)
1575
{
1576
    struct itimerval itv;
1577

    
1578
    memset(&itv, 0, sizeof(itv));
1579
    setitimer(ITIMER_REAL, &itv, NULL);
1580
}
1581

    
1582
#endif /* !defined(_WIN32) */
1583

    
1584
#ifdef _WIN32
1585

    
1586
static int win32_start_timer(struct qemu_alarm_timer *t)
1587
{
1588
    TIMECAPS tc;
1589
    struct qemu_alarm_win32 *data = t->priv;
1590
    UINT flags;
1591

    
1592
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1593
    if (!data->host_alarm) {
1594
        perror("Failed CreateEvent");
1595
        return -1;
1596
    }
1597

    
1598
    memset(&tc, 0, sizeof(tc));
1599
    timeGetDevCaps(&tc, sizeof(tc));
1600

    
1601
    if (data->period < tc.wPeriodMin)
1602
        data->period = tc.wPeriodMin;
1603

    
1604
    timeBeginPeriod(data->period);
1605

    
1606
    flags = TIME_CALLBACK_FUNCTION;
1607
    if (alarm_has_dynticks(t))
1608
        flags |= TIME_ONESHOT;
1609
    else
1610
        flags |= TIME_PERIODIC;
1611

    
1612
    data->timerId = timeSetEvent(1,         // interval (ms)
1613
                        data->period,       // resolution
1614
                        host_alarm_handler, // function
1615
                        (DWORD)t,           // parameter
1616
                        flags);
1617

    
1618
    if (!data->timerId) {
1619
        perror("Failed to initialize win32 alarm timer");
1620

    
1621
        timeEndPeriod(data->period);
1622
        CloseHandle(data->host_alarm);
1623
        return -1;
1624
    }
1625

    
1626
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1627

    
1628
    return 0;
1629
}
1630

    
1631
static void win32_stop_timer(struct qemu_alarm_timer *t)
1632
{
1633
    struct qemu_alarm_win32 *data = t->priv;
1634

    
1635
    timeKillEvent(data->timerId);
1636
    timeEndPeriod(data->period);
1637

    
1638
    CloseHandle(data->host_alarm);
1639
}
1640

    
1641
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1642
{
1643
    struct qemu_alarm_win32 *data = t->priv;
1644
    uint64_t nearest_delta_us;
1645

    
1646
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1647
                !active_timers[QEMU_TIMER_VIRTUAL])
1648
        return;
1649

    
1650
    nearest_delta_us = qemu_next_deadline_dyntick();
1651
    nearest_delta_us /= 1000;
1652

    
1653
    timeKillEvent(data->timerId);
1654

    
1655
    data->timerId = timeSetEvent(1,
1656
                        data->period,
1657
                        host_alarm_handler,
1658
                        (DWORD)t,
1659
                        TIME_ONESHOT | TIME_PERIODIC);
1660

    
1661
    if (!data->timerId) {
1662
        perror("Failed to re-arm win32 alarm timer");
1663

    
1664
        timeEndPeriod(data->period);
1665
        CloseHandle(data->host_alarm);
1666
        exit(1);
1667
    }
1668
}
1669

    
1670
#endif /* _WIN32 */
1671

    
1672
static void init_timer_alarm(void)
1673
{
1674
    struct qemu_alarm_timer *t = NULL;
1675
    int i, err = -1;
1676

    
1677
    for (i = 0; alarm_timers[i].name; i++) {
1678
        t = &alarm_timers[i];
1679

    
1680
        err = t->start(t);
1681
        if (!err)
1682
            break;
1683
    }
1684

    
1685
    if (err) {
1686
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1687
        fprintf(stderr, "Terminating\n");
1688
        exit(1);
1689
    }
1690

    
1691
    alarm_timer = t;
1692
}
1693

    
1694
static void quit_timers(void)
1695
{
1696
    alarm_timer->stop(alarm_timer);
1697
    alarm_timer = NULL;
1698
}
1699

    
1700
/***********************************************************/
1701
/* host time/date access */
1702
void qemu_get_timedate(struct tm *tm, int offset)
1703
{
1704
    time_t ti;
1705
    struct tm *ret;
1706

    
1707
    time(&ti);
1708
    ti += offset;
1709
    if (rtc_date_offset == -1) {
1710
        if (rtc_utc)
1711
            ret = gmtime(&ti);
1712
        else
1713
            ret = localtime(&ti);
1714
    } else {
1715
        ti -= rtc_date_offset;
1716
        ret = gmtime(&ti);
1717
    }
1718

    
1719
    memcpy(tm, ret, sizeof(struct tm));
1720
}
1721

    
1722
int qemu_timedate_diff(struct tm *tm)
1723
{
1724
    time_t seconds;
1725

    
1726
    if (rtc_date_offset == -1)
1727
        if (rtc_utc)
1728
            seconds = mktimegm(tm);
1729
        else
1730
            seconds = mktime(tm);
1731
    else
1732
        seconds = mktimegm(tm) + rtc_date_offset;
1733

    
1734
    return seconds - time(NULL);
1735
}
1736

    
1737
#ifdef _WIN32
1738
static void socket_cleanup(void)
1739
{
1740
    WSACleanup();
1741
}
1742

    
1743
static int socket_init(void)
1744
{
1745
    WSADATA Data;
1746
    int ret, err;
1747

    
1748
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1749
    if (ret != 0) {
1750
        err = WSAGetLastError();
1751
        fprintf(stderr, "WSAStartup: %d\n", err);
1752
        return -1;
1753
    }
1754
    atexit(socket_cleanup);
1755
    return 0;
1756
}
1757
#endif
1758

    
1759
const char *get_opt_name(char *buf, int buf_size, const char *p)
1760
{
1761
    char *q;
1762

    
1763
    q = buf;
1764
    while (*p != '\0' && *p != '=') {
1765
        if (q && (q - buf) < buf_size - 1)
1766
            *q++ = *p;
1767
        p++;
1768
    }
1769
    if (q)
1770
        *q = '\0';
1771

    
1772
    return p;
1773
}
1774

    
1775
const char *get_opt_value(char *buf, int buf_size, const char *p)
1776
{
1777
    char *q;
1778

    
1779
    q = buf;
1780
    while (*p != '\0') {
1781
        if (*p == ',') {
1782
            if (*(p + 1) != ',')
1783
                break;
1784
            p++;
1785
        }
1786
        if (q && (q - buf) < buf_size - 1)
1787
            *q++ = *p;
1788
        p++;
1789
    }
1790
    if (q)
1791
        *q = '\0';
1792

    
1793
    return p;
1794
}
1795

    
1796
int get_param_value(char *buf, int buf_size,
1797
                    const char *tag, const char *str)
1798
{
1799
    const char *p;
1800
    char option[128];
1801

    
1802
    p = str;
1803
    for(;;) {
1804
        p = get_opt_name(option, sizeof(option), p);
1805
        if (*p != '=')
1806
            break;
1807
        p++;
1808
        if (!strcmp(tag, option)) {
1809
            (void)get_opt_value(buf, buf_size, p);
1810
            return strlen(buf);
1811
        } else {
1812
            p = get_opt_value(NULL, 0, p);
1813
        }
1814
        if (*p != ',')
1815
            break;
1816
        p++;
1817
    }
1818
    return 0;
1819
}
1820

    
1821
int check_params(char *buf, int buf_size,
1822
                 const char * const *params, const char *str)
1823
{
1824
    const char *p;
1825
    int i;
1826

    
1827
    p = str;
1828
    for(;;) {
1829
        p = get_opt_name(buf, buf_size, p);
1830
        if (*p != '=')
1831
            return -1;
1832
        p++;
1833
        for(i = 0; params[i] != NULL; i++)
1834
            if (!strcmp(params[i], buf))
1835
                break;
1836
        if (params[i] == NULL)
1837
            return -1;
1838
        p = get_opt_value(NULL, 0, p);
1839
        if (*p != ',')
1840
            break;
1841
        p++;
1842
    }
1843
    return 0;
1844
}
1845

    
1846
/***********************************************************/
1847
/* Bluetooth support */
1848
static int nb_hcis;
1849
static int cur_hci;
1850
static struct HCIInfo *hci_table[MAX_NICS];
1851
#if 0
1852
static struct bt_vlan_s {
1853
    struct bt_scatternet_s net;
1854
    int id;
1855
    struct bt_vlan_s *next;
1856
} *first_bt_vlan;
1857

1858
/* find or alloc a new bluetooth "VLAN" */
1859
static struct bt_scatternet_s *qemu_find_bt_vlan(int id)
1860
{
1861
    struct bt_vlan_s **pvlan, *vlan;
1862
    for (vlan = first_bt_vlan; vlan != NULL; vlan = vlan->next) {
1863
        if (vlan->id == id)
1864
            return &vlan->net;
1865
    }
1866
    vlan = qemu_mallocz(sizeof(struct bt_vlan_s));
1867
    vlan->id = id;
1868
    pvlan = &first_bt_vlan;
1869
    while (*pvlan != NULL)
1870
        pvlan = &(*pvlan)->next;
1871
    *pvlan = vlan;
1872
    return &vlan->net;
1873
}
1874
#endif
1875

    
1876
static void null_hci_send(struct HCIInfo *hci, const uint8_t *data, int len)
1877
{
1878
}
1879

    
1880
static int null_hci_addr_set(struct HCIInfo *hci, const uint8_t *bd_addr)
1881
{
1882
    return -ENOTSUP;
1883
}
1884

    
1885
static struct HCIInfo null_hci = {
1886
    .cmd_send = null_hci_send,
1887
    .sco_send = null_hci_send,
1888
    .acl_send = null_hci_send,
1889
    .bdaddr_set = null_hci_addr_set,
1890
};
1891

    
1892
struct HCIInfo *qemu_next_hci(void)
1893
{
1894
    if (cur_hci == nb_hcis)
1895
        return &null_hci;
1896

    
1897
    return hci_table[cur_hci++];
1898
}
1899

    
1900
/***********************************************************/
1901
/* QEMU Block devices */
1902

    
1903
#define HD_ALIAS "index=%d,media=disk"
1904
#ifdef TARGET_PPC
1905
#define CDROM_ALIAS "index=1,media=cdrom"
1906
#else
1907
#define CDROM_ALIAS "index=2,media=cdrom"
1908
#endif
1909
#define FD_ALIAS "index=%d,if=floppy"
1910
#define PFLASH_ALIAS "if=pflash"
1911
#define MTD_ALIAS "if=mtd"
1912
#define SD_ALIAS "index=0,if=sd"
1913

    
1914
static int drive_add(const char *file, const char *fmt, ...)
1915
{
1916
    va_list ap;
1917

    
1918
    if (nb_drives_opt >= MAX_DRIVES) {
1919
        fprintf(stderr, "qemu: too many drives\n");
1920
        exit(1);
1921
    }
1922

    
1923
    drives_opt[nb_drives_opt].file = file;
1924
    va_start(ap, fmt);
1925
    vsnprintf(drives_opt[nb_drives_opt].opt,
1926
              sizeof(drives_opt[0].opt), fmt, ap);
1927
    va_end(ap);
1928

    
1929
    return nb_drives_opt++;
1930
}
1931

    
1932
int drive_get_index(BlockInterfaceType type, int bus, int unit)
1933
{
1934
    int index;
1935

    
1936
    /* seek interface, bus and unit */
1937

    
1938
    for (index = 0; index < nb_drives; index++)
1939
        if (drives_table[index].type == type &&
1940
            drives_table[index].bus == bus &&
1941
            drives_table[index].unit == unit)
1942
        return index;
1943

    
1944
    return -1;
1945
}
1946

    
1947
int drive_get_max_bus(BlockInterfaceType type)
1948
{
1949
    int max_bus;
1950
    int index;
1951

    
1952
    max_bus = -1;
1953
    for (index = 0; index < nb_drives; index++) {
1954
        if(drives_table[index].type == type &&
1955
           drives_table[index].bus > max_bus)
1956
            max_bus = drives_table[index].bus;
1957
    }
1958
    return max_bus;
1959
}
1960

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

    
1966
static int drive_init(struct drive_opt *arg, int snapshot,
1967
                      QEMUMachine *machine)
1968
{
1969
    char buf[128];
1970
    char file[1024];
1971
    char devname[128];
1972
    const char *mediastr = "";
1973
    BlockInterfaceType type;
1974
    enum { MEDIA_DISK, MEDIA_CDROM } media;
1975
    int bus_id, unit_id;
1976
    int cyls, heads, secs, translation;
1977
    BlockDriverState *bdrv;
1978
    BlockDriver *drv = NULL;
1979
    int max_devs;
1980
    int index;
1981
    int cache;
1982
    int bdrv_flags;
1983
    char *str = arg->opt;
1984
    static const char * const params[] = { "bus", "unit", "if", "index",
1985
                                           "cyls", "heads", "secs", "trans",
1986
                                           "media", "snapshot", "file",
1987
                                           "cache", "format", NULL };
1988

    
1989
    if (check_params(buf, sizeof(buf), params, str) < 0) {
1990
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
1991
                         buf, str);
1992
         return -1;
1993
    }
1994

    
1995
    file[0] = 0;
1996
    cyls = heads = secs = 0;
1997
    bus_id = 0;
1998
    unit_id = -1;
1999
    translation = BIOS_ATA_TRANSLATION_AUTO;
2000
    index = -1;
2001
    cache = 1;
2002

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

    
2014
    /* extract parameters */
2015

    
2016
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
2017
        bus_id = strtol(buf, NULL, 0);
2018
        if (bus_id < 0) {
2019
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
2020
            return -1;
2021
        }
2022
    }
2023

    
2024
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
2025
        unit_id = strtol(buf, NULL, 0);
2026
        if (unit_id < 0) {
2027
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
2028
            return -1;
2029
        }
2030
    }
2031

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

    
2058
    if (get_param_value(buf, sizeof(buf), "index", str)) {
2059
        index = strtol(buf, NULL, 0);
2060
        if (index < 0) {
2061
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
2062
            return -1;
2063
        }
2064
    }
2065

    
2066
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
2067
        cyls = strtol(buf, NULL, 0);
2068
    }
2069

    
2070
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
2071
        heads = strtol(buf, NULL, 0);
2072
    }
2073

    
2074
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
2075
        secs = strtol(buf, NULL, 0);
2076
    }
2077

    
2078
    if (cyls || heads || secs) {
2079
        if (cyls < 1 || cyls > 16383) {
2080
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
2081
            return -1;
2082
        }
2083
        if (heads < 1 || heads > 16) {
2084
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
2085
            return -1;
2086
        }
2087
        if (secs < 1 || secs > 63) {
2088
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
2089
            return -1;
2090
        }
2091
    }
2092

    
2093
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
2094
        if (!cyls) {
2095
            fprintf(stderr,
2096
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
2097
                    str);
2098
            return -1;
2099
        }
2100
        if (!strcmp(buf, "none"))
2101
            translation = BIOS_ATA_TRANSLATION_NONE;
2102
        else if (!strcmp(buf, "lba"))
2103
            translation = BIOS_ATA_TRANSLATION_LBA;
2104
        else if (!strcmp(buf, "auto"))
2105
            translation = BIOS_ATA_TRANSLATION_AUTO;
2106
        else {
2107
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
2108
            return -1;
2109
        }
2110
    }
2111

    
2112
    if (get_param_value(buf, sizeof(buf), "media", str)) {
2113
        if (!strcmp(buf, "disk")) {
2114
            media = MEDIA_DISK;
2115
        } else if (!strcmp(buf, "cdrom")) {
2116
            if (cyls || secs || heads) {
2117
                fprintf(stderr,
2118
                        "qemu: '%s' invalid physical CHS format\n", str);
2119
                return -1;
2120
            }
2121
            media = MEDIA_CDROM;
2122
        } else {
2123
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
2124
            return -1;
2125
        }
2126
    }
2127

    
2128
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
2129
        if (!strcmp(buf, "on"))
2130
            snapshot = 1;
2131
        else if (!strcmp(buf, "off"))
2132
            snapshot = 0;
2133
        else {
2134
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
2135
            return -1;
2136
        }
2137
    }
2138

    
2139
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
2140
        if (!strcmp(buf, "off") || !strcmp(buf, "none"))
2141
            cache = 0;
2142
        else if (!strcmp(buf, "writethrough"))
2143
            cache = 1;
2144
        else if (!strcmp(buf, "writeback"))
2145
            cache = 2;
2146
        else {
2147
           fprintf(stderr, "qemu: invalid cache option\n");
2148
           return -1;
2149
        }
2150
    }
2151

    
2152
    if (get_param_value(buf, sizeof(buf), "format", str)) {
2153
       if (strcmp(buf, "?") == 0) {
2154
            fprintf(stderr, "qemu: Supported formats:");
2155
            bdrv_iterate_format(bdrv_format_print, NULL);
2156
            fprintf(stderr, "\n");
2157
            return -1;
2158
        }
2159
        drv = bdrv_find_format(buf);
2160
        if (!drv) {
2161
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
2162
            return -1;
2163
        }
2164
    }
2165

    
2166
    if (arg->file == NULL)
2167
        get_param_value(file, sizeof(file), "file", str);
2168
    else
2169
        pstrcpy(file, sizeof(file), arg->file);
2170

    
2171
    /* compute bus and unit according index */
2172

    
2173
    if (index != -1) {
2174
        if (bus_id != 0 || unit_id != -1) {
2175
            fprintf(stderr,
2176
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
2177
            return -1;
2178
        }
2179
        if (max_devs == 0)
2180
        {
2181
            unit_id = index;
2182
            bus_id = 0;
2183
        } else {
2184
            unit_id = index % max_devs;
2185
            bus_id = index / max_devs;
2186
        }
2187
    }
2188

    
2189
    /* if user doesn't specify a unit_id,
2190
     * try to find the first free
2191
     */
2192

    
2193
    if (unit_id == -1) {
2194
       unit_id = 0;
2195
       while (drive_get_index(type, bus_id, unit_id) != -1) {
2196
           unit_id++;
2197
           if (max_devs && unit_id >= max_devs) {
2198
               unit_id -= max_devs;
2199
               bus_id++;
2200
           }
2201
       }
2202
    }
2203

    
2204
    /* check unit id */
2205

    
2206
    if (max_devs && unit_id >= max_devs) {
2207
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
2208
                        str, unit_id, max_devs - 1);
2209
        return -1;
2210
    }
2211

    
2212
    /*
2213
     * ignore multiple definitions
2214
     */
2215

    
2216
    if (drive_get_index(type, bus_id, unit_id) != -1)
2217
        return 0;
2218

    
2219
    /* init */
2220

    
2221
    if (type == IF_IDE || type == IF_SCSI)
2222
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
2223
    if (max_devs)
2224
        snprintf(buf, sizeof(buf), "%s%i%s%i",
2225
                 devname, bus_id, mediastr, unit_id);
2226
    else
2227
        snprintf(buf, sizeof(buf), "%s%s%i",
2228
                 devname, mediastr, unit_id);
2229
    bdrv = bdrv_new(buf);
2230
    drives_table[nb_drives].bdrv = bdrv;
2231
    drives_table[nb_drives].type = type;
2232
    drives_table[nb_drives].bus = bus_id;
2233
    drives_table[nb_drives].unit = unit_id;
2234
    nb_drives++;
2235

    
2236
    switch(type) {
2237
    case IF_IDE:
2238
    case IF_SCSI:
2239
        switch(media) {
2240
        case MEDIA_DISK:
2241
            if (cyls != 0) {
2242
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
2243
                bdrv_set_translation_hint(bdrv, translation);
2244
            }
2245
            break;
2246
        case MEDIA_CDROM:
2247
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
2248
            break;
2249
        }
2250
        break;
2251
    case IF_SD:
2252
        /* FIXME: This isn't really a floppy, but it's a reasonable
2253
           approximation.  */
2254
    case IF_FLOPPY:
2255
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
2256
        break;
2257
    case IF_PFLASH:
2258
    case IF_MTD:
2259
        break;
2260
    }
2261
    if (!file[0])
2262
        return 0;
2263
    bdrv_flags = 0;
2264
    if (snapshot) {
2265
        bdrv_flags |= BDRV_O_SNAPSHOT;
2266
        cache = 2; /* always use write-back with snapshot */
2267
    }
2268
    if (cache == 0) /* no caching */
2269
        bdrv_flags |= BDRV_O_NOCACHE;
2270
    else if (cache == 2) /* write-back */
2271
        bdrv_flags |= BDRV_O_CACHE_WB;
2272
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
2273
        fprintf(stderr, "qemu: could not open disk image %s\n",
2274
                        file);
2275
        return -1;
2276
    }
2277
    return 0;
2278
}
2279

    
2280
/***********************************************************/
2281
/* USB devices */
2282

    
2283
static USBPort *used_usb_ports;
2284
static USBPort *free_usb_ports;
2285

    
2286
/* ??? Maybe change this to register a hub to keep track of the topology.  */
2287
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
2288
                            usb_attachfn attach)
2289
{
2290
    port->opaque = opaque;
2291
    port->index = index;
2292
    port->attach = attach;
2293
    port->next = free_usb_ports;
2294
    free_usb_ports = port;
2295
}
2296

    
2297
int usb_device_add_dev(USBDevice *dev)
2298
{
2299
    USBPort *port;
2300

    
2301
    /* Find a USB port to add the device to.  */
2302
    port = free_usb_ports;
2303
    if (!port->next) {
2304
        USBDevice *hub;
2305

    
2306
        /* Create a new hub and chain it on.  */
2307
        free_usb_ports = NULL;
2308
        port->next = used_usb_ports;
2309
        used_usb_ports = port;
2310

    
2311
        hub = usb_hub_init(VM_USB_HUB_SIZE);
2312
        usb_attach(port, hub);
2313
        port = free_usb_ports;
2314
    }
2315

    
2316
    free_usb_ports = port->next;
2317
    port->next = used_usb_ports;
2318
    used_usb_ports = port;
2319
    usb_attach(port, dev);
2320
    return 0;
2321
}
2322

    
2323
static int usb_device_add(const char *devname)
2324
{
2325
    const char *p;
2326
    USBDevice *dev;
2327

    
2328
    if (!free_usb_ports)
2329
        return -1;
2330

    
2331
    if (strstart(devname, "host:", &p)) {
2332
        dev = usb_host_device_open(p);
2333
    } else if (!strcmp(devname, "mouse")) {
2334
        dev = usb_mouse_init();
2335
    } else if (!strcmp(devname, "tablet")) {
2336
        dev = usb_tablet_init();
2337
    } else if (!strcmp(devname, "keyboard")) {
2338
        dev = usb_keyboard_init();
2339
    } else if (strstart(devname, "disk:", &p)) {
2340
        dev = usb_msd_init(p);
2341
    } else if (!strcmp(devname, "wacom-tablet")) {
2342
        dev = usb_wacom_init();
2343
    } else if (strstart(devname, "serial:", &p)) {
2344
        dev = usb_serial_init(p);
2345
#ifdef CONFIG_BRLAPI
2346
    } else if (!strcmp(devname, "braille")) {
2347
        dev = usb_baum_init();
2348
#endif
2349
    } else if (strstart(devname, "net:", &p)) {
2350
        int nic = nb_nics;
2351

    
2352
        if (net_client_init("nic", p) < 0)
2353
            return -1;
2354
        nd_table[nic].model = "usb";
2355
        dev = usb_net_init(&nd_table[nic]);
2356
    } else {
2357
        return -1;
2358
    }
2359
    if (!dev)
2360
        return -1;
2361

    
2362
    return usb_device_add_dev(dev);
2363
}
2364

    
2365
int usb_device_del_addr(int bus_num, int addr)
2366
{
2367
    USBPort *port;
2368
    USBPort **lastp;
2369
    USBDevice *dev;
2370

    
2371
    if (!used_usb_ports)
2372
        return -1;
2373

    
2374
    if (bus_num != 0)
2375
        return -1;
2376

    
2377
    lastp = &used_usb_ports;
2378
    port = used_usb_ports;
2379
    while (port && port->dev->addr != addr) {
2380
        lastp = &port->next;
2381
        port = port->next;
2382
    }
2383

    
2384
    if (!port)
2385
        return -1;
2386

    
2387
    dev = port->dev;
2388
    *lastp = port->next;
2389
    usb_attach(port, NULL);
2390
    dev->handle_destroy(dev);
2391
    port->next = free_usb_ports;
2392
    free_usb_ports = port;
2393
    return 0;
2394
}
2395

    
2396
static int usb_device_del(const char *devname)
2397
{
2398
    int bus_num, addr;
2399
    const char *p;
2400

    
2401
    if (strstart(devname, "host:", &p))
2402
        return usb_host_device_close(p);
2403

    
2404
    if (!used_usb_ports)
2405
        return -1;
2406

    
2407
    p = strchr(devname, '.');
2408
    if (!p)
2409
        return -1;
2410
    bus_num = strtoul(devname, NULL, 0);
2411
    addr = strtoul(p + 1, NULL, 0);
2412

    
2413
    return usb_device_del_addr(bus_num, addr);
2414
}
2415

    
2416
void do_usb_add(const char *devname)
2417
{
2418
    usb_device_add(devname);
2419
}
2420

    
2421
void do_usb_del(const char *devname)
2422
{
2423
    usb_device_del(devname);
2424
}
2425

    
2426
void usb_info(void)
2427
{
2428
    USBDevice *dev;
2429
    USBPort *port;
2430
    const char *speed_str;
2431

    
2432
    if (!usb_enabled) {
2433
        term_printf("USB support not enabled\n");
2434
        return;
2435
    }
2436

    
2437
    for (port = used_usb_ports; port; port = port->next) {
2438
        dev = port->dev;
2439
        if (!dev)
2440
            continue;
2441
        switch(dev->speed) {
2442
        case USB_SPEED_LOW:
2443
            speed_str = "1.5";
2444
            break;
2445
        case USB_SPEED_FULL:
2446
            speed_str = "12";
2447
            break;
2448
        case USB_SPEED_HIGH:
2449
            speed_str = "480";
2450
            break;
2451
        default:
2452
            speed_str = "?";
2453
            break;
2454
        }
2455
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
2456
                    0, dev->addr, speed_str, dev->devname);
2457
    }
2458
}
2459

    
2460
/***********************************************************/
2461
/* PCMCIA/Cardbus */
2462

    
2463
static struct pcmcia_socket_entry_s {
2464
    struct pcmcia_socket_s *socket;
2465
    struct pcmcia_socket_entry_s *next;
2466
} *pcmcia_sockets = 0;
2467

    
2468
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
2469
{
2470
    struct pcmcia_socket_entry_s *entry;
2471

    
2472
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
2473
    entry->socket = socket;
2474
    entry->next = pcmcia_sockets;
2475
    pcmcia_sockets = entry;
2476
}
2477

    
2478
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
2479
{
2480
    struct pcmcia_socket_entry_s *entry, **ptr;
2481

    
2482
    ptr = &pcmcia_sockets;
2483
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
2484
        if (entry->socket == socket) {
2485
            *ptr = entry->next;
2486
            qemu_free(entry);
2487
        }
2488
}
2489

    
2490
void pcmcia_info(void)
2491
{
2492
    struct pcmcia_socket_entry_s *iter;
2493
    if (!pcmcia_sockets)
2494
        term_printf("No PCMCIA sockets\n");
2495

    
2496
    for (iter = pcmcia_sockets; iter; iter = iter->next)
2497
        term_printf("%s: %s\n", iter->socket->slot_string,
2498
                    iter->socket->attached ? iter->socket->card_string :
2499
                    "Empty");
2500
}
2501

    
2502
/***********************************************************/
2503
/* dumb display */
2504

    
2505
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2506
{
2507
}
2508

    
2509
static void dumb_resize(DisplayState *ds, int w, int h)
2510
{
2511
}
2512

    
2513
static void dumb_refresh(DisplayState *ds)
2514
{
2515
#if defined(CONFIG_SDL)
2516
    vga_hw_update();
2517
#endif
2518
}
2519

    
2520
static void dumb_display_init(DisplayState *ds)
2521
{
2522
    ds->data = NULL;
2523
    ds->linesize = 0;
2524
    ds->depth = 0;
2525
    ds->dpy_update = dumb_update;
2526
    ds->dpy_resize = dumb_resize;
2527
    ds->dpy_refresh = dumb_refresh;
2528
    ds->gui_timer_interval = 500;
2529
    ds->idle = 1;
2530
}
2531

    
2532
/***********************************************************/
2533
/* I/O handling */
2534

    
2535
#define MAX_IO_HANDLERS 64
2536

    
2537
typedef struct IOHandlerRecord {
2538
    int fd;
2539
    IOCanRWHandler *fd_read_poll;
2540
    IOHandler *fd_read;
2541
    IOHandler *fd_write;
2542
    int deleted;
2543
    void *opaque;
2544
    /* temporary data */
2545
    struct pollfd *ufd;
2546
    struct IOHandlerRecord *next;
2547
} IOHandlerRecord;
2548

    
2549
static IOHandlerRecord *first_io_handler;
2550

    
2551
/* XXX: fd_read_poll should be suppressed, but an API change is
2552
   necessary in the character devices to suppress fd_can_read(). */
2553
int qemu_set_fd_handler2(int fd,
2554
                         IOCanRWHandler *fd_read_poll,
2555
                         IOHandler *fd_read,
2556
                         IOHandler *fd_write,
2557
                         void *opaque)
2558
{
2559
    IOHandlerRecord **pioh, *ioh;
2560

    
2561
    if (!fd_read && !fd_write) {
2562
        pioh = &first_io_handler;
2563
        for(;;) {
2564
            ioh = *pioh;
2565
            if (ioh == NULL)
2566
                break;
2567
            if (ioh->fd == fd) {
2568
                ioh->deleted = 1;
2569
                break;
2570
            }
2571
            pioh = &ioh->next;
2572
        }
2573
    } else {
2574
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
2575
            if (ioh->fd == fd)
2576
                goto found;
2577
        }
2578
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
2579
        if (!ioh)
2580
            return -1;
2581
        ioh->next = first_io_handler;
2582
        first_io_handler = ioh;
2583
    found:
2584
        ioh->fd = fd;
2585
        ioh->fd_read_poll = fd_read_poll;
2586
        ioh->fd_read = fd_read;
2587
        ioh->fd_write = fd_write;
2588
        ioh->opaque = opaque;
2589
        ioh->deleted = 0;
2590
    }
2591
    return 0;
2592
}
2593

    
2594
int qemu_set_fd_handler(int fd,
2595
                        IOHandler *fd_read,
2596
                        IOHandler *fd_write,
2597
                        void *opaque)
2598
{
2599
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
2600
}
2601

    
2602
#ifdef _WIN32
2603
/***********************************************************/
2604
/* Polling handling */
2605

    
2606
typedef struct PollingEntry {
2607
    PollingFunc *func;
2608
    void *opaque;
2609
    struct PollingEntry *next;
2610
} PollingEntry;
2611

    
2612
static PollingEntry *first_polling_entry;
2613

    
2614
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
2615
{
2616
    PollingEntry **ppe, *pe;
2617
    pe = qemu_mallocz(sizeof(PollingEntry));
2618
    if (!pe)
2619
        return -1;
2620
    pe->func = func;
2621
    pe->opaque = opaque;
2622
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
2623
    *ppe = pe;
2624
    return 0;
2625
}
2626

    
2627
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
2628
{
2629
    PollingEntry **ppe, *pe;
2630
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
2631
        pe = *ppe;
2632
        if (pe->func == func && pe->opaque == opaque) {
2633
            *ppe = pe->next;
2634
            qemu_free(pe);
2635
            break;
2636
        }
2637
    }
2638
}
2639

    
2640
/***********************************************************/
2641
/* Wait objects support */
2642
typedef struct WaitObjects {
2643
    int num;
2644
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
2645
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
2646
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
2647
} WaitObjects;
2648

    
2649
static WaitObjects wait_objects = {0};
2650

    
2651
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2652
{
2653
    WaitObjects *w = &wait_objects;
2654

    
2655
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
2656
        return -1;
2657
    w->events[w->num] = handle;
2658
    w->func[w->num] = func;
2659
    w->opaque[w->num] = opaque;
2660
    w->num++;
2661
    return 0;
2662
}
2663

    
2664
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
2665
{
2666
    int i, found;
2667
    WaitObjects *w = &wait_objects;
2668

    
2669
    found = 0;
2670
    for (i = 0; i < w->num; i++) {
2671
        if (w->events[i] == handle)
2672
            found = 1;
2673
        if (found) {
2674
            w->events[i] = w->events[i + 1];
2675
            w->func[i] = w->func[i + 1];
2676
            w->opaque[i] = w->opaque[i + 1];
2677
        }
2678
    }
2679
    if (found)
2680
        w->num--;
2681
}
2682
#endif
2683

    
2684
#define SELF_ANNOUNCE_ROUNDS 5
2685
#define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
2686
//#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
2687
#define EXPERIMENTAL_MAGIC 0xf1f23f4f
2688

    
2689
static int announce_self_create(uint8_t *buf, 
2690
                                uint8_t *mac_addr)
2691
{
2692
    uint32_t magic = EXPERIMENTAL_MAGIC;
2693
    uint16_t proto = htons(ETH_P_EXPERIMENTAL);
2694

    
2695
    /* FIXME: should we send a different packet (arp/rarp/ping)? */
2696

    
2697
    memset(buf, 0xff, 6);         /* h_dst */
2698
    memcpy(buf + 6, mac_addr, 6); /* h_src */
2699
    memcpy(buf + 12, &proto, 2);  /* h_proto */
2700
    memcpy(buf + 14, &magic, 4);  /* magic */
2701

    
2702
    return 18; /* len */
2703
}
2704

    
2705
void qemu_announce_self(void)
2706
{
2707
    int i, j, len;
2708
    VLANState *vlan;
2709
    VLANClientState *vc;
2710
    uint8_t buf[256];
2711

    
2712
    for (i = 0; i < nb_nics; i++) {
2713
        len = announce_self_create(buf, nd_table[i].macaddr);
2714
        vlan = nd_table[i].vlan;
2715
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2716
            for (j=0; j < SELF_ANNOUNCE_ROUNDS; j++)
2717
                vc->fd_read(vc->opaque, buf, len);
2718
        }
2719
    }
2720
}
2721

    
2722
/***********************************************************/
2723
/* savevm/loadvm support */
2724

    
2725
#define IO_BUF_SIZE 32768
2726

    
2727
struct QEMUFile {
2728
    QEMUFilePutBufferFunc *put_buffer;
2729
    QEMUFileGetBufferFunc *get_buffer;
2730
    QEMUFileCloseFunc *close;
2731
    QEMUFileRateLimit *rate_limit;
2732
    void *opaque;
2733
    int is_write;
2734

    
2735
    int64_t buf_offset; /* start of buffer when writing, end of buffer
2736
                           when reading */
2737
    int buf_index;
2738
    int buf_size; /* 0 when writing */
2739
    uint8_t buf[IO_BUF_SIZE];
2740

    
2741
    int has_error;
2742
};
2743

    
2744
typedef struct QEMUFileSocket
2745
{
2746
    int fd;
2747
    QEMUFile *file;
2748
} QEMUFileSocket;
2749

    
2750
static int socket_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2751
{
2752
    QEMUFileSocket *s = opaque;
2753
    ssize_t len;
2754

    
2755
    do {
2756
        len = recv(s->fd, buf, size, 0);
2757
    } while (len == -1 && socket_error() == EINTR);
2758

    
2759
    if (len == -1)
2760
        len = -socket_error();
2761

    
2762
    return len;
2763
}
2764

    
2765
static int socket_close(void *opaque)
2766
{
2767
    QEMUFileSocket *s = opaque;
2768
    qemu_free(s);
2769
    return 0;
2770
}
2771

    
2772
QEMUFile *qemu_fopen_socket(int fd)
2773
{
2774
    QEMUFileSocket *s = qemu_mallocz(sizeof(QEMUFileSocket));
2775

    
2776
    if (s == NULL)
2777
        return NULL;
2778

    
2779
    s->fd = fd;
2780
    s->file = qemu_fopen_ops(s, NULL, socket_get_buffer, socket_close, NULL);
2781
    return s->file;
2782
}
2783

    
2784
typedef struct QEMUFileStdio
2785
{
2786
    FILE *outfile;
2787
} QEMUFileStdio;
2788

    
2789
static int file_put_buffer(void *opaque, const uint8_t *buf,
2790
                            int64_t pos, int size)
2791
{
2792
    QEMUFileStdio *s = opaque;
2793
    fseek(s->outfile, pos, SEEK_SET);
2794
    fwrite(buf, 1, size, s->outfile);
2795
    return size;
2796
}
2797

    
2798
static int file_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2799
{
2800
    QEMUFileStdio *s = opaque;
2801
    fseek(s->outfile, pos, SEEK_SET);
2802
    return fread(buf, 1, size, s->outfile);
2803
}
2804

    
2805
static int file_close(void *opaque)
2806
{
2807
    QEMUFileStdio *s = opaque;
2808
    fclose(s->outfile);
2809
    qemu_free(s);
2810
    return 0;
2811
}
2812

    
2813
QEMUFile *qemu_fopen(const char *filename, const char *mode)
2814
{
2815
    QEMUFileStdio *s;
2816

    
2817
    s = qemu_mallocz(sizeof(QEMUFileStdio));
2818
    if (!s)
2819
        return NULL;
2820

    
2821
    s->outfile = fopen(filename, mode);
2822
    if (!s->outfile)
2823
        goto fail;
2824

    
2825
    if (!strcmp(mode, "wb"))
2826
        return qemu_fopen_ops(s, file_put_buffer, NULL, file_close, NULL);
2827
    else if (!strcmp(mode, "rb"))
2828
        return qemu_fopen_ops(s, NULL, file_get_buffer, file_close, NULL);
2829

    
2830
fail:
2831
    if (s->outfile)
2832
        fclose(s->outfile);
2833
    qemu_free(s);
2834
    return NULL;
2835
}
2836

    
2837
typedef struct QEMUFileBdrv
2838
{
2839
    BlockDriverState *bs;
2840
    int64_t base_offset;
2841
} QEMUFileBdrv;
2842

    
2843
static int bdrv_put_buffer(void *opaque, const uint8_t *buf,
2844
                           int64_t pos, int size)
2845
{
2846
    QEMUFileBdrv *s = opaque;
2847
    bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);
2848
    return size;
2849
}
2850

    
2851
static int bdrv_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)
2852
{
2853
    QEMUFileBdrv *s = opaque;
2854
    return bdrv_pread(s->bs, s->base_offset + pos, buf, size);
2855
}
2856

    
2857
static int bdrv_fclose(void *opaque)
2858
{
2859
    QEMUFileBdrv *s = opaque;
2860
    qemu_free(s);
2861
    return 0;
2862
}
2863

    
2864
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
2865
{
2866
    QEMUFileBdrv *s;
2867

    
2868
    s = qemu_mallocz(sizeof(QEMUFileBdrv));
2869
    if (!s)
2870
        return NULL;
2871

    
2872
    s->bs = bs;
2873
    s->base_offset = offset;
2874

    
2875
    if (is_writable)
2876
        return qemu_fopen_ops(s, bdrv_put_buffer, NULL, bdrv_fclose, NULL);
2877

    
2878
    return qemu_fopen_ops(s, NULL, bdrv_get_buffer, bdrv_fclose, NULL);
2879
}
2880

    
2881
QEMUFile *qemu_fopen_ops(void *opaque, QEMUFilePutBufferFunc *put_buffer,
2882
                         QEMUFileGetBufferFunc *get_buffer,
2883
                         QEMUFileCloseFunc *close,
2884
                         QEMUFileRateLimit *rate_limit)
2885
{
2886
    QEMUFile *f;
2887

    
2888
    f = qemu_mallocz(sizeof(QEMUFile));
2889
    if (!f)
2890
        return NULL;
2891

    
2892
    f->opaque = opaque;
2893
    f->put_buffer = put_buffer;
2894
    f->get_buffer = get_buffer;
2895
    f->close = close;
2896
    f->rate_limit = rate_limit;
2897
    f->is_write = 0;
2898

    
2899
    return f;
2900
}
2901

    
2902
int qemu_file_has_error(QEMUFile *f)
2903
{
2904
    return f->has_error;
2905
}
2906

    
2907
void qemu_fflush(QEMUFile *f)
2908
{
2909
    if (!f->put_buffer)
2910
        return;
2911

    
2912
    if (f->is_write && f->buf_index > 0) {
2913
        int len;
2914

    
2915
        len = f->put_buffer(f->opaque, f->buf, f->buf_offset, f->buf_index);
2916
        if (len > 0)
2917
            f->buf_offset += f->buf_index;
2918
        else
2919
            f->has_error = 1;
2920
        f->buf_index = 0;
2921
    }
2922
}
2923

    
2924
static void qemu_fill_buffer(QEMUFile *f)
2925
{
2926
    int len;
2927

    
2928
    if (!f->get_buffer)
2929
        return;
2930

    
2931
    if (f->is_write)
2932
        abort();
2933

    
2934
    len = f->get_buffer(f->opaque, f->buf, f->buf_offset, IO_BUF_SIZE);
2935
    if (len > 0) {
2936
        f->buf_index = 0;
2937
        f->buf_size = len;
2938
        f->buf_offset += len;
2939
    } else if (len != -EAGAIN)
2940
        f->has_error = 1;
2941
}
2942

    
2943
int qemu_fclose(QEMUFile *f)
2944
{
2945
    int ret = 0;
2946
    qemu_fflush(f);
2947
    if (f->close)
2948
        ret = f->close(f->opaque);
2949
    qemu_free(f);
2950
    return ret;
2951
}
2952

    
2953
void qemu_file_put_notify(QEMUFile *f)
2954
{
2955
    f->put_buffer(f->opaque, NULL, 0, 0);
2956
}
2957

    
2958
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
2959
{
2960
    int l;
2961

    
2962
    if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
2963
        fprintf(stderr,
2964
                "Attempted to write to buffer while read buffer is not empty\n");
2965
        abort();
2966
    }
2967

    
2968
    while (!f->has_error && size > 0) {
2969
        l = IO_BUF_SIZE - f->buf_index;
2970
        if (l > size)
2971
            l = size;
2972
        memcpy(f->buf + f->buf_index, buf, l);
2973
        f->is_write = 1;
2974
        f->buf_index += l;
2975
        buf += l;
2976
        size -= l;
2977
        if (f->buf_index >= IO_BUF_SIZE)
2978
            qemu_fflush(f);
2979
    }
2980
}
2981

    
2982
void qemu_put_byte(QEMUFile *f, int v)
2983
{
2984
    if (!f->has_error && f->is_write == 0 && f->buf_index > 0) {
2985
        fprintf(stderr,
2986
                "Attempted to write to buffer while read buffer is not empty\n");
2987
        abort();
2988
    }
2989

    
2990
    f->buf[f->buf_index++] = v;
2991
    f->is_write = 1;
2992
    if (f->buf_index >= IO_BUF_SIZE)
2993
        qemu_fflush(f);
2994
}
2995

    
2996
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
2997
{
2998
    int size, l;
2999

    
3000
    if (f->is_write)
3001
        abort();
3002

    
3003
    size = size1;
3004
    while (size > 0) {
3005
        l = f->buf_size - f->buf_index;
3006
        if (l == 0) {
3007
            qemu_fill_buffer(f);
3008
            l = f->buf_size - f->buf_index;
3009
            if (l == 0)
3010
                break;
3011
        }
3012
        if (l > size)
3013
            l = size;
3014
        memcpy(buf, f->buf + f->buf_index, l);
3015
        f->buf_index += l;
3016
        buf += l;
3017
        size -= l;
3018
    }
3019
    return size1 - size;
3020
}
3021

    
3022
int qemu_get_byte(QEMUFile *f)
3023
{
3024
    if (f->is_write)
3025
        abort();
3026

    
3027
    if (f->buf_index >= f->buf_size) {
3028
        qemu_fill_buffer(f);
3029
        if (f->buf_index >= f->buf_size)
3030
            return 0;
3031
    }
3032
    return f->buf[f->buf_index++];
3033
}
3034

    
3035
int64_t qemu_ftell(QEMUFile *f)
3036
{
3037
    return f->buf_offset - f->buf_size + f->buf_index;
3038
}
3039

    
3040
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3041
{
3042
    if (whence == SEEK_SET) {
3043
        /* nothing to do */
3044
    } else if (whence == SEEK_CUR) {
3045
        pos += qemu_ftell(f);
3046
    } else {
3047
        /* SEEK_END not supported */
3048
        return -1;
3049
    }
3050
    if (f->put_buffer) {
3051
        qemu_fflush(f);
3052
        f->buf_offset = pos;
3053
    } else {
3054
        f->buf_offset = pos;
3055
        f->buf_index = 0;
3056
        f->buf_size = 0;
3057
    }
3058
    return pos;
3059
}
3060

    
3061
int qemu_file_rate_limit(QEMUFile *f)
3062
{
3063
    if (f->rate_limit)
3064
        return f->rate_limit(f->opaque);
3065

    
3066
    return 0;
3067
}
3068

    
3069
void qemu_put_be16(QEMUFile *f, unsigned int v)
3070
{
3071
    qemu_put_byte(f, v >> 8);
3072
    qemu_put_byte(f, v);
3073
}
3074

    
3075
void qemu_put_be32(QEMUFile *f, unsigned int v)
3076
{
3077
    qemu_put_byte(f, v >> 24);
3078
    qemu_put_byte(f, v >> 16);
3079
    qemu_put_byte(f, v >> 8);
3080
    qemu_put_byte(f, v);
3081
}
3082

    
3083
void qemu_put_be64(QEMUFile *f, uint64_t v)
3084
{
3085
    qemu_put_be32(f, v >> 32);
3086
    qemu_put_be32(f, v);
3087
}
3088

    
3089
unsigned int qemu_get_be16(QEMUFile *f)
3090
{
3091
    unsigned int v;
3092
    v = qemu_get_byte(f) << 8;
3093
    v |= qemu_get_byte(f);
3094
    return v;
3095
}
3096

    
3097
unsigned int qemu_get_be32(QEMUFile *f)
3098
{
3099
    unsigned int v;
3100
    v = qemu_get_byte(f) << 24;
3101
    v |= qemu_get_byte(f) << 16;
3102
    v |= qemu_get_byte(f) << 8;
3103
    v |= qemu_get_byte(f);
3104
    return v;
3105
}
3106

    
3107
uint64_t qemu_get_be64(QEMUFile *f)
3108
{
3109
    uint64_t v;
3110
    v = (uint64_t)qemu_get_be32(f) << 32;
3111
    v |= qemu_get_be32(f);
3112
    return v;
3113
}
3114

    
3115
typedef struct SaveStateEntry {
3116
    char idstr[256];
3117
    int instance_id;
3118
    int version_id;
3119
    int section_id;
3120
    SaveLiveStateHandler *save_live_state;
3121
    SaveStateHandler *save_state;
3122
    LoadStateHandler *load_state;
3123
    void *opaque;
3124
    struct SaveStateEntry *next;
3125
} SaveStateEntry;
3126

    
3127
static SaveStateEntry *first_se;
3128

    
3129
/* TODO: Individual devices generally have very little idea about the rest
3130
   of the system, so instance_id should be removed/replaced.
3131
   Meanwhile pass -1 as instance_id if you do not already have a clearly
3132
   distinguishing id for all instances of your device class. */
3133
int register_savevm_live(const char *idstr,
3134
                         int instance_id,
3135
                         int version_id,
3136
                         SaveLiveStateHandler *save_live_state,
3137
                         SaveStateHandler *save_state,
3138
                         LoadStateHandler *load_state,
3139
                         void *opaque)
3140
{
3141
    SaveStateEntry *se, **pse;
3142
    static int global_section_id;
3143

    
3144
    se = qemu_malloc(sizeof(SaveStateEntry));
3145
    if (!se)
3146
        return -1;
3147
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3148
    se->instance_id = (instance_id == -1) ? 0 : instance_id;
3149
    se->version_id = version_id;
3150
    se->section_id = global_section_id++;
3151
    se->save_live_state = save_live_state;
3152
    se->save_state = save_state;
3153
    se->load_state = load_state;
3154
    se->opaque = opaque;
3155
    se->next = NULL;
3156

    
3157
    /* add at the end of list */
3158
    pse = &first_se;
3159
    while (*pse != NULL) {
3160
        if (instance_id == -1
3161
                && strcmp(se->idstr, (*pse)->idstr) == 0
3162
                && se->instance_id <= (*pse)->instance_id)
3163
            se->instance_id = (*pse)->instance_id + 1;
3164
        pse = &(*pse)->next;
3165
    }
3166
    *pse = se;
3167
    return 0;
3168
}
3169

    
3170
int register_savevm(const char *idstr,
3171
                    int instance_id,
3172
                    int version_id,
3173
                    SaveStateHandler *save_state,
3174
                    LoadStateHandler *load_state,
3175
                    void *opaque)
3176
{
3177
    return register_savevm_live(idstr, instance_id, version_id,
3178
                                NULL, save_state, load_state, opaque);
3179
}
3180

    
3181
#define QEMU_VM_FILE_MAGIC           0x5145564d
3182
#define QEMU_VM_FILE_VERSION_COMPAT  0x00000002
3183
#define QEMU_VM_FILE_VERSION         0x00000003
3184

    
3185
#define QEMU_VM_EOF                  0x00
3186
#define QEMU_VM_SECTION_START        0x01
3187
#define QEMU_VM_SECTION_PART         0x02
3188
#define QEMU_VM_SECTION_END          0x03
3189
#define QEMU_VM_SECTION_FULL         0x04
3190

    
3191
int qemu_savevm_state_begin(QEMUFile *f)
3192
{
3193
    SaveStateEntry *se;
3194

    
3195
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3196
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3197

    
3198
    for (se = first_se; se != NULL; se = se->next) {
3199
        int len;
3200

    
3201
        if (se->save_live_state == NULL)
3202
            continue;
3203

    
3204
        /* Section type */
3205
        qemu_put_byte(f, QEMU_VM_SECTION_START);
3206
        qemu_put_be32(f, se->section_id);
3207

    
3208
        /* ID string */
3209
        len = strlen(se->idstr);
3210
        qemu_put_byte(f, len);
3211
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3212

    
3213
        qemu_put_be32(f, se->instance_id);
3214
        qemu_put_be32(f, se->version_id);
3215

    
3216
        se->save_live_state(f, QEMU_VM_SECTION_START, se->opaque);
3217
    }
3218

    
3219
    if (qemu_file_has_error(f))
3220
        return -EIO;
3221

    
3222
    return 0;
3223
}
3224

    
3225
int qemu_savevm_state_iterate(QEMUFile *f)
3226
{
3227
    SaveStateEntry *se;
3228
    int ret = 1;
3229

    
3230
    for (se = first_se; se != NULL; se = se->next) {
3231
        if (se->save_live_state == NULL)
3232
            continue;
3233

    
3234
        /* Section type */
3235
        qemu_put_byte(f, QEMU_VM_SECTION_PART);
3236
        qemu_put_be32(f, se->section_id);
3237

    
3238
        ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);
3239
    }
3240

    
3241
    if (ret)
3242
        return 1;
3243

    
3244
    if (qemu_file_has_error(f))
3245
        return -EIO;
3246

    
3247
    return 0;
3248
}
3249

    
3250
int qemu_savevm_state_complete(QEMUFile *f)
3251
{
3252
    SaveStateEntry *se;
3253

    
3254
    for (se = first_se; se != NULL; se = se->next) {
3255
        if (se->save_live_state == NULL)
3256
            continue;
3257

    
3258
        /* Section type */
3259
        qemu_put_byte(f, QEMU_VM_SECTION_END);
3260
        qemu_put_be32(f, se->section_id);
3261

    
3262
        se->save_live_state(f, QEMU_VM_SECTION_END, se->opaque);
3263
    }
3264

    
3265
    for(se = first_se; se != NULL; se = se->next) {
3266
        int len;
3267

    
3268
        if (se->save_state == NULL)
3269
            continue;
3270

    
3271
        /* Section type */
3272
        qemu_put_byte(f, QEMU_VM_SECTION_FULL);
3273
        qemu_put_be32(f, se->section_id);
3274

    
3275
        /* ID string */
3276
        len = strlen(se->idstr);
3277
        qemu_put_byte(f, len);
3278
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
3279

    
3280
        qemu_put_be32(f, se->instance_id);
3281
        qemu_put_be32(f, se->version_id);
3282

    
3283
        se->save_state(f, se->opaque);
3284
    }
3285

    
3286
    qemu_put_byte(f, QEMU_VM_EOF);
3287

    
3288
    if (qemu_file_has_error(f))
3289
        return -EIO;
3290

    
3291
    return 0;
3292
}
3293

    
3294
int qemu_savevm_state(QEMUFile *f)
3295
{
3296
    int saved_vm_running;
3297
    int ret;
3298

    
3299
    saved_vm_running = vm_running;
3300
    vm_stop(0);
3301

    
3302
    bdrv_flush_all();
3303

    
3304
    ret = qemu_savevm_state_begin(f);
3305
    if (ret < 0)
3306
        goto out;
3307

    
3308
    do {
3309
        ret = qemu_savevm_state_iterate(f);
3310
        if (ret < 0)
3311
            goto out;
3312
    } while (ret == 0);
3313

    
3314
    ret = qemu_savevm_state_complete(f);
3315

    
3316
out:
3317
    if (qemu_file_has_error(f))
3318
        ret = -EIO;
3319

    
3320
    if (!ret && saved_vm_running)
3321
        vm_start();
3322

    
3323
    return ret;
3324
}
3325

    
3326
static SaveStateEntry *find_se(const char *idstr, int instance_id)
3327
{
3328
    SaveStateEntry *se;
3329

    
3330
    for(se = first_se; se != NULL; se = se->next) {
3331
        if (!strcmp(se->idstr, idstr) &&
3332
            instance_id == se->instance_id)
3333
            return se;
3334
    }
3335
    return NULL;
3336
}
3337

    
3338
typedef struct LoadStateEntry {
3339
    SaveStateEntry *se;
3340
    int section_id;
3341
    int version_id;
3342
    struct LoadStateEntry *next;
3343
} LoadStateEntry;
3344

    
3345
static int qemu_loadvm_state_v2(QEMUFile *f)
3346
{
3347
    SaveStateEntry *se;
3348
    int len, ret, instance_id, record_len, version_id;
3349
    int64_t total_len, end_pos, cur_pos;
3350
    char idstr[256];
3351

    
3352
    total_len = qemu_get_be64(f);
3353
    end_pos = total_len + qemu_ftell(f);
3354
    for(;;) {
3355
        if (qemu_ftell(f) >= end_pos)
3356
            break;
3357
        len = qemu_get_byte(f);
3358
        qemu_get_buffer(f, (uint8_t *)idstr, len);
3359
        idstr[len] = '\0';
3360
        instance_id = qemu_get_be32(f);
3361
        version_id = qemu_get_be32(f);
3362
        record_len = qemu_get_be32(f);
3363
        cur_pos = qemu_ftell(f);
3364
        se = find_se(idstr, instance_id);
3365
        if (!se) {
3366
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3367
                    instance_id, idstr);
3368
        } else {
3369
            ret = se->load_state(f, se->opaque, version_id);
3370
            if (ret < 0) {
3371
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3372
                        instance_id, idstr);
3373
            }
3374
        }
3375
        /* always seek to exact end of record */
3376
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3377
    }
3378

    
3379
    if (qemu_file_has_error(f))
3380
        return -EIO;
3381

    
3382
    return 0;
3383
}
3384

    
3385
int qemu_loadvm_state(QEMUFile *f)
3386
{
3387
    LoadStateEntry *first_le = NULL;
3388
    uint8_t section_type;
3389
    unsigned int v;
3390
    int ret;
3391

    
3392
    v = qemu_get_be32(f);
3393
    if (v != QEMU_VM_FILE_MAGIC)
3394
        return -EINVAL;
3395

    
3396
    v = qemu_get_be32(f);
3397
    if (v == QEMU_VM_FILE_VERSION_COMPAT)
3398
        return qemu_loadvm_state_v2(f);
3399
    if (v != QEMU_VM_FILE_VERSION)
3400
        return -ENOTSUP;
3401

    
3402
    while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
3403
        uint32_t instance_id, version_id, section_id;
3404
        LoadStateEntry *le;
3405
        SaveStateEntry *se;
3406
        char idstr[257];
3407
        int len;
3408

    
3409
        switch (section_type) {
3410
        case QEMU_VM_SECTION_START:
3411
        case QEMU_VM_SECTION_FULL:
3412
            /* Read section start */
3413
            section_id = qemu_get_be32(f);
3414
            len = qemu_get_byte(f);
3415
            qemu_get_buffer(f, (uint8_t *)idstr, len);
3416
            idstr[len] = 0;
3417
            instance_id = qemu_get_be32(f);
3418
            version_id = qemu_get_be32(f);
3419

    
3420
            /* Find savevm section */
3421
            se = find_se(idstr, instance_id);
3422
            if (se == NULL) {
3423
                fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);
3424
                ret = -EINVAL;
3425
                goto out;
3426
            }
3427

    
3428
            /* Validate version */
3429
            if (version_id > se->version_id) {
3430
                fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",
3431
                        version_id, idstr, se->version_id);
3432
                ret = -EINVAL;
3433
                goto out;
3434
            }
3435

    
3436
            /* Add entry */
3437
            le = qemu_mallocz(sizeof(*le));
3438
            if (le == NULL) {
3439
                ret = -ENOMEM;
3440
                goto out;
3441
            }
3442

    
3443
            le->se = se;
3444
            le->section_id = section_id;
3445
            le->version_id = version_id;
3446
            le->next = first_le;
3447
            first_le = le;
3448

    
3449
            le->se->load_state(f, le->se->opaque, le->version_id);
3450
            break;
3451
        case QEMU_VM_SECTION_PART:
3452
        case QEMU_VM_SECTION_END:
3453
            section_id = qemu_get_be32(f);
3454

    
3455
            for (le = first_le; le && le->section_id != section_id; le = le->next);
3456
            if (le == NULL) {
3457
                fprintf(stderr, "Unknown savevm section %d\n", section_id);
3458
                ret = -EINVAL;
3459
                goto out;
3460
            }
3461

    
3462
            le->se->load_state(f, le->se->opaque, le->version_id);
3463
            break;
3464
        default:
3465
            fprintf(stderr, "Unknown savevm section type %d\n", section_type);
3466
            ret = -EINVAL;
3467
            goto out;
3468
        }
3469
    }
3470

    
3471
    ret = 0;
3472

    
3473
out:
3474
    while (first_le) {
3475
        LoadStateEntry *le = first_le;
3476
        first_le = first_le->next;
3477
        qemu_free(le);
3478
    }
3479

    
3480
    if (qemu_file_has_error(f))
3481
        ret = -EIO;
3482

    
3483
    return ret;
3484
}
3485

    
3486
/* device can contain snapshots */
3487
static int bdrv_can_snapshot(BlockDriverState *bs)
3488
{
3489
    return (bs &&
3490
            !bdrv_is_removable(bs) &&
3491
            !bdrv_is_read_only(bs));
3492
}
3493

    
3494
/* device must be snapshots in order to have a reliable snapshot */
3495
static int bdrv_has_snapshot(BlockDriverState *bs)
3496
{
3497
    return (bs &&
3498
            !bdrv_is_removable(bs) &&
3499
            !bdrv_is_read_only(bs));
3500
}
3501

    
3502
static BlockDriverState *get_bs_snapshots(void)
3503
{
3504
    BlockDriverState *bs;
3505
    int i;
3506

    
3507
    if (bs_snapshots)
3508
        return bs_snapshots;
3509
    for(i = 0; i <= nb_drives; i++) {
3510
        bs = drives_table[i].bdrv;
3511
        if (bdrv_can_snapshot(bs))
3512
            goto ok;
3513
    }
3514
    return NULL;
3515
 ok:
3516
    bs_snapshots = bs;
3517
    return bs;
3518
}
3519

    
3520
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
3521
                              const char *name)
3522
{
3523
    QEMUSnapshotInfo *sn_tab, *sn;
3524
    int nb_sns, i, ret;
3525

    
3526
    ret = -ENOENT;
3527
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3528
    if (nb_sns < 0)
3529
        return ret;
3530
    for(i = 0; i < nb_sns; i++) {
3531
        sn = &sn_tab[i];
3532
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
3533
            *sn_info = *sn;
3534
            ret = 0;
3535
            break;
3536
        }
3537
    }
3538
    qemu_free(sn_tab);
3539
    return ret;
3540
}
3541

    
3542
void do_savevm(const char *name)
3543
{
3544
    BlockDriverState *bs, *bs1;
3545
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
3546
    int must_delete, ret, i;
3547
    BlockDriverInfo bdi1, *bdi = &bdi1;
3548
    QEMUFile *f;
3549
    int saved_vm_running;
3550
#ifdef _WIN32
3551
    struct _timeb tb;
3552
#else
3553
    struct timeval tv;
3554
#endif
3555

    
3556
    bs = get_bs_snapshots();
3557
    if (!bs) {
3558
        term_printf("No block device can accept snapshots\n");
3559
        return;
3560
    }
3561

    
3562
    /* ??? Should this occur after vm_stop?  */
3563
    qemu_aio_flush();
3564

    
3565
    saved_vm_running = vm_running;
3566
    vm_stop(0);
3567

    
3568
    must_delete = 0;
3569
    if (name) {
3570
        ret = bdrv_snapshot_find(bs, old_sn, name);
3571
        if (ret >= 0) {
3572
            must_delete = 1;
3573
        }
3574
    }
3575
    memset(sn, 0, sizeof(*sn));
3576
    if (must_delete) {
3577
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
3578
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
3579
    } else {
3580
        if (name)
3581
            pstrcpy(sn->name, sizeof(sn->name), name);
3582
    }
3583

    
3584
    /* fill auxiliary fields */
3585
#ifdef _WIN32
3586
    _ftime(&tb);
3587
    sn->date_sec = tb.time;
3588
    sn->date_nsec = tb.millitm * 1000000;
3589
#else
3590
    gettimeofday(&tv, NULL);
3591
    sn->date_sec = tv.tv_sec;
3592
    sn->date_nsec = tv.tv_usec * 1000;
3593
#endif
3594
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
3595

    
3596
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3597
        term_printf("Device %s does not support VM state snapshots\n",
3598
                    bdrv_get_device_name(bs));
3599
        goto the_end;
3600
    }
3601

    
3602
    /* save the VM state */
3603
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
3604
    if (!f) {
3605
        term_printf("Could not open VM state file\n");
3606
        goto the_end;
3607
    }
3608
    ret = qemu_savevm_state(f);
3609
    sn->vm_state_size = qemu_ftell(f);
3610
    qemu_fclose(f);
3611
    if (ret < 0) {
3612
        term_printf("Error %d while writing VM\n", ret);
3613
        goto the_end;
3614
    }
3615

    
3616
    /* create the snapshots */
3617

    
3618
    for(i = 0; i < nb_drives; i++) {
3619
        bs1 = drives_table[i].bdrv;
3620
        if (bdrv_has_snapshot(bs1)) {
3621
            if (must_delete) {
3622
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
3623
                if (ret < 0) {
3624
                    term_printf("Error while deleting snapshot on '%s'\n",
3625
                                bdrv_get_device_name(bs1));
3626
                }
3627
            }
3628
            ret = bdrv_snapshot_create(bs1, sn);
3629
            if (ret < 0) {
3630
                term_printf("Error while creating snapshot on '%s'\n",
3631
                            bdrv_get_device_name(bs1));
3632
            }
3633
        }
3634
    }
3635

    
3636
 the_end:
3637
    if (saved_vm_running)
3638
        vm_start();
3639
}
3640

    
3641
void do_loadvm(const char *name)
3642
{
3643
    BlockDriverState *bs, *bs1;
3644
    BlockDriverInfo bdi1, *bdi = &bdi1;
3645
    QEMUFile *f;
3646
    int i, ret;
3647
    int saved_vm_running;
3648

    
3649
    bs = get_bs_snapshots();
3650
    if (!bs) {
3651
        term_printf("No block device supports snapshots\n");
3652
        return;
3653
    }
3654

    
3655
    /* Flush all IO requests so they don't interfere with the new state.  */
3656
    qemu_aio_flush();
3657

    
3658
    saved_vm_running = vm_running;
3659
    vm_stop(0);
3660

    
3661
    for(i = 0; i <= nb_drives; i++) {
3662
        bs1 = drives_table[i].bdrv;
3663
        if (bdrv_has_snapshot(bs1)) {
3664
            ret = bdrv_snapshot_goto(bs1, name);
3665
            if (ret < 0) {
3666
                if (bs != bs1)
3667
                    term_printf("Warning: ");
3668
                switch(ret) {
3669
                case -ENOTSUP:
3670
                    term_printf("Snapshots not supported on device '%s'\n",
3671
                                bdrv_get_device_name(bs1));
3672
                    break;
3673
                case -ENOENT:
3674
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
3675
                                name, bdrv_get_device_name(bs1));
3676
                    break;
3677
                default:
3678
                    term_printf("Error %d while activating snapshot on '%s'\n",
3679
                                ret, bdrv_get_device_name(bs1));
3680
                    break;
3681
                }
3682
                /* fatal on snapshot block device */
3683
                if (bs == bs1)
3684
                    goto the_end;
3685
            }
3686
        }
3687
    }
3688

    
3689
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
3690
        term_printf("Device %s does not support VM state snapshots\n",
3691
                    bdrv_get_device_name(bs));
3692
        return;
3693
    }
3694

    
3695
    /* restore the VM state */
3696
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
3697
    if (!f) {
3698
        term_printf("Could not open VM state file\n");
3699
        goto the_end;
3700
    }
3701
    ret = qemu_loadvm_state(f);
3702
    qemu_fclose(f);
3703
    if (ret < 0) {
3704
        term_printf("Error %d while loading VM state\n", ret);
3705
    }
3706
 the_end:
3707
    if (saved_vm_running)
3708
        vm_start();
3709
}
3710

    
3711
void do_delvm(const char *name)
3712
{
3713
    BlockDriverState *bs, *bs1;
3714
    int i, ret;
3715

    
3716
    bs = get_bs_snapshots();
3717
    if (!bs) {
3718
        term_printf("No block device supports snapshots\n");
3719
        return;
3720
    }
3721

    
3722
    for(i = 0; i <= nb_drives; i++) {
3723
        bs1 = drives_table[i].bdrv;
3724
        if (bdrv_has_snapshot(bs1)) {
3725
            ret = bdrv_snapshot_delete(bs1, name);
3726
            if (ret < 0) {
3727
                if (ret == -ENOTSUP)
3728
                    term_printf("Snapshots not supported on device '%s'\n",
3729
                                bdrv_get_device_name(bs1));
3730
                else
3731
                    term_printf("Error %d while deleting snapshot on '%s'\n",
3732
                                ret, bdrv_get_device_name(bs1));
3733
            }
3734
        }
3735
    }
3736
}
3737

    
3738
void do_info_snapshots(void)
3739
{
3740
    BlockDriverState *bs, *bs1;
3741
    QEMUSnapshotInfo *sn_tab, *sn;
3742
    int nb_sns, i;
3743
    char buf[256];
3744

    
3745
    bs = get_bs_snapshots();
3746
    if (!bs) {
3747
        term_printf("No available block device supports snapshots\n");
3748
        return;
3749
    }
3750
    term_printf("Snapshot devices:");
3751
    for(i = 0; i <= nb_drives; i++) {
3752
        bs1 = drives_table[i].bdrv;
3753
        if (bdrv_has_snapshot(bs1)) {
3754
            if (bs == bs1)
3755
                term_printf(" %s", bdrv_get_device_name(bs1));
3756
        }
3757
    }
3758
    term_printf("\n");
3759

    
3760
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
3761
    if (nb_sns < 0) {
3762
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
3763
        return;
3764
    }
3765
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
3766
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
3767
    for(i = 0; i < nb_sns; i++) {
3768
        sn = &sn_tab[i];
3769
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
3770
    }
3771
    qemu_free(sn_tab);
3772
}
3773

    
3774
/***********************************************************/
3775
/* ram save/restore */
3776

    
3777
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
3778
{
3779
    int v;
3780

    
3781
    v = qemu_get_byte(f);
3782
    switch(v) {
3783
    case 0:
3784
        if (qemu_get_buffer(f, buf, len) != len)
3785
            return -EIO;
3786
        break;
3787
    case 1:
3788
        v = qemu_get_byte(f);
3789
        memset(buf, v, len);
3790
        break;
3791
    default:
3792
        return -EINVAL;
3793
    }
3794

    
3795
    if (qemu_file_has_error(f))
3796
        return -EIO;
3797

    
3798
    return 0;
3799
}
3800

    
3801
static int ram_load_v1(QEMUFile *f, void *opaque)
3802
{
3803
    int ret;
3804
    ram_addr_t i;
3805

    
3806
    if (qemu_get_be32(f) != phys_ram_size)
3807
        return -EINVAL;
3808
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
3809
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
3810
        if (ret)
3811
            return ret;
3812
    }
3813
    return 0;
3814
}
3815

    
3816
#define BDRV_HASH_BLOCK_SIZE 1024
3817
#define IOBUF_SIZE 4096
3818
#define RAM_CBLOCK_MAGIC 0xfabe
3819

    
3820
typedef struct RamDecompressState {
3821
    z_stream zstream;
3822
    QEMUFile *f;
3823
    uint8_t buf[IOBUF_SIZE];
3824
} RamDecompressState;
3825

    
3826
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
3827
{
3828
    int ret;
3829
    memset(s, 0, sizeof(*s));
3830
    s->f = f;
3831
    ret = inflateInit(&s->zstream);
3832
    if (ret != Z_OK)
3833
        return -1;
3834
    return 0;
3835
}
3836

    
3837
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
3838
{
3839
    int ret, clen;
3840

    
3841
    s->zstream.avail_out = len;
3842
    s->zstream.next_out = buf;
3843
    while (s->zstream.avail_out > 0) {
3844
        if (s->zstream.avail_in == 0) {
3845
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
3846
                return -1;
3847
            clen = qemu_get_be16(s->f);
3848
            if (clen > IOBUF_SIZE)
3849
                return -1;
3850
            qemu_get_buffer(s->f, s->buf, clen);
3851
            s->zstream.avail_in = clen;
3852
            s->zstream.next_in = s->buf;
3853
        }
3854
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
3855
        if (ret != Z_OK && ret != Z_STREAM_END) {
3856
            return -1;
3857
        }
3858
    }
3859
    return 0;
3860
}
3861

    
3862
static void ram_decompress_close(RamDecompressState *s)
3863
{
3864
    inflateEnd(&s->zstream);
3865
}
3866

    
3867
#define RAM_SAVE_FLAG_FULL        0x01
3868
#define RAM_SAVE_FLAG_COMPRESS        0x02
3869
#define RAM_SAVE_FLAG_MEM_SIZE        0x04
3870
#define RAM_SAVE_FLAG_PAGE        0x08
3871
#define RAM_SAVE_FLAG_EOS        0x10
3872

    
3873
static int is_dup_page(uint8_t *page, uint8_t ch)
3874
{
3875
    uint32_t val = ch << 24 | ch << 16 | ch << 8 | ch;
3876
    uint32_t *array = (uint32_t *)page;
3877
    int i;
3878

    
3879
    for (i = 0; i < (TARGET_PAGE_SIZE / 4); i++) {
3880
        if (array[i] != val)
3881
            return 0;
3882
    }
3883

    
3884
    return 1;
3885
}
3886

    
3887
static int ram_save_block(QEMUFile *f)
3888
{
3889
    static ram_addr_t current_addr = 0;
3890
    ram_addr_t saved_addr = current_addr;
3891
    ram_addr_t addr = 0;
3892
    int found = 0;
3893

    
3894
    while (addr < phys_ram_size) {
3895
        if (cpu_physical_memory_get_dirty(current_addr, MIGRATION_DIRTY_FLAG)) {
3896
            uint8_t ch;
3897

    
3898
            cpu_physical_memory_reset_dirty(current_addr,
3899
                                            current_addr + TARGET_PAGE_SIZE,
3900
                                            MIGRATION_DIRTY_FLAG);
3901

    
3902
            ch = *(phys_ram_base + current_addr);
3903

    
3904
            if (is_dup_page(phys_ram_base + current_addr, ch)) {
3905
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_COMPRESS);
3906
                qemu_put_byte(f, ch);
3907
            } else {
3908
                qemu_put_be64(f, current_addr | RAM_SAVE_FLAG_PAGE);
3909
                qemu_put_buffer(f, phys_ram_base + current_addr, TARGET_PAGE_SIZE);
3910
            }
3911

    
3912
            found = 1;
3913
            break;
3914
        }
3915
        addr += TARGET_PAGE_SIZE;
3916
        current_addr = (saved_addr + addr) % phys_ram_size;
3917
    }
3918

    
3919
    return found;
3920
}
3921

    
3922
static ram_addr_t ram_save_threshold = 10;
3923

    
3924
static ram_addr_t ram_save_remaining(void)
3925
{
3926
    ram_addr_t addr;
3927
    ram_addr_t count = 0;
3928

    
3929
    for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3930
        if (cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3931
            count++;
3932
    }
3933

    
3934
    return count;
3935
}
3936

    
3937
static int ram_save_live(QEMUFile *f, int stage, void *opaque)
3938
{
3939
    ram_addr_t addr;
3940

    
3941
    if (stage == 1) {
3942
        /* Make sure all dirty bits are set */
3943
        for (addr = 0; addr < phys_ram_size; addr += TARGET_PAGE_SIZE) {
3944
            if (!cpu_physical_memory_get_dirty(addr, MIGRATION_DIRTY_FLAG))
3945
                cpu_physical_memory_set_dirty(addr);
3946
        }
3947
        
3948
        /* Enable dirty memory tracking */
3949
        cpu_physical_memory_set_dirty_tracking(1);
3950

    
3951
        qemu_put_be64(f, phys_ram_size | RAM_SAVE_FLAG_MEM_SIZE);
3952
    }
3953

    
3954
    while (!qemu_file_rate_limit(f)) {
3955
        int ret;
3956

    
3957
        ret = ram_save_block(f);
3958
        if (ret == 0) /* no more blocks */
3959
            break;
3960
    }
3961

    
3962
    /* try transferring iterative blocks of memory */
3963

    
3964
    if (stage == 3) {
3965
        cpu_physical_memory_set_dirty_tracking(0);
3966

    
3967
        /* flush all remaining blocks regardless of rate limiting */
3968
        while (ram_save_block(f) != 0);
3969
    }
3970

    
3971
    qemu_put_be64(f, RAM_SAVE_FLAG_EOS);
3972

    
3973
    return (stage == 2) && (ram_save_remaining() < ram_save_threshold);
3974
}
3975

    
3976
static int ram_load_dead(QEMUFile *f, void *opaque)
3977
{
3978
    RamDecompressState s1, *s = &s1;
3979
    uint8_t buf[10];
3980
    ram_addr_t i;
3981

    
3982
    if (ram_decompress_open(s, f) < 0)
3983
        return -EINVAL;
3984
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
3985
        if (ram_decompress_buf(s, buf, 1) < 0) {
3986
            fprintf(stderr, "Error while reading ram block header\n");
3987
            goto error;
3988
        }
3989
        if (buf[0] == 0) {
3990
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
3991
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
3992
                goto error;
3993
            }
3994
        } else {
3995
        error:
3996
            printf("Error block header\n");
3997
            return -EINVAL;
3998
        }
3999
    }
4000
    ram_decompress_close(s);
4001

    
4002
    return 0;
4003
}
4004

    
4005
static int ram_load(QEMUFile *f, void *opaque, int version_id)
4006
{
4007
    ram_addr_t addr;
4008
    int flags;
4009

    
4010
    if (version_id == 1)
4011
        return ram_load_v1(f, opaque);
4012

    
4013
    if (version_id == 2) {
4014
        if (qemu_get_be32(f) != phys_ram_size)
4015
            return -EINVAL;
4016
        return ram_load_dead(f, opaque);
4017
    }
4018

    
4019
    if (version_id != 3)
4020
        return -EINVAL;
4021

    
4022
    do {
4023
        addr = qemu_get_be64(f);
4024

    
4025
        flags = addr & ~TARGET_PAGE_MASK;
4026
        addr &= TARGET_PAGE_MASK;
4027

    
4028
        if (flags & RAM_SAVE_FLAG_MEM_SIZE) {
4029
            if (addr != phys_ram_size)
4030
                return -EINVAL;
4031
        }
4032

    
4033
        if (flags & RAM_SAVE_FLAG_FULL) {
4034
            if (ram_load_dead(f, opaque) < 0)
4035
                return -EINVAL;
4036
        }
4037
        
4038
        if (flags & RAM_SAVE_FLAG_COMPRESS) {
4039
            uint8_t ch = qemu_get_byte(f);
4040
            memset(phys_ram_base + addr, ch, TARGET_PAGE_SIZE);
4041
        } else if (flags & RAM_SAVE_FLAG_PAGE)
4042
            qemu_get_buffer(f, phys_ram_base + addr, TARGET_PAGE_SIZE);
4043
    } while (!(flags & RAM_SAVE_FLAG_EOS));
4044

    
4045
    return 0;
4046
}
4047

    
4048
void qemu_service_io(void)
4049
{
4050
    CPUState *env = cpu_single_env;
4051
    if (env) {
4052
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4053
#ifdef USE_KQEMU
4054
        if (env->kqemu_enabled) {
4055
            kqemu_cpu_interrupt(env);
4056
        }
4057
#endif
4058
    }
4059
}
4060

    
4061
/***********************************************************/
4062
/* bottom halves (can be seen as timers which expire ASAP) */
4063

    
4064
struct QEMUBH {
4065
    QEMUBHFunc *cb;
4066
    void *opaque;
4067
    int scheduled;
4068
    int idle;
4069
    int deleted;
4070
    QEMUBH *next;
4071
};
4072

    
4073
static QEMUBH *first_bh = NULL;
4074

    
4075
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
4076
{
4077
    QEMUBH *bh;
4078
    bh = qemu_mallocz(sizeof(QEMUBH));
4079
    if (!bh)
4080
        return NULL;
4081
    bh->cb = cb;
4082
    bh->opaque = opaque;
4083
    bh->next = first_bh;
4084
    first_bh = bh;
4085
    return bh;
4086
}
4087

    
4088
int qemu_bh_poll(void)
4089
{
4090
    QEMUBH *bh, **bhp;
4091
    int ret;
4092

    
4093
    ret = 0;
4094
    for (bh = first_bh; bh; bh = bh->next) {
4095
        if (!bh->deleted && bh->scheduled) {
4096
            bh->scheduled = 0;
4097
            if (!bh->idle)
4098
                ret = 1;
4099
            bh->idle = 0;
4100
            bh->cb(bh->opaque);
4101
        }
4102
    }
4103

    
4104
    /* remove deleted bhs */
4105
    bhp = &first_bh;
4106
    while (*bhp) {
4107
        bh = *bhp;
4108
        if (bh->deleted) {
4109
            *bhp = bh->next;
4110
            qemu_free(bh);
4111
        } else
4112
            bhp = &bh->next;
4113
    }
4114

    
4115
    return ret;
4116
}
4117

    
4118
void qemu_bh_schedule_idle(QEMUBH *bh)
4119
{
4120
    if (bh->scheduled)
4121
        return;
4122
    bh->scheduled = 1;
4123
    bh->idle = 1;
4124
}
4125

    
4126
void qemu_bh_schedule(QEMUBH *bh)
4127
{
4128
    CPUState *env = cpu_single_env;
4129
    if (bh->scheduled)
4130
        return;
4131
    bh->scheduled = 1;
4132
    bh->idle = 0;
4133
    /* stop the currently executing CPU to execute the BH ASAP */
4134
    if (env) {
4135
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
4136
    }
4137
}
4138

    
4139
void qemu_bh_cancel(QEMUBH *bh)
4140
{
4141
    bh->scheduled = 0;
4142
}
4143

    
4144
void qemu_bh_delete(QEMUBH *bh)
4145
{
4146
    bh->scheduled = 0;
4147
    bh->deleted = 1;
4148
}
4149

    
4150
static void qemu_bh_update_timeout(int *timeout)
4151
{
4152
    QEMUBH *bh;
4153

    
4154
    for (bh = first_bh; bh; bh = bh->next) {
4155
        if (!bh->deleted && bh->scheduled) {
4156
            if (bh->idle) {
4157
                /* idle bottom halves will be polled at least
4158
                 * every 10ms */
4159
                *timeout = MIN(10, *timeout);
4160
            } else {
4161
                /* non-idle bottom halves will be executed
4162
                 * immediately */
4163
                *timeout = 0;
4164
                break;
4165
            }
4166
        }
4167
    }
4168
}
4169

    
4170
/***********************************************************/
4171
/* machine registration */
4172

    
4173
static QEMUMachine *first_machine = NULL;
4174

    
4175
int qemu_register_machine(QEMUMachine *m)
4176
{
4177
    QEMUMachine **pm;
4178
    pm = &first_machine;
4179
    while (*pm != NULL)
4180
        pm = &(*pm)->next;
4181
    m->next = NULL;
4182
    *pm = m;
4183
    return 0;
4184
}
4185

    
4186
static QEMUMachine *find_machine(const char *name)
4187
{
4188
    QEMUMachine *m;
4189

    
4190
    for(m = first_machine; m != NULL; m = m->next) {
4191
        if (!strcmp(m->name, name))
4192
            return m;
4193
    }
4194
    return NULL;
4195
}
4196

    
4197
/***********************************************************/
4198
/* main execution loop */
4199

    
4200
static void gui_update(void *opaque)
4201
{
4202
    DisplayState *ds = opaque;
4203
    ds->dpy_refresh(ds);
4204
    qemu_mod_timer(ds->gui_timer,
4205
        (ds->gui_timer_interval ?
4206
            ds->gui_timer_interval :
4207
            GUI_REFRESH_INTERVAL)
4208
        + qemu_get_clock(rt_clock));
4209
}
4210

    
4211
struct vm_change_state_entry {
4212
    VMChangeStateHandler *cb;
4213
    void *opaque;
4214
    LIST_ENTRY (vm_change_state_entry) entries;
4215
};
4216

    
4217
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4218

    
4219
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4220
                                                     void *opaque)
4221
{
4222
    VMChangeStateEntry *e;
4223

    
4224
    e = qemu_mallocz(sizeof (*e));
4225
    if (!e)
4226
        return NULL;
4227

    
4228
    e->cb = cb;
4229
    e->opaque = opaque;
4230
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4231
    return e;
4232
}
4233

    
4234
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4235
{
4236
    LIST_REMOVE (e, entries);
4237
    qemu_free (e);
4238
}
4239

    
4240
static void vm_state_notify(int running)
4241
{
4242
    VMChangeStateEntry *e;
4243

    
4244
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4245
        e->cb(e->opaque, running);
4246
    }
4247
}
4248

    
4249
/* XXX: support several handlers */
4250
static VMStopHandler *vm_stop_cb;
4251
static void *vm_stop_opaque;
4252

    
4253
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4254
{
4255
    vm_stop_cb = cb;
4256
    vm_stop_opaque = opaque;
4257
    return 0;
4258
}
4259

    
4260
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4261
{
4262
    vm_stop_cb = NULL;
4263
}
4264

    
4265
void vm_start(void)
4266
{
4267
    if (!vm_running) {
4268
        cpu_enable_ticks();
4269
        vm_running = 1;
4270
        vm_state_notify(1);
4271
        qemu_rearm_alarm_timer(alarm_timer);
4272
    }
4273
}
4274

    
4275
void vm_stop(int reason)
4276
{
4277
    if (vm_running) {
4278
        cpu_disable_ticks();
4279
        vm_running = 0;
4280
        if (reason != 0) {
4281
            if (vm_stop_cb) {
4282
                vm_stop_cb(vm_stop_opaque, reason);
4283
            }
4284
        }
4285
        vm_state_notify(0);
4286
    }
4287
}
4288

    
4289
/* reset/shutdown handler */
4290

    
4291
typedef struct QEMUResetEntry {
4292
    QEMUResetHandler *func;
4293
    void *opaque;
4294
    struct QEMUResetEntry *next;
4295
} QEMUResetEntry;
4296

    
4297
static QEMUResetEntry *first_reset_entry;
4298
static int reset_requested;
4299
static int shutdown_requested;
4300
static int powerdown_requested;
4301

    
4302
int qemu_shutdown_requested(void)
4303
{
4304
    int r = shutdown_requested;
4305
    shutdown_requested = 0;
4306
    return r;
4307
}
4308

    
4309
int qemu_reset_requested(void)
4310
{
4311
    int r = reset_requested;
4312
    reset_requested = 0;
4313
    return r;
4314
}
4315

    
4316
int qemu_powerdown_requested(void)
4317
{
4318
    int r = powerdown_requested;
4319
    powerdown_requested = 0;
4320
    return r;
4321
}
4322

    
4323
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4324
{
4325
    QEMUResetEntry **pre, *re;
4326

    
4327
    pre = &first_reset_entry;
4328
    while (*pre != NULL)
4329
        pre = &(*pre)->next;
4330
    re = qemu_mallocz(sizeof(QEMUResetEntry));
4331
    re->func = func;
4332
    re->opaque = opaque;
4333
    re->next = NULL;
4334
    *pre = re;
4335
}
4336

    
4337
void qemu_system_reset(void)
4338
{
4339
    QEMUResetEntry *re;
4340

    
4341
    /* reset all devices */
4342
    for(re = first_reset_entry; re != NULL; re = re->next) {
4343
        re->func(re->opaque);
4344
    }
4345
}
4346

    
4347
void qemu_system_reset_request(void)
4348
{
4349
    if (no_reboot) {
4350
        shutdown_requested = 1;
4351
    } else {
4352
        reset_requested = 1;
4353
    }
4354
    if (cpu_single_env)
4355
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4356
}
4357

    
4358
void qemu_system_shutdown_request(void)
4359
{
4360
    shutdown_requested = 1;
4361
    if (cpu_single_env)
4362
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4363
}
4364

    
4365
void qemu_system_powerdown_request(void)
4366
{
4367
    powerdown_requested = 1;
4368
    if (cpu_single_env)
4369
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4370
}
4371

    
4372
#ifdef _WIN32
4373
void host_main_loop_wait(int *timeout)
4374
{
4375
    int ret, ret2, i;
4376
    PollingEntry *pe;
4377

    
4378

    
4379
    /* XXX: need to suppress polling by better using win32 events */
4380
    ret = 0;
4381
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4382
        ret |= pe->func(pe->opaque);
4383
    }
4384
    if (ret == 0) {
4385
        int err;
4386
        WaitObjects *w = &wait_objects;
4387

    
4388
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);
4389
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
4390
            if (w->func[ret - WAIT_OBJECT_0])
4391
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
4392

    
4393
            /* Check for additional signaled events */
4394
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
4395

    
4396
                /* Check if event is signaled */
4397
                ret2 = WaitForSingleObject(w->events[i], 0);
4398
                if(ret2 == WAIT_OBJECT_0) {
4399
                    if (w->func[i])
4400
                        w->func[i](w->opaque[i]);
4401
                } else if (ret2 == WAIT_TIMEOUT) {
4402
                } else {
4403
                    err = GetLastError();
4404
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
4405
                }
4406
            }
4407
        } else if (ret == WAIT_TIMEOUT) {
4408
        } else {
4409
            err = GetLastError();
4410
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
4411
        }
4412
    }
4413

    
4414
    *timeout = 0;
4415
}
4416
#else
4417
void host_main_loop_wait(int *timeout)
4418
{
4419
}
4420
#endif
4421

    
4422
void main_loop_wait(int timeout)
4423
{
4424
    IOHandlerRecord *ioh;
4425
    fd_set rfds, wfds, xfds;
4426
    int ret, nfds;
4427
    struct timeval tv;
4428

    
4429
    qemu_bh_update_timeout(&timeout);
4430

    
4431
    host_main_loop_wait(&timeout);
4432

    
4433
    /* poll any events */
4434
    /* XXX: separate device handlers from system ones */
4435
    nfds = -1;
4436
    FD_ZERO(&rfds);
4437
    FD_ZERO(&wfds);
4438
    FD_ZERO(&xfds);
4439
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4440
        if (ioh->deleted)
4441
            continue;
4442
        if (ioh->fd_read &&
4443
            (!ioh->fd_read_poll ||
4444
             ioh->fd_read_poll(ioh->opaque) != 0)) {
4445
            FD_SET(ioh->fd, &rfds);
4446
            if (ioh->fd > nfds)
4447
                nfds = ioh->fd;
4448
        }
4449
        if (ioh->fd_write) {
4450
            FD_SET(ioh->fd, &wfds);
4451
            if (ioh->fd > nfds)
4452
                nfds = ioh->fd;
4453
        }
4454
    }
4455

    
4456
    tv.tv_sec = timeout / 1000;
4457
    tv.tv_usec = (timeout % 1000) * 1000;
4458

    
4459
#if defined(CONFIG_SLIRP)
4460
    if (slirp_is_inited()) {
4461
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4462
    }
4463
#endif
4464
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4465
    if (ret > 0) {
4466
        IOHandlerRecord **pioh;
4467

    
4468
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4469
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
4470
                ioh->fd_read(ioh->opaque);
4471
            }
4472
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
4473
                ioh->fd_write(ioh->opaque);
4474
            }
4475
        }
4476

    
4477
        /* remove deleted IO handlers */
4478
        pioh = &first_io_handler;
4479
        while (*pioh) {
4480
            ioh = *pioh;
4481
            if (ioh->deleted) {
4482
                *pioh = ioh->next;
4483
                qemu_free(ioh);
4484
            } else
4485
                pioh = &ioh->next;
4486
        }
4487
    }
4488
#if defined(CONFIG_SLIRP)
4489
    if (slirp_is_inited()) {
4490
        if (ret < 0) {
4491
            FD_ZERO(&rfds);
4492
            FD_ZERO(&wfds);
4493
            FD_ZERO(&xfds);
4494
        }
4495
        slirp_select_poll(&rfds, &wfds, &xfds);
4496
    }
4497
#endif
4498

    
4499
    if (vm_running) {
4500
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
4501
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4502
                        qemu_get_clock(vm_clock));
4503
    }
4504

    
4505
    /* real time timers */
4506
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4507
                    qemu_get_clock(rt_clock));
4508

    
4509
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
4510
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
4511
        qemu_rearm_alarm_timer(alarm_timer);
4512
    }
4513

    
4514
    /* Check bottom-halves last in case any of the earlier events triggered
4515
       them.  */
4516
    qemu_bh_poll();
4517

    
4518
}
4519

    
4520
static int main_loop(void)
4521
{
4522
    int ret, timeout;
4523
#ifdef CONFIG_PROFILER
4524
    int64_t ti;
4525
#endif
4526
    CPUState *env;
4527

    
4528
    cur_cpu = first_cpu;
4529
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
4530
    for(;;) {
4531
        if (vm_running) {
4532

    
4533
            for(;;) {
4534
                /* get next cpu */
4535
                env = next_cpu;
4536
#ifdef CONFIG_PROFILER
4537
                ti = profile_getclock();
4538
#endif
4539
                if (use_icount) {
4540
                    int64_t count;
4541
                    int decr;
4542
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
4543
                    env->icount_decr.u16.low = 0;
4544
                    env->icount_extra = 0;
4545
                    count = qemu_next_deadline();
4546
                    count = (count + (1 << icount_time_shift) - 1)
4547
                            >> icount_time_shift;
4548
                    qemu_icount += count;
4549
                    decr = (count > 0xffff) ? 0xffff : count;
4550
                    count -= decr;
4551
                    env->icount_decr.u16.low = decr;
4552
                    env->icount_extra = count;
4553
                }
4554
                ret = cpu_exec(env);
4555
#ifdef CONFIG_PROFILER
4556
                qemu_time += profile_getclock() - ti;
4557
#endif
4558
                if (use_icount) {
4559
                    /* Fold pending instructions back into the
4560
                       instruction counter, and clear the interrupt flag.  */
4561
                    qemu_icount -= (env->icount_decr.u16.low
4562
                                    + env->icount_extra);
4563
                    env->icount_decr.u32 = 0;
4564
                    env->icount_extra = 0;
4565
                }
4566
                next_cpu = env->next_cpu ?: first_cpu;
4567
                if (event_pending && likely(ret != EXCP_DEBUG)) {
4568
                    ret = EXCP_INTERRUPT;
4569
                    event_pending = 0;
4570
                    break;
4571
                }
4572
                if (ret == EXCP_HLT) {
4573
                    /* Give the next CPU a chance to run.  */
4574
                    cur_cpu = env;
4575
                    continue;
4576
                }
4577
                if (ret != EXCP_HALTED)
4578
                    break;
4579
                /* all CPUs are halted ? */
4580
                if (env == cur_cpu)
4581
                    break;
4582
            }
4583
            cur_cpu = env;
4584

    
4585
            if (shutdown_requested) {
4586
                ret = EXCP_INTERRUPT;
4587
                if (no_shutdown) {
4588
                    vm_stop(0);
4589
                    no_shutdown = 0;
4590
                }
4591
                else
4592
                    break;
4593
            }
4594
            if (reset_requested) {
4595
                reset_requested = 0;
4596
                qemu_system_reset();
4597
                ret = EXCP_INTERRUPT;
4598
            }
4599
            if (powerdown_requested) {
4600
                powerdown_requested = 0;
4601
                qemu_system_powerdown();
4602
                ret = EXCP_INTERRUPT;
4603
            }
4604
            if (unlikely(ret == EXCP_DEBUG)) {
4605
                vm_stop(EXCP_DEBUG);
4606
            }
4607
            /* If all cpus are halted then wait until the next IRQ */
4608
            /* XXX: use timeout computed from timers */
4609
            if (ret == EXCP_HALTED) {
4610
                if (use_icount) {
4611
                    int64_t add;
4612
                    int64_t delta;
4613
                    /* Advance virtual time to the next event.  */
4614
                    if (use_icount == 1) {
4615
                        /* When not using an adaptive execution frequency
4616
                           we tend to get badly out of sync with real time,
4617
                           so just delay for a reasonable amount of time.  */
4618
                        delta = 0;
4619
                    } else {
4620
                        delta = cpu_get_icount() - cpu_get_clock();
4621
                    }
4622
                    if (delta > 0) {
4623
                        /* If virtual time is ahead of real time then just
4624
                           wait for IO.  */
4625
                        timeout = (delta / 1000000) + 1;
4626
                    } else {
4627
                        /* Wait for either IO to occur or the next
4628
                           timer event.  */
4629
                        add = qemu_next_deadline();
4630
                        /* We advance the timer before checking for IO.
4631
                           Limit the amount we advance so that early IO
4632
                           activity won't get the guest too far ahead.  */
4633
                        if (add > 10000000)
4634
                            add = 10000000;
4635
                        delta += add;
4636
                        add = (add + (1 << icount_time_shift) - 1)
4637
                              >> icount_time_shift;
4638
                        qemu_icount += add;
4639
                        timeout = delta / 1000000;
4640
                        if (timeout < 0)
4641
                            timeout = 0;
4642
                    }
4643
                } else {
4644
                    timeout = 5000;
4645
                }
4646
            } else {
4647
                timeout = 0;
4648
            }
4649
        } else {
4650
            if (shutdown_requested) {
4651
                ret = EXCP_INTERRUPT;
4652
                break;
4653
            }
4654
            timeout = 5000;
4655
        }
4656
#ifdef CONFIG_PROFILER
4657
        ti = profile_getclock();
4658
#endif
4659
        main_loop_wait(timeout);
4660
#ifdef CONFIG_PROFILER
4661
        dev_time += profile_getclock() - ti;
4662
#endif
4663
    }
4664
    cpu_disable_ticks();
4665
    return ret;
4666
}
4667

    
4668
static void help(int exitcode)
4669
{
4670
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
4671
           "usage: %s [options] [disk_image]\n"
4672
           "\n"
4673
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4674
           "\n"
4675
           "Standard options:\n"
4676
           "-M machine      select emulated machine (-M ? for list)\n"
4677
           "-cpu cpu        select CPU (-cpu ? for list)\n"
4678
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
4679
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
4680
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
4681
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4682
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
4683
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
4684
           "       [,cache=writethrough|writeback|none][,format=f]\n"
4685
           "                use 'file' as a drive image\n"
4686
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
4687
           "-sd file        use 'file' as SecureDigital card image\n"
4688
           "-pflash file    use 'file' as a parallel flash image\n"
4689
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
4690
           "-snapshot       write to temporary files instead of disk image files\n"
4691
#ifdef CONFIG_SDL
4692
           "-no-frame       open SDL window without a frame and window decorations\n"
4693
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
4694
           "-no-quit        disable SDL window close capability\n"
4695
#endif
4696
#ifdef TARGET_I386
4697
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
4698
#endif
4699
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
4700
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
4701
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
4702
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
4703
#ifndef _WIN32
4704
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
4705
#endif
4706
#ifdef HAS_AUDIO
4707
           "-audio-help     print list of audio drivers and their options\n"
4708
           "-soundhw c1,... enable audio support\n"
4709
           "                and only specified sound cards (comma separated list)\n"
4710
           "                use -soundhw ? to get the list of supported cards\n"
4711
           "                use -soundhw all to enable all of them\n"
4712
#endif
4713
           "-vga [std|cirrus|vmware]\n"
4714
           "                select video card type\n"
4715
           "-localtime      set the real time clock to local time [default=utc]\n"
4716
           "-full-screen    start in full screen\n"
4717
#ifdef TARGET_I386
4718
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
4719
#endif
4720
           "-usb            enable the USB driver (will be the default soon)\n"
4721
           "-usbdevice name add the host or guest USB device 'name'\n"
4722
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4723
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
4724
#endif
4725
           "-name string    set the name of the guest\n"
4726
           "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
4727
           "\n"
4728
           "Network options:\n"
4729
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4730
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
4731
#ifdef CONFIG_SLIRP
4732
           "-net user[,vlan=n][,hostname=host]\n"
4733
           "                connect the user mode network stack to VLAN 'n' and send\n"
4734
           "                hostname 'host' to DHCP clients\n"
4735
#endif
4736
#ifdef _WIN32
4737
           "-net tap[,vlan=n],ifname=name\n"
4738
           "                connect the host TAP network interface to VLAN 'n'\n"
4739
#else
4740
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
4741
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
4742
           "                network scripts 'file' (default=%s)\n"
4743
           "                and 'dfile' (default=%s);\n"
4744
           "                use '[down]script=no' to disable script execution;\n"
4745
           "                use 'fd=h' to connect to an already opened TAP interface\n"
4746
#endif
4747
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4748
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
4749
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4750
           "                connect the vlan 'n' to multicast maddr and port\n"
4751
#ifdef CONFIG_VDE
4752
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
4753
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
4754
           "                on host and listening for incoming connections on 'socketpath'.\n"
4755
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
4756
           "                ownership and permissions for communication port.\n"
4757
#endif
4758
           "-net none       use it alone to have zero network devices; if no -net option\n"
4759
           "                is provided, the default is '-net nic -net user'\n"
4760
           "\n"
4761
#ifdef CONFIG_SLIRP
4762
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
4763
           "-bootp file     advertise file in BOOTP replies\n"
4764
#ifndef _WIN32
4765
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
4766
#endif
4767
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4768
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
4769
#endif
4770
           "\n"
4771
           "Linux boot specific:\n"
4772
           "-kernel bzImage use 'bzImage' as kernel image\n"
4773
           "-append cmdline use 'cmdline' as kernel command line\n"
4774
           "-initrd file    use 'file' as initial ram disk\n"
4775
           "\n"
4776
           "Debug/Expert options:\n"
4777
           "-monitor dev    redirect the monitor to char device 'dev'\n"
4778
           "-serial dev     redirect the serial port to char device 'dev'\n"
4779
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
4780
           "-pidfile file   Write PID to 'file'\n"
4781
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
4782
           "-s              wait gdb connection to port\n"
4783
           "-p port         set gdb connection port [default=%s]\n"
4784
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
4785
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
4786
           "                translation (t=none or lba) (usually qemu can guess them)\n"
4787
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
4788
#ifdef USE_KQEMU
4789
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
4790
           "-no-kqemu       disable KQEMU kernel module usage\n"
4791
#endif
4792
#ifdef TARGET_I386
4793
           "-no-acpi        disable ACPI\n"
4794
#endif
4795
#ifdef CONFIG_CURSES
4796
           "-curses         use a curses/ncurses interface instead of SDL\n"
4797
#endif
4798
           "-no-reboot      exit instead of rebooting\n"
4799
           "-no-shutdown    stop before shutdown\n"
4800
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
4801
           "-vnc display    start a VNC server on display\n"
4802
#ifndef _WIN32
4803
           "-daemonize      daemonize QEMU after initializing\n"
4804
#endif
4805
           "-option-rom rom load a file, rom, into the option ROM space\n"
4806
#ifdef TARGET_SPARC
4807
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
4808
#endif
4809
           "-clock          force the use of the given methods for timer alarm.\n"
4810
           "                To see what timers are available use -clock ?\n"
4811
           "-startdate      select initial date of the clock\n"
4812
           "-icount [N|auto]\n"
4813
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
4814
           "\n"
4815
           "During emulation, the following keys are useful:\n"
4816
           "ctrl-alt-f      toggle full screen\n"
4817
           "ctrl-alt-n      switch to virtual console 'n'\n"
4818
           "ctrl-alt        toggle mouse and keyboard grab\n"
4819
           "\n"
4820
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
4821
           ,
4822
           "qemu",
4823
           DEFAULT_RAM_SIZE,
4824
#ifndef _WIN32
4825
           DEFAULT_NETWORK_SCRIPT,
4826
           DEFAULT_NETWORK_DOWN_SCRIPT,
4827
#endif
4828
           DEFAULT_GDBSTUB_PORT,
4829
           "/tmp/qemu.log");
4830
    exit(exitcode);
4831
}
4832

    
4833
#define HAS_ARG 0x0001
4834

    
4835
enum {
4836
    QEMU_OPTION_h,
4837

    
4838
    QEMU_OPTION_M,
4839
    QEMU_OPTION_cpu,
4840
    QEMU_OPTION_fda,
4841
    QEMU_OPTION_fdb,
4842
    QEMU_OPTION_hda,
4843
    QEMU_OPTION_hdb,
4844
    QEMU_OPTION_hdc,
4845
    QEMU_OPTION_hdd,
4846
    QEMU_OPTION_drive,
4847
    QEMU_OPTION_cdrom,
4848
    QEMU_OPTION_mtdblock,
4849
    QEMU_OPTION_sd,
4850
    QEMU_OPTION_pflash,
4851
    QEMU_OPTION_boot,
4852
    QEMU_OPTION_snapshot,
4853
#ifdef TARGET_I386
4854
    QEMU_OPTION_no_fd_bootchk,
4855
#endif
4856
    QEMU_OPTION_m,
4857
    QEMU_OPTION_nographic,
4858
    QEMU_OPTION_portrait,
4859
#ifdef HAS_AUDIO
4860
    QEMU_OPTION_audio_help,
4861
    QEMU_OPTION_soundhw,
4862
#endif
4863

    
4864
    QEMU_OPTION_net,
4865
    QEMU_OPTION_tftp,
4866
    QEMU_OPTION_bootp,
4867
    QEMU_OPTION_smb,
4868
    QEMU_OPTION_redir,
4869

    
4870
    QEMU_OPTION_kernel,
4871
    QEMU_OPTION_append,
4872
    QEMU_OPTION_initrd,
4873

    
4874
    QEMU_OPTION_S,
4875
    QEMU_OPTION_s,
4876
    QEMU_OPTION_p,
4877
    QEMU_OPTION_d,
4878
    QEMU_OPTION_hdachs,
4879
    QEMU_OPTION_L,
4880
    QEMU_OPTION_bios,
4881
    QEMU_OPTION_k,
4882
    QEMU_OPTION_localtime,
4883
    QEMU_OPTION_g,
4884
    QEMU_OPTION_vga,
4885
    QEMU_OPTION_echr,
4886
    QEMU_OPTION_monitor,
4887
    QEMU_OPTION_serial,
4888
    QEMU_OPTION_parallel,
4889
    QEMU_OPTION_loadvm,
4890
    QEMU_OPTION_full_screen,
4891
    QEMU_OPTION_no_frame,
4892
    QEMU_OPTION_alt_grab,
4893
    QEMU_OPTION_no_quit,
4894
    QEMU_OPTION_pidfile,
4895
    QEMU_OPTION_no_kqemu,
4896
    QEMU_OPTION_kernel_kqemu,
4897
    QEMU_OPTION_win2k_hack,
4898
    QEMU_OPTION_usb,
4899
    QEMU_OPTION_usbdevice,
4900
    QEMU_OPTION_smp,
4901
    QEMU_OPTION_vnc,
4902
    QEMU_OPTION_no_acpi,
4903
    QEMU_OPTION_curses,
4904
    QEMU_OPTION_no_reboot,
4905
    QEMU_OPTION_no_shutdown,
4906
    QEMU_OPTION_show_cursor,
4907
    QEMU_OPTION_daemonize,
4908
    QEMU_OPTION_option_rom,
4909
    QEMU_OPTION_semihosting,
4910
    QEMU_OPTION_name,
4911
    QEMU_OPTION_prom_env,
4912
    QEMU_OPTION_old_param,
4913
    QEMU_OPTION_clock,
4914
    QEMU_OPTION_startdate,
4915
    QEMU_OPTION_tb_size,
4916
    QEMU_OPTION_icount,
4917
    QEMU_OPTION_uuid,
4918
    QEMU_OPTION_incoming,
4919
};
4920

    
4921
typedef struct QEMUOption {
4922
    const char *name;
4923
    int flags;
4924
    int index;
4925
} QEMUOption;
4926

    
4927
static const QEMUOption qemu_options[] = {
4928
    { "h", 0, QEMU_OPTION_h },
4929
    { "help", 0, QEMU_OPTION_h },
4930

    
4931
    { "M", HAS_ARG, QEMU_OPTION_M },
4932
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
4933
    { "fda", HAS_ARG, QEMU_OPTION_fda },
4934
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4935
    { "hda", HAS_ARG, QEMU_OPTION_hda },
4936
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4937
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4938
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4939
    { "drive", HAS_ARG, QEMU_OPTION_drive },
4940
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4941
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
4942
    { "sd", HAS_ARG, QEMU_OPTION_sd },
4943
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
4944
    { "boot", HAS_ARG, QEMU_OPTION_boot },
4945
    { "snapshot", 0, QEMU_OPTION_snapshot },
4946
#ifdef TARGET_I386
4947
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
4948
#endif
4949
    { "m", HAS_ARG, QEMU_OPTION_m },
4950
    { "nographic", 0, QEMU_OPTION_nographic },
4951
    { "portrait", 0, QEMU_OPTION_portrait },
4952
    { "k", HAS_ARG, QEMU_OPTION_k },
4953
#ifdef HAS_AUDIO
4954
    { "audio-help", 0, QEMU_OPTION_audio_help },
4955
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4956
#endif
4957

    
4958
    { "net", HAS_ARG, QEMU_OPTION_net},
4959
#ifdef CONFIG_SLIRP
4960
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4961
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
4962
#ifndef _WIN32
4963
    { "smb", HAS_ARG, QEMU_OPTION_smb },
4964
#endif
4965
    { "redir", HAS_ARG, QEMU_OPTION_redir },
4966
#endif
4967

    
4968
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4969
    { "append", HAS_ARG, QEMU_OPTION_append },
4970
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4971

    
4972
    { "S", 0, QEMU_OPTION_S },
4973
    { "s", 0, QEMU_OPTION_s },
4974
    { "p", HAS_ARG, QEMU_OPTION_p },
4975
    { "d", HAS_ARG, QEMU_OPTION_d },
4976
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4977
    { "L", HAS_ARG, QEMU_OPTION_L },
4978
    { "bios", HAS_ARG, QEMU_OPTION_bios },
4979
#ifdef USE_KQEMU
4980
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4981
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4982
#endif
4983
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
4984
    { "g", 1, QEMU_OPTION_g },
4985
#endif
4986
    { "localtime", 0, QEMU_OPTION_localtime },
4987
    { "vga", HAS_ARG, QEMU_OPTION_vga },
4988
    { "echr", HAS_ARG, QEMU_OPTION_echr },
4989
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
4990
    { "serial", HAS_ARG, QEMU_OPTION_serial },
4991
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
4992
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4993
    { "full-screen", 0, QEMU_OPTION_full_screen },
4994
#ifdef CONFIG_SDL
4995
    { "no-frame", 0, QEMU_OPTION_no_frame },
4996
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
4997
    { "no-quit", 0, QEMU_OPTION_no_quit },
4998
#endif
4999
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5000
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5001
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5002
    { "smp", HAS_ARG, QEMU_OPTION_smp },
5003
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5004
#ifdef CONFIG_CURSES
5005
    { "curses", 0, QEMU_OPTION_curses },
5006
#endif
5007
    { "uuid", HAS_ARG, QEMU_OPTION_uuid },
5008

    
5009
    /* temporary options */
5010
    { "usb", 0, QEMU_OPTION_usb },
5011
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
5012
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
5013
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
5014
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
5015
    { "daemonize", 0, QEMU_OPTION_daemonize },
5016
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
5017
#if defined(TARGET_ARM) || defined(TARGET_M68K)
5018
    { "semihosting", 0, QEMU_OPTION_semihosting },
5019
#endif
5020
    { "name", HAS_ARG, QEMU_OPTION_name },
5021
#if defined(TARGET_SPARC)
5022
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
5023
#endif
5024
#if defined(TARGET_ARM)
5025
    { "old-param", 0, QEMU_OPTION_old_param },
5026
#endif
5027
    { "clock", HAS_ARG, QEMU_OPTION_clock },
5028
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
5029
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
5030
    { "icount", HAS_ARG, QEMU_OPTION_icount },
5031
    { "incoming", HAS_ARG, QEMU_OPTION_incoming },
5032
    { NULL },
5033
};
5034

    
5035
/* password input */
5036

    
5037
int qemu_key_check(BlockDriverState *bs, const char *name)
5038
{
5039
    char password[256];
5040
    int i;
5041

    
5042
    if (!bdrv_is_encrypted(bs))
5043
        return 0;
5044

    
5045
    term_printf("%s is encrypted.\n", name);
5046
    for(i = 0; i < 3; i++) {
5047
        monitor_readline("Password: ", 1, password, sizeof(password));
5048
        if (bdrv_set_key(bs, password) == 0)
5049
            return 0;
5050
        term_printf("invalid password\n");
5051
    }
5052
    return -EPERM;
5053
}
5054

    
5055
static BlockDriverState *get_bdrv(int index)
5056
{
5057
    if (index > nb_drives)
5058
        return NULL;
5059
    return drives_table[index].bdrv;
5060
}
5061

    
5062
static void read_passwords(void)
5063
{
5064
    BlockDriverState *bs;
5065
    int i;
5066

    
5067
    for(i = 0; i < 6; i++) {
5068
        bs = get_bdrv(i);
5069
        if (bs)
5070
            qemu_key_check(bs, bdrv_get_device_name(bs));
5071
    }
5072
}
5073

    
5074
#ifdef HAS_AUDIO
5075
struct soundhw soundhw[] = {
5076
#ifdef HAS_AUDIO_CHOICE
5077
#if defined(TARGET_I386) || defined(TARGET_MIPS)
5078
    {
5079
        "pcspk",
5080
        "PC speaker",
5081
        0,
5082
        1,
5083
        { .init_isa = pcspk_audio_init }
5084
    },
5085
#endif
5086
    {
5087
        "sb16",
5088
        "Creative Sound Blaster 16",
5089
        0,
5090
        1,
5091
        { .init_isa = SB16_init }
5092
    },
5093

    
5094
#ifdef CONFIG_CS4231A
5095
    {
5096
        "cs4231a",
5097
        "CS4231A",
5098
        0,
5099
        1,
5100
        { .init_isa = cs4231a_init }
5101
    },
5102
#endif
5103

    
5104
#ifdef CONFIG_ADLIB
5105
    {
5106
        "adlib",
5107
#ifdef HAS_YMF262
5108
        "Yamaha YMF262 (OPL3)",
5109
#else
5110
        "Yamaha YM3812 (OPL2)",
5111
#endif
5112
        0,
5113
        1,
5114
        { .init_isa = Adlib_init }
5115
    },
5116
#endif
5117

    
5118
#ifdef CONFIG_GUS
5119
    {
5120
        "gus",
5121
        "Gravis Ultrasound GF1",
5122
        0,
5123
        1,
5124
        { .init_isa = GUS_init }
5125
    },
5126
#endif
5127

    
5128
#ifdef CONFIG_AC97
5129
    {
5130
        "ac97",
5131
        "Intel 82801AA AC97 Audio",
5132
        0,
5133
        0,
5134
        { .init_pci = ac97_init }
5135
    },
5136
#endif
5137

    
5138
    {
5139
        "es1370",
5140
        "ENSONIQ AudioPCI ES1370",
5141
        0,
5142
        0,
5143
        { .init_pci = es1370_init }
5144
    },
5145
#endif
5146

    
5147
    { NULL, NULL, 0, 0, { NULL } }
5148
};
5149

    
5150
static void select_soundhw (const char *optarg)
5151
{
5152
    struct soundhw *c;
5153

    
5154
    if (*optarg == '?') {
5155
    show_valid_cards:
5156

    
5157
        printf ("Valid sound card names (comma separated):\n");
5158
        for (c = soundhw; c->name; ++c) {
5159
            printf ("%-11s %s\n", c->name, c->descr);
5160
        }
5161
        printf ("\n-soundhw all will enable all of the above\n");
5162
        exit (*optarg != '?');
5163
    }
5164
    else {
5165
        size_t l;
5166
        const char *p;
5167
        char *e;
5168
        int bad_card = 0;
5169

    
5170
        if (!strcmp (optarg, "all")) {
5171
            for (c = soundhw; c->name; ++c) {
5172
                c->enabled = 1;
5173
            }
5174
            return;
5175
        }
5176

    
5177
        p = optarg;
5178
        while (*p) {
5179
            e = strchr (p, ',');
5180
            l = !e ? strlen (p) : (size_t) (e - p);
5181

    
5182
            for (c = soundhw; c->name; ++c) {
5183
                if (!strncmp (c->name, p, l)) {
5184
                    c->enabled = 1;
5185
                    break;
5186
                }
5187
            }
5188

    
5189
            if (!c->name) {
5190
                if (l > 80) {
5191
                    fprintf (stderr,
5192
                             "Unknown sound card name (too big to show)\n");
5193
                }
5194
                else {
5195
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
5196
                             (int) l, p);
5197
                }
5198
                bad_card = 1;
5199
            }
5200
            p += l + (e != NULL);
5201
        }
5202

    
5203
        if (bad_card)
5204
            goto show_valid_cards;
5205
    }
5206
}
5207
#endif
5208

    
5209
static void select_vgahw (const char *p)
5210
{
5211
    const char *opts;
5212

    
5213
    if (strstart(p, "std", &opts)) {
5214
        cirrus_vga_enabled = 0;
5215
        vmsvga_enabled = 0;
5216
    } else if (strstart(p, "cirrus", &opts)) {
5217
        cirrus_vga_enabled = 1;
5218
        vmsvga_enabled = 0;
5219
    } else if (strstart(p, "vmware", &opts)) {
5220
        cirrus_vga_enabled = 0;
5221
        vmsvga_enabled = 1;
5222
    } else {
5223
    invalid_vga:
5224
        fprintf(stderr, "Unknown vga type: %s\n", p);
5225
        exit(1);
5226
    }
5227
    while (*opts) {
5228
        const char *nextopt;
5229

    
5230
        if (strstart(opts, ",retrace=", &nextopt)) {
5231
            opts = nextopt;
5232
            if (strstart(opts, "dumb", &nextopt))
5233
                vga_retrace_method = VGA_RETRACE_DUMB;
5234
            else if (strstart(opts, "precise", &nextopt))
5235
                vga_retrace_method = VGA_RETRACE_PRECISE;
5236
            else goto invalid_vga;
5237
        } else goto invalid_vga;
5238
        opts = nextopt;
5239
    }
5240
}
5241

    
5242
#ifdef _WIN32
5243
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
5244
{
5245
    exit(STATUS_CONTROL_C_EXIT);
5246
    return TRUE;
5247
}
5248
#endif
5249

    
5250
static int qemu_uuid_parse(const char *str, uint8_t *uuid)
5251
{
5252
    int ret;
5253

    
5254
    if(strlen(str) != 36)
5255
        return -1;
5256

    
5257
    ret = sscanf(str, UUID_FMT, &uuid[0], &uuid[1], &uuid[2], &uuid[3],
5258
            &uuid[4], &uuid[5], &uuid[6], &uuid[7], &uuid[8], &uuid[9],
5259
            &uuid[10], &uuid[11], &uuid[12], &uuid[13], &uuid[14], &uuid[15]);
5260

    
5261
    if(ret != 16)
5262
        return -1;
5263

    
5264
    return 0;
5265
}
5266

    
5267
#define MAX_NET_CLIENTS 32
5268

    
5269
#ifndef _WIN32
5270

    
5271
static void termsig_handler(int signal)
5272
{
5273
    qemu_system_shutdown_request();
5274
}
5275

    
5276
static void termsig_setup(void)
5277
{
5278
    struct sigaction act;
5279

    
5280
    memset(&act, 0, sizeof(act));
5281
    act.sa_handler = termsig_handler;
5282
    sigaction(SIGINT,  &act, NULL);
5283
    sigaction(SIGHUP,  &act, NULL);
5284
    sigaction(SIGTERM, &act, NULL);
5285
}
5286

    
5287
#endif
5288

    
5289
int main(int argc, char **argv)
5290
{
5291
#ifdef CONFIG_GDBSTUB
5292
    int use_gdbstub;
5293
    const char *gdbstub_port;
5294
#endif
5295
    uint32_t boot_devices_bitmap = 0;
5296
    int i;
5297
    int snapshot, linux_boot, net_boot;
5298
    const char *initrd_filename;
5299
    const char *kernel_filename, *kernel_cmdline;
5300
    const char *boot_devices = "";
5301
    DisplayState *ds = &display_state;
5302
    int cyls, heads, secs, translation;
5303
    const char *net_clients[MAX_NET_CLIENTS];
5304
    int nb_net_clients;
5305
    int hda_index;
5306
    int optind;
5307
    const char *r, *optarg;
5308
    CharDriverState *monitor_hd;
5309
    const char *monitor_device;
5310
    const char *serial_devices[MAX_SERIAL_PORTS];
5311
    int serial_device_index;
5312
    const char *parallel_devices[MAX_PARALLEL_PORTS];
5313
    int parallel_device_index;
5314
    const char *loadvm = NULL;
5315
    QEMUMachine *machine;
5316
    const char *cpu_model;
5317
    const char *usb_devices[MAX_USB_CMDLINE];
5318
    int usb_devices_index;
5319
    int fds[2];
5320
    int tb_size;
5321
    const char *pid_file = NULL;
5322
    int autostart;
5323
    const char *incoming = NULL;
5324

    
5325
    LIST_INIT (&vm_change_state_head);
5326
#ifndef _WIN32
5327
    {
5328
        struct sigaction act;
5329
        sigfillset(&act.sa_mask);
5330
        act.sa_flags = 0;
5331
        act.sa_handler = SIG_IGN;
5332
        sigaction(SIGPIPE, &act, NULL);
5333
    }
5334
#else
5335
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
5336
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
5337
       QEMU to run on a single CPU */
5338
    {
5339
        HANDLE h;
5340
        DWORD mask, smask;
5341
        int i;
5342
        h = GetCurrentProcess();
5343
        if (GetProcessAffinityMask(h, &mask, &smask)) {
5344
            for(i = 0; i < 32; i++) {
5345
                if (mask & (1 << i))
5346
                    break;
5347
            }
5348
            if (i != 32) {
5349
                mask = 1 << i;
5350
                SetProcessAffinityMask(h, mask);
5351
            }
5352
        }
5353
    }
5354
#endif
5355

    
5356
    register_machines();
5357
    machine = first_machine;
5358
    cpu_model = NULL;
5359
    initrd_filename = NULL;
5360
    ram_size = 0;
5361
    vga_ram_size = VGA_RAM_SIZE;
5362
#ifdef CONFIG_GDBSTUB
5363
    use_gdbstub = 0;
5364
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
5365
#endif
5366
    snapshot = 0;
5367
    nographic = 0;
5368
    curses = 0;
5369
    kernel_filename = NULL;
5370
    kernel_cmdline = "";
5371
    cyls = heads = secs = 0;
5372
    translation = BIOS_ATA_TRANSLATION_AUTO;
5373
    monitor_device = "vc";
5374

    
5375
    serial_devices[0] = "vc:80Cx24C";
5376
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
5377
        serial_devices[i] = NULL;
5378
    serial_device_index = 0;
5379

    
5380
    parallel_devices[0] = "vc:640x480";
5381
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5382
        parallel_devices[i] = NULL;
5383
    parallel_device_index = 0;
5384

    
5385
    usb_devices_index = 0;
5386

    
5387
    nb_net_clients = 0;
5388
    nb_drives = 0;
5389
    nb_drives_opt = 0;
5390
    hda_index = -1;
5391

    
5392
    nb_nics = 0;
5393

    
5394
    tb_size = 0;
5395
    autostart= 1;
5396

    
5397
    optind = 1;
5398
    for(;;) {
5399
        if (optind >= argc)
5400
            break;
5401
        r = argv[optind];
5402
        if (r[0] != '-') {
5403
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
5404
        } else {
5405
            const QEMUOption *popt;
5406

    
5407
            optind++;
5408
            /* Treat --foo the same as -foo.  */
5409
            if (r[1] == '-')
5410
                r++;
5411
            popt = qemu_options;
5412
            for(;;) {
5413
                if (!popt->name) {
5414
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
5415
                            argv[0], r);
5416
                    exit(1);
5417
                }
5418
                if (!strcmp(popt->name, r + 1))
5419
                    break;
5420
                popt++;
5421
            }
5422
            if (popt->flags & HAS_ARG) {
5423
                if (optind >= argc) {
5424
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
5425
                            argv[0], r);
5426
                    exit(1);
5427
                }
5428
                optarg = argv[optind++];
5429
            } else {
5430
                optarg = NULL;
5431
            }
5432

    
5433
            switch(popt->index) {
5434
            case QEMU_OPTION_M:
5435
                machine = find_machine(optarg);
5436
                if (!machine) {
5437
                    QEMUMachine *m;
5438
                    printf("Supported machines are:\n");
5439
                    for(m = first_machine; m != NULL; m = m->next) {
5440
                        printf("%-10s %s%s\n",
5441
                               m->name, m->desc,
5442
                               m == first_machine ? " (default)" : "");
5443
                    }
5444
                    exit(*optarg != '?');
5445
                }
5446
                break;
5447
            case QEMU_OPTION_cpu:
5448
                /* hw initialization will check this */
5449
                if (*optarg == '?') {
5450
/* XXX: implement xxx_cpu_list for targets that still miss it */
5451
#if defined(cpu_list)
5452
                    cpu_list(stdout, &fprintf);
5453
#endif
5454
                    exit(0);
5455
                } else {
5456
                    cpu_model = optarg;
5457
                }
5458
                break;
5459
            case QEMU_OPTION_initrd:
5460
                initrd_filename = optarg;
5461
                break;
5462
            case QEMU_OPTION_hda:
5463
                if (cyls == 0)
5464
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
5465
                else
5466
                    hda_index = drive_add(optarg, HD_ALIAS
5467
                             ",cyls=%d,heads=%d,secs=%d%s",
5468
                             0, cyls, heads, secs,
5469
                             translation == BIOS_ATA_TRANSLATION_LBA ?
5470
                                 ",trans=lba" :
5471
                             translation == BIOS_ATA_TRANSLATION_NONE ?
5472
                                 ",trans=none" : "");
5473
                 break;
5474
            case QEMU_OPTION_hdb:
5475
            case QEMU_OPTION_hdc:
5476
            case QEMU_OPTION_hdd:
5477
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
5478
                break;
5479
            case QEMU_OPTION_drive:
5480
                drive_add(NULL, "%s", optarg);
5481
                break;
5482
            case QEMU_OPTION_mtdblock:
5483
                drive_add(optarg, MTD_ALIAS);
5484
                break;
5485
            case QEMU_OPTION_sd:
5486
                drive_add(optarg, SD_ALIAS);
5487
                break;
5488
            case QEMU_OPTION_pflash:
5489
                drive_add(optarg, PFLASH_ALIAS);
5490
                break;
5491
            case QEMU_OPTION_snapshot:
5492
                snapshot = 1;
5493
                break;
5494
            case QEMU_OPTION_hdachs:
5495
                {
5496
                    const char *p;
5497
                    p = optarg;
5498
                    cyls = strtol(p, (char **)&p, 0);
5499
                    if (cyls < 1 || cyls > 16383)
5500
                        goto chs_fail;
5501
                    if (*p != ',')
5502
                        goto chs_fail;
5503
                    p++;
5504
                    heads = strtol(p, (char **)&p, 0);
5505
                    if (heads < 1 || heads > 16)
5506
                        goto chs_fail;
5507
                    if (*p != ',')
5508
                        goto chs_fail;
5509
                    p++;
5510
                    secs = strtol(p, (char **)&p, 0);
5511
                    if (secs < 1 || secs > 63)
5512
                        goto chs_fail;
5513
                    if (*p == ',') {
5514
                        p++;
5515
                        if (!strcmp(p, "none"))
5516
                            translation = BIOS_ATA_TRANSLATION_NONE;
5517
                        else if (!strcmp(p, "lba"))
5518
                            translation = BIOS_ATA_TRANSLATION_LBA;
5519
                        else if (!strcmp(p, "auto"))
5520
                            translation = BIOS_ATA_TRANSLATION_AUTO;
5521
                        else
5522
                            goto chs_fail;
5523
                    } else if (*p != '\0') {
5524
                    chs_fail:
5525
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
5526
                        exit(1);
5527
                    }
5528
                    if (hda_index != -1)
5529
                        snprintf(drives_opt[hda_index].opt,
5530
                                 sizeof(drives_opt[hda_index].opt),
5531
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
5532
                                 0, cyls, heads, secs,
5533
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
5534
                                         ",trans=lba" :
5535
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
5536
                                     ",trans=none" : "");
5537
                }
5538
                break;
5539
            case QEMU_OPTION_nographic:
5540
                nographic = 1;
5541
                break;
5542
#ifdef CONFIG_CURSES
5543
            case QEMU_OPTION_curses:
5544
                curses = 1;
5545
                break;
5546
#endif
5547
            case QEMU_OPTION_portrait:
5548
                graphic_rotate = 1;
5549
                break;
5550
            case QEMU_OPTION_kernel:
5551
                kernel_filename = optarg;
5552
                break;
5553
            case QEMU_OPTION_append:
5554
                kernel_cmdline = optarg;
5555
                break;
5556
            case QEMU_OPTION_cdrom:
5557
                drive_add(optarg, CDROM_ALIAS);
5558
                break;
5559
            case QEMU_OPTION_boot:
5560
                boot_devices = optarg;
5561
                /* We just do some generic consistency checks */
5562
                {
5563
                    /* Could easily be extended to 64 devices if needed */
5564
                    const char *p;
5565
                    
5566
                    boot_devices_bitmap = 0;
5567
                    for (p = boot_devices; *p != '\0'; p++) {
5568
                        /* Allowed boot devices are:
5569
                         * a b     : floppy disk drives
5570
                         * c ... f : IDE disk drives
5571
                         * g ... m : machine implementation dependant drives
5572
                         * n ... p : network devices
5573
                         * It's up to each machine implementation to check
5574
                         * if the given boot devices match the actual hardware
5575
                         * implementation and firmware features.
5576
                         */
5577
                        if (*p < 'a' || *p > 'q') {
5578
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
5579
                            exit(1);
5580
                        }
5581
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
5582
                            fprintf(stderr,
5583
                                    "Boot device '%c' was given twice\n",*p);
5584
                            exit(1);
5585
                        }
5586
                        boot_devices_bitmap |= 1 << (*p - 'a');
5587
                    }
5588
                }
5589
                break;
5590
            case QEMU_OPTION_fda:
5591
            case QEMU_OPTION_fdb:
5592
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
5593
                break;
5594
#ifdef TARGET_I386
5595
            case QEMU_OPTION_no_fd_bootchk:
5596
                fd_bootchk = 0;
5597
                break;
5598
#endif
5599
            case QEMU_OPTION_net:
5600
                if (nb_net_clients >= MAX_NET_CLIENTS) {
5601
                    fprintf(stderr, "qemu: too many network clients\n");
5602
                    exit(1);
5603
                }
5604
                net_clients[nb_net_clients] = optarg;
5605
                nb_net_clients++;
5606
                break;
5607
#ifdef CONFIG_SLIRP
5608
            case QEMU_OPTION_tftp:
5609
                tftp_prefix = optarg;
5610
                break;
5611
            case QEMU_OPTION_bootp:
5612
                bootp_filename = optarg;
5613
                break;
5614
#ifndef _WIN32
5615
            case QEMU_OPTION_smb:
5616
                net_slirp_smb(optarg);
5617
                break;
5618
#endif
5619
            case QEMU_OPTION_redir:
5620
                net_slirp_redir(optarg);
5621
                break;
5622
#endif
5623
#ifdef HAS_AUDIO
5624
            case QEMU_OPTION_audio_help:
5625
                AUD_help ();
5626
                exit (0);
5627
                break;
5628
            case QEMU_OPTION_soundhw:
5629
                select_soundhw (optarg);
5630
                break;
5631
#endif
5632
            case QEMU_OPTION_h:
5633
                help(0);
5634
                break;
5635
            case QEMU_OPTION_m: {
5636
                uint64_t value;
5637
                char *ptr;
5638

    
5639
                value = strtoul(optarg, &ptr, 10);
5640
                switch (*ptr) {
5641
                case 0: case 'M': case 'm':
5642
                    value <<= 20;
5643
                    break;
5644
                case 'G': case 'g':
5645
                    value <<= 30;
5646
                    break;
5647
                default:
5648
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
5649
                    exit(1);
5650
                }
5651

    
5652
                /* On 32-bit hosts, QEMU is limited by virtual address space */
5653
                if (value > (2047 << 20)
5654
#ifndef USE_KQEMU
5655
                    && HOST_LONG_BITS == 32
5656
#endif
5657
                    ) {
5658
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
5659
                    exit(1);
5660
                }
5661
                if (value != (uint64_t)(ram_addr_t)value) {
5662
                    fprintf(stderr, "qemu: ram size too large\n");
5663
                    exit(1);
5664
                }
5665
                ram_size = value;
5666
                break;
5667
            }
5668
            case QEMU_OPTION_d:
5669
                {
5670
                    int mask;
5671
                    const CPULogItem *item;
5672

    
5673
                    mask = cpu_str_to_log_mask(optarg);
5674
                    if (!mask) {
5675
                        printf("Log items (comma separated):\n");
5676
                    for(item = cpu_log_items; item->mask != 0; item++) {
5677
                        printf("%-10s %s\n", item->name, item->help);
5678
                    }
5679
                    exit(1);
5680
                    }
5681
                    cpu_set_log(mask);
5682
                }
5683
                break;
5684
#ifdef CONFIG_GDBSTUB
5685
            case QEMU_OPTION_s:
5686
                use_gdbstub = 1;
5687
                break;
5688
            case QEMU_OPTION_p:
5689
                gdbstub_port = optarg;
5690
                break;
5691
#endif
5692
            case QEMU_OPTION_L:
5693
                bios_dir = optarg;
5694
                break;
5695
            case QEMU_OPTION_bios:
5696
                bios_name = optarg;
5697
                break;
5698
            case QEMU_OPTION_S:
5699
                autostart = 0;
5700
                break;
5701
            case QEMU_OPTION_k:
5702
                keyboard_layout = optarg;
5703
                break;
5704
            case QEMU_OPTION_localtime:
5705
                rtc_utc = 0;
5706
                break;
5707
            case QEMU_OPTION_vga:
5708
                select_vgahw (optarg);
5709
                break;
5710
            case QEMU_OPTION_g:
5711
                {
5712
                    const char *p;
5713
                    int w, h, depth;
5714
                    p = optarg;
5715
                    w = strtol(p, (char **)&p, 10);
5716
                    if (w <= 0) {
5717
                    graphic_error:
5718
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
5719
                        exit(1);
5720
                    }
5721
                    if (*p != 'x')
5722
                        goto graphic_error;
5723
                    p++;
5724
                    h = strtol(p, (char **)&p, 10);
5725
                    if (h <= 0)
5726
                        goto graphic_error;
5727
                    if (*p == 'x') {
5728
                        p++;
5729
                        depth = strtol(p, (char **)&p, 10);
5730
                        if (depth != 8 && depth != 15 && depth != 16 &&
5731
                            depth != 24 && depth != 32)
5732
                            goto graphic_error;
5733
                    } else if (*p == '\0') {
5734
                        depth = graphic_depth;
5735
                    } else {
5736
                        goto graphic_error;
5737
                    }
5738

    
5739
                    graphic_width = w;
5740
                    graphic_height = h;
5741
                    graphic_depth = depth;
5742
                }
5743
                break;
5744
            case QEMU_OPTION_echr:
5745
                {
5746
                    char *r;
5747
                    term_escape_char = strtol(optarg, &r, 0);
5748
                    if (r == optarg)
5749
                        printf("Bad argument to echr\n");
5750
                    break;
5751
                }
5752
            case QEMU_OPTION_monitor:
5753
                monitor_device = optarg;
5754
                break;
5755
            case QEMU_OPTION_serial:
5756
                if (serial_device_index >= MAX_SERIAL_PORTS) {
5757
                    fprintf(stderr, "qemu: too many serial ports\n");
5758
                    exit(1);
5759
                }
5760
                serial_devices[serial_device_index] = optarg;
5761
                serial_device_index++;
5762
                break;
5763
            case QEMU_OPTION_parallel:
5764
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5765
                    fprintf(stderr, "qemu: too many parallel ports\n");
5766
                    exit(1);
5767
                }
5768
                parallel_devices[parallel_device_index] = optarg;
5769
                parallel_device_index++;
5770
                break;
5771
            case QEMU_OPTION_loadvm:
5772
                loadvm = optarg;
5773
                break;
5774
            case QEMU_OPTION_full_screen:
5775
                full_screen = 1;
5776
                break;
5777
#ifdef CONFIG_SDL
5778
            case QEMU_OPTION_no_frame:
5779
                no_frame = 1;
5780
                break;
5781
            case QEMU_OPTION_alt_grab:
5782
                alt_grab = 1;
5783
                break;
5784
            case QEMU_OPTION_no_quit:
5785
                no_quit = 1;
5786
                break;
5787
#endif
5788
            case QEMU_OPTION_pidfile:
5789
                pid_file = optarg;
5790
                break;
5791
#ifdef TARGET_I386
5792
            case QEMU_OPTION_win2k_hack:
5793
                win2k_install_hack = 1;
5794
                break;
5795
#endif
5796
#ifdef USE_KQEMU
5797
            case QEMU_OPTION_no_kqemu:
5798
                kqemu_allowed = 0;
5799
                break;
5800
            case QEMU_OPTION_kernel_kqemu:
5801
                kqemu_allowed = 2;
5802
                break;
5803
#endif
5804
            case QEMU_OPTION_usb:
5805
                usb_enabled = 1;
5806
                break;
5807
            case QEMU_OPTION_usbdevice:
5808
                usb_enabled = 1;
5809
                if (usb_devices_index >= MAX_USB_CMDLINE) {
5810
                    fprintf(stderr, "Too many USB devices\n");
5811
                    exit(1);
5812
                }
5813
                usb_devices[usb_devices_index] = optarg;
5814
                usb_devices_index++;
5815
                break;
5816
            case QEMU_OPTION_smp:
5817
                smp_cpus = atoi(optarg);
5818
                if (smp_cpus < 1) {
5819
                    fprintf(stderr, "Invalid number of CPUs\n");
5820
                    exit(1);
5821
                }
5822
                break;
5823
            case QEMU_OPTION_vnc:
5824
                vnc_display = optarg;
5825
                break;
5826
            case QEMU_OPTION_no_acpi:
5827
                acpi_enabled = 0;
5828
                break;
5829
            case QEMU_OPTION_no_reboot:
5830
                no_reboot = 1;
5831
                break;
5832
            case QEMU_OPTION_no_shutdown:
5833
                no_shutdown = 1;
5834
                break;
5835
            case QEMU_OPTION_show_cursor:
5836
                cursor_hide = 0;
5837
                break;
5838
            case QEMU_OPTION_uuid:
5839
                if(qemu_uuid_parse(optarg, qemu_uuid) < 0) {
5840
                    fprintf(stderr, "Fail to parse UUID string."
5841
                            " Wrong format.\n");
5842
                    exit(1);
5843
                }
5844
                break;
5845
            case QEMU_OPTION_daemonize:
5846
                daemonize = 1;
5847
                break;
5848
            case QEMU_OPTION_option_rom:
5849
                if (nb_option_roms >= MAX_OPTION_ROMS) {
5850
                    fprintf(stderr, "Too many option ROMs\n");
5851
                    exit(1);
5852
                }
5853
                option_rom[nb_option_roms] = optarg;
5854
                nb_option_roms++;
5855
                break;
5856
            case QEMU_OPTION_semihosting:
5857
                semihosting_enabled = 1;
5858
                break;
5859
            case QEMU_OPTION_name:
5860
                qemu_name = optarg;
5861
                break;
5862
#ifdef TARGET_SPARC
5863
            case QEMU_OPTION_prom_env:
5864
                if (nb_prom_envs >= MAX_PROM_ENVS) {
5865
                    fprintf(stderr, "Too many prom variables\n");
5866
                    exit(1);
5867
                }
5868
                prom_envs[nb_prom_envs] = optarg;
5869
                nb_prom_envs++;
5870
                break;
5871
#endif
5872
#ifdef TARGET_ARM
5873
            case QEMU_OPTION_old_param:
5874
                old_param = 1;
5875
                break;
5876
#endif
5877
            case QEMU_OPTION_clock:
5878
                configure_alarms(optarg);
5879
                break;
5880
            case QEMU_OPTION_startdate:
5881
                {
5882
                    struct tm tm;
5883
                    time_t rtc_start_date;
5884
                    if (!strcmp(optarg, "now")) {
5885
                        rtc_date_offset = -1;
5886
                    } else {
5887
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
5888
                               &tm.tm_year,
5889
                               &tm.tm_mon,
5890
                               &tm.tm_mday,
5891
                               &tm.tm_hour,
5892
                               &tm.tm_min,
5893
                               &tm.tm_sec) == 6) {
5894
                            /* OK */
5895
                        } else if (sscanf(optarg, "%d-%d-%d",
5896
                                          &tm.tm_year,
5897
                                          &tm.tm_mon,
5898
                                          &tm.tm_mday) == 3) {
5899
                            tm.tm_hour = 0;
5900
                            tm.tm_min = 0;
5901
                            tm.tm_sec = 0;
5902
                        } else {
5903
                            goto date_fail;
5904
                        }
5905
                        tm.tm_year -= 1900;
5906
                        tm.tm_mon--;
5907
                        rtc_start_date = mktimegm(&tm);
5908
                        if (rtc_start_date == -1) {
5909
                        date_fail:
5910
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
5911
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
5912
                            exit(1);
5913
                        }
5914
                        rtc_date_offset = time(NULL) - rtc_start_date;
5915
                    }
5916
                }
5917
                break;
5918
            case QEMU_OPTION_tb_size:
5919
                tb_size = strtol(optarg, NULL, 0);
5920
                if (tb_size < 0)
5921
                    tb_size = 0;
5922
                break;
5923
            case QEMU_OPTION_icount:
5924
                use_icount = 1;
5925
                if (strcmp(optarg, "auto") == 0) {
5926
                    icount_time_shift = -1;
5927
                } else {
5928
                    icount_time_shift = strtol(optarg, NULL, 0);
5929
                }
5930
                break;
5931
            case QEMU_OPTION_incoming:
5932
                incoming = optarg;
5933
                break;
5934
            }
5935
        }
5936
    }
5937

    
5938
    machine->max_cpus = machine->max_cpus ?: 1; /* Default to UP */
5939
    if (smp_cpus > machine->max_cpus) {
5940
        fprintf(stderr, "Number of SMP cpus requested (%d), exceeds max cpus "
5941
                "supported by machine `%s' (%d)\n", smp_cpus,  machine->name,
5942
                machine->max_cpus);
5943
        exit(1);
5944
    }
5945

    
5946
    if (nographic) {
5947
       if (serial_device_index == 0)
5948
           serial_devices[0] = "stdio";
5949
       if (parallel_device_index == 0)
5950
           parallel_devices[0] = "null";
5951
       if (strncmp(monitor_device, "vc", 2) == 0)
5952
           monitor_device = "stdio";
5953
    }
5954

    
5955
#ifndef _WIN32
5956
    if (daemonize) {
5957
        pid_t pid;
5958

    
5959
        if (pipe(fds) == -1)
5960
            exit(1);
5961

    
5962
        pid = fork();
5963
        if (pid > 0) {
5964
            uint8_t status;
5965
            ssize_t len;
5966

    
5967
            close(fds[1]);
5968

    
5969
        again:
5970
            len = read(fds[0], &status, 1);
5971
            if (len == -1 && (errno == EINTR))
5972
                goto again;
5973

    
5974
            if (len != 1)
5975
                exit(1);
5976
            else if (status == 1) {
5977
                fprintf(stderr, "Could not acquire pidfile\n");
5978
                exit(1);
5979
            } else
5980
                exit(0);
5981
        } else if (pid < 0)
5982
            exit(1);
5983

    
5984
        setsid();
5985

    
5986
        pid = fork();
5987
        if (pid > 0)
5988
            exit(0);
5989
        else if (pid < 0)
5990
            exit(1);
5991

    
5992
        umask(027);
5993

    
5994
        signal(SIGTSTP, SIG_IGN);
5995
        signal(SIGTTOU, SIG_IGN);
5996
        signal(SIGTTIN, SIG_IGN);
5997
    }
5998
#endif
5999

    
6000
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
6001
        if (daemonize) {
6002
            uint8_t status = 1;
6003
            write(fds[1], &status, 1);
6004
        } else
6005
            fprintf(stderr, "Could not acquire pid file\n");
6006
        exit(1);
6007
    }
6008

    
6009
#ifdef USE_KQEMU
6010
    if (smp_cpus > 1)
6011
        kqemu_allowed = 0;
6012
#endif
6013
    linux_boot = (kernel_filename != NULL);
6014
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
6015

    
6016
    if (!linux_boot && net_boot == 0 &&
6017
        !machine->nodisk_ok && nb_drives_opt == 0)
6018
        help(1);
6019

    
6020
    if (!linux_boot && *kernel_cmdline != '\0') {
6021
        fprintf(stderr, "-append only allowed with -kernel option\n");
6022
        exit(1);
6023
    }
6024

    
6025
    if (!linux_boot && initrd_filename != NULL) {
6026
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
6027
        exit(1);
6028
    }
6029

    
6030
    /* boot to floppy or the default cd if no hard disk defined yet */
6031
    if (!boot_devices[0]) {
6032
        boot_devices = "cad";
6033
    }
6034
    setvbuf(stdout, NULL, _IOLBF, 0);
6035

    
6036
    init_timers();
6037
    init_timer_alarm();
6038
    if (use_icount && icount_time_shift < 0) {
6039
        use_icount = 2;
6040
        /* 125MIPS seems a reasonable initial guess at the guest speed.
6041
           It will be corrected fairly quickly anyway.  */
6042
        icount_time_shift = 3;
6043
        init_icount_adjust();
6044
    }
6045

    
6046
#ifdef _WIN32
6047
    socket_init();
6048
#endif
6049

    
6050
    /* init network clients */
6051
    if (nb_net_clients == 0) {
6052
        /* if no clients, we use a default config */
6053
        net_clients[nb_net_clients++] = "nic";
6054
#ifdef CONFIG_SLIRP
6055
        net_clients[nb_net_clients++] = "user";
6056
#endif
6057
    }
6058

    
6059
    for(i = 0;i < nb_net_clients; i++) {
6060
        if (net_client_parse(net_clients[i]) < 0)
6061
            exit(1);
6062
    }
6063
    net_client_check();
6064

    
6065
#ifdef TARGET_I386
6066
    /* XXX: this should be moved in the PC machine instantiation code */
6067
    if (net_boot != 0) {
6068
        int netroms = 0;
6069
        for (i = 0; i < nb_nics && i < 4; i++) {
6070
            const char *model = nd_table[i].model;
6071
            char buf[1024];
6072
            if (net_boot & (1 << i)) {
6073
                if (model == NULL)
6074
                    model = "ne2k_pci";
6075
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
6076
                if (get_image_size(buf) > 0) {
6077
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
6078
                        fprintf(stderr, "Too many option ROMs\n");
6079
                        exit(1);
6080
                    }
6081
                    option_rom[nb_option_roms] = strdup(buf);
6082
                    nb_option_roms++;
6083
                    netroms++;
6084
                }
6085
            }
6086
        }
6087
        if (netroms == 0) {
6088
            fprintf(stderr, "No valid PXE rom found for network device\n");
6089
            exit(1);
6090
        }
6091
    }
6092
#endif
6093

    
6094
    /* init the memory */
6095
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
6096

    
6097
    if (machine->ram_require & RAMSIZE_FIXED) {
6098
        if (ram_size > 0) {
6099
            if (ram_size < phys_ram_size) {
6100
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
6101
                                machine->name, (unsigned long long) phys_ram_size);
6102
                exit(-1);
6103
            }
6104

    
6105
            phys_ram_size = ram_size;
6106
        } else
6107
            ram_size = phys_ram_size;
6108
    } else {
6109
        if (ram_size == 0)
6110
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6111

    
6112
        phys_ram_size += ram_size;
6113
    }
6114

    
6115
    phys_ram_base = qemu_vmalloc(phys_ram_size);
6116
    if (!phys_ram_base) {
6117
        fprintf(stderr, "Could not allocate physical memory\n");
6118
        exit(1);
6119
    }
6120

    
6121
    /* init the dynamic translator */
6122
    cpu_exec_init_all(tb_size * 1024 * 1024);
6123

    
6124
    bdrv_init();
6125

    
6126
    /* we always create the cdrom drive, even if no disk is there */
6127

    
6128
    if (nb_drives_opt < MAX_DRIVES)
6129
        drive_add(NULL, CDROM_ALIAS);
6130

    
6131
    /* we always create at least one floppy */
6132

    
6133
    if (nb_drives_opt < MAX_DRIVES)
6134
        drive_add(NULL, FD_ALIAS, 0);
6135

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

    
6138
    if (nb_drives_opt < MAX_DRIVES)
6139
        drive_add(NULL, SD_ALIAS);
6140

    
6141
    /* open the virtual block devices */
6142

    
6143
    for(i = 0; i < nb_drives_opt; i++)
6144
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
6145
            exit(1);
6146

    
6147
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
6148
    register_savevm_live("ram", 0, 3, ram_save_live, NULL, ram_load, NULL);
6149

    
6150
    /* terminal init */
6151
    memset(&display_state, 0, sizeof(display_state));
6152
    if (nographic) {
6153
        if (curses) {
6154
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
6155
            exit(1);
6156
        }
6157
        /* nearly nothing to do */
6158
        dumb_display_init(ds);
6159
    } else if (vnc_display != NULL) {
6160
        vnc_display_init(ds);
6161
        if (vnc_display_open(ds, vnc_display) < 0)
6162
            exit(1);
6163
    } else
6164
#if defined(CONFIG_CURSES)
6165
    if (curses) {
6166
        curses_display_init(ds, full_screen);
6167
    } else
6168
#endif
6169
    {
6170
#if defined(CONFIG_SDL)
6171
        sdl_display_init(ds, full_screen, no_frame);
6172
#elif defined(CONFIG_COCOA)
6173
        cocoa_display_init(ds, full_screen);
6174
#else
6175
        dumb_display_init(ds);
6176
#endif
6177
    }
6178

    
6179
#ifndef _WIN32
6180
    /* must be after terminal init, SDL library changes signal handlers */
6181
    termsig_setup();
6182
#endif
6183

    
6184
    /* Maintain compatibility with multiple stdio monitors */
6185
    if (!strcmp(monitor_device,"stdio")) {
6186
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
6187
            const char *devname = serial_devices[i];
6188
            if (devname && !strcmp(devname,"mon:stdio")) {
6189
                monitor_device = NULL;
6190
                break;
6191
            } else if (devname && !strcmp(devname,"stdio")) {
6192
                monitor_device = NULL;
6193
                serial_devices[i] = "mon:stdio";
6194
                break;
6195
            }
6196
        }
6197
    }
6198
    if (monitor_device) {
6199
        monitor_hd = qemu_chr_open("monitor", monitor_device);
6200
        if (!monitor_hd) {
6201
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6202
            exit(1);
6203
        }
6204
        monitor_init(monitor_hd, !nographic);
6205
    }
6206

    
6207
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6208
        const char *devname = serial_devices[i];
6209
        if (devname && strcmp(devname, "none")) {
6210
            char label[32];
6211
            snprintf(label, sizeof(label), "serial%d", i);
6212
            serial_hds[i] = qemu_chr_open(label, devname);
6213
            if (!serial_hds[i]) {
6214
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
6215
                        devname);
6216
                exit(1);
6217
            }
6218
            if (strstart(devname, "vc", 0))
6219
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6220
        }
6221
    }
6222

    
6223
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6224
        const char *devname = parallel_devices[i];
6225
        if (devname && strcmp(devname, "none")) {
6226
            char label[32];
6227
            snprintf(label, sizeof(label), "parallel%d", i);
6228
            parallel_hds[i] = qemu_chr_open(label, devname);
6229
            if (!parallel_hds[i]) {
6230
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6231
                        devname);
6232
                exit(1);
6233
            }
6234
            if (strstart(devname, "vc", 0))
6235
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6236
        }
6237
    }
6238

    
6239
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
6240
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
6241

    
6242
    /* init USB devices */
6243
    if (usb_enabled) {
6244
        for(i = 0; i < usb_devices_index; i++) {
6245
            if (usb_device_add(usb_devices[i]) < 0) {
6246
                fprintf(stderr, "Warning: could not add USB device %s\n",
6247
                        usb_devices[i]);
6248
            }
6249
        }
6250
    }
6251

    
6252
    if (display_state.dpy_refresh) {
6253
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
6254
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
6255
    }
6256

    
6257
#ifdef CONFIG_GDBSTUB
6258
    if (use_gdbstub) {
6259
        /* XXX: use standard host:port notation and modify options
6260
           accordingly. */
6261
        if (gdbserver_start(gdbstub_port) < 0) {
6262
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
6263
                    gdbstub_port);
6264
            exit(1);
6265
        }
6266
    }
6267
#endif
6268

    
6269
    if (loadvm)
6270
        do_loadvm(loadvm);
6271

    
6272
    if (incoming) {
6273
        autostart = 0; /* fixme how to deal with -daemonize */
6274
        qemu_start_incoming_migration(incoming);
6275
    }
6276

    
6277
    {
6278
        /* XXX: simplify init */
6279
        read_passwords();
6280
        if (autostart) {
6281
            vm_start();
6282
        }
6283
    }
6284

    
6285
    if (daemonize) {
6286
        uint8_t status = 0;
6287
        ssize_t len;
6288
        int fd;
6289

    
6290
    again1:
6291
        len = write(fds[1], &status, 1);
6292
        if (len == -1 && (errno == EINTR))
6293
            goto again1;
6294

    
6295
        if (len != 1)
6296
            exit(1);
6297

    
6298
        chdir("/");
6299
        TFR(fd = open("/dev/null", O_RDWR));
6300
        if (fd == -1)
6301
            exit(1);
6302

    
6303
        dup2(fd, 0);
6304
        dup2(fd, 1);
6305
        dup2(fd, 2);
6306

    
6307
        close(fd);
6308
    }
6309

    
6310
    main_loop();
6311
    quit_timers();
6312
    net_cleanup();
6313

    
6314
    return 0;
6315
}